【发布时间】:2018-01-22 08:22:00
【问题描述】:
我在尝试使用 python sendmail 发送电子邮件时出错。这是我的python代码: (Pas d'objet)
#! /usr/bin/python
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# me == my email address
# you == recipient's email address
me = "my@email.com"
you = "email@gmail.com"
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"
msg['From'] = me
msg['To'] = you
# Create the body of the message (a plain-text and an HTML version).
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org"
html = """\
<html>
<head></head>
<body>
<p>Hi!<br>
How are you?<br>
Here is the <a href="[http://www.python.org">link</a]http://www.python.org">link</a> you wanted.
</p>
</body>
</html>
"""
# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)
# Send the message via local SMTP server.
s = smtplib.SMTP('localhost')
# sendmail function takes 3 arguments: sender's address, recipient's address
# and message to send - here it is sent as one string.
s.sendmail(me, you, msg.as_string())
s.quit()
当我发送这封电子邮件时,我遇到了这个错误:
Traceback (most recent call last):
File "./mail.py", line 47, in <module>
s.sendmail(me, you, msg.as_string())
File "/usr/lib/python2.7/smtplib.py", line 747, in sendmail
raise SMTPRecipientsRefused(senderrs)
smtplib.SMTPRecipientsRefused: {'email@gmail.com': (454, '4.7.1 <email@gmail.com>: Relay access denied')}
我真的不知道为什么这在生产环境中不起作用,因为它在测试环境中工作。请帮忙理解一下好吗?
【问题讨论】:
-
您是否尝试通过 gmail 发送电子邮件?还是您实际上有
localSMTP 服务器?看到这个答案 - stackoverflow.com/questions/10147455/… -
@droravr 不,我只是希望能够向 Gmail 或其他人发送电子邮件
-
您需要一个 SMTP 服务器来发送电子邮件,如果您有帐户,则使用 Gmail 或其他具有相同性质的东西。
-
@droravr Gmail 只是一个例子。在我的脚本中,我使用了我公司的本地邮件服务器。我有一台测试机器,它可以正常工作。但不是在生产环境中。基本上,我只需要发送带有
sendmail的HTML 电子邮件。这似乎是最简单的方法。 -
哦,当我询问您是否有本地服务器时,您回答“否”时让我感到困惑。测试机上,你也是发给
email@gmail.com吗?