Python:电子邮件问题

2024-05-19 18:41:12 发布

您现在位置: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


Tags: tofromtest脚本commessagefoo电子邮件
3条回答

我有件事要补充克拉克的伟大回答。当我尝试:

Encoders.encode_base64(part)

我收到一个错误

NameError: global name 'Encoders' is not defined

应该是

encoders.encode_base64(msg)

https://docs.python.org/2/library/email-examples.html

为什么使用本地主机作为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()

杰夫·阿特伍德去年4月写的blog post可能会有所帮助。

相关问题 更多 >