Python: 邮件问题
我正在使用下面的脚本给自己发送一封邮件,这个脚本运行得很好,没有错误,但我实际上没有收到邮件。
import smtplib
sender = 'foo@hotmail.com'
receivers = ['foo@hotmail.com']
message = """From: From Person <foo@hotmail.com>
To: To Person <foo@hotmail.com>
Subject: SMTP e-mail test
This is a test e-mail message.
"""
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"
编辑
这个脚本的名字是 test.py
4 个回答
1
杰夫·阿特伍德在去年的四月写了一篇博客文章,可能对你有一些帮助。
2
我想补充一下Klark的精彩回答。当我尝试以下代码时:
Encoders.encode_base64(part)
我收到了一个错误提示
NameError: global name 'Encoders' is not defined
正确的写法应该是
encoders.encode_base64(msg)
5
为什么你要把localhost当作SMTP?
如果你在用hotmail的话,你需要用你的hotmail账号,提供密码,输入端口和SMTP服务器等信息。
这里有你需要的所有内容:http://techblissonline.com/hotmail-pop3-and-smtp-settings/
补充:如果你用的是gmail,这里有个例子:
def mail(to, subject, text):
msg = MIMEMultipart()
msg['From'] = gmail_user
msg['To'] = to
msg['Subject'] = subject
msg.attach(MIMEText(text))
part = MIMEBase('application', 'octet-stream')
Encoders.encode_base64(part)
msg.attach(part)
mailServer = smtplib.SMTP("smtp.gmail.com", 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(gmail_user, gmail_pwd)
mailServer.sendmail(gmail_user, to, msg.as_string())
# Should be mailServer.quit(), but that crashes...
mailServer.close()