无法从 python 发送电子邮件

Unable to send email from python

我正在使用以下代码从本地主机中的 python 程序发送电子邮件,

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

me = "tonyr1291@gmail.com"
you = "testaccount@gmail.com"


msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"
msg['From'] = me
msg['To'] = you

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> you wanted.
    </p>
  </body>
</html>
"""

part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')

msg.attach(part1)
msg.attach(part2)

s = smtplib.SMTP('localhost',5000)
s.sendmail(me, you, msg.as_string())
s.quit()

此代码来自 python 文档。

当我 运行 此代码时,它一直 运行ning 但没有发送电子邮件。

我想知道,除了这段代码,我还需要在其他地方做一些其他配置吗?

我没有看到任何错误。

我正在使用 python 2.7

这在 Sending HTML email using Python

中作为解决方案给出

您似乎在使用 gmail id。现在,SMTP 服务器不是您的龙卷风服务器。它是电子邮件提供商的服务器。

您可以在线搜索gmail服务器的smtp设置,得到如下信息:

  • 服务器名称:smtp.gmail.com
  • SSL 服务器端口:465
  • TLS 服务器端口:587

我从http://email.about.com/od/accessinggmail/f/Gmail_SMTP_Settings.htm

那里得到了它们

另外,您需要确保在执行此操作时没有启用gmail 的两步验证,否则会失败。此外,gmail 可能特别要求您发送其他内容,例如 ehlo 和 starttls。您可以在此处找到带有完整示例的先前答案:How to send an email with Gmail as provider using Python?

    import smtplib

    gmail_user = user
    gmail_pwd = pwd
    FROM = user
    TO = recipient if type(recipient) is list else [recipient]
    SUBJECT = subject
    TEXT = body

    # Prepare actual message
    message = """\From: %s\nTo: %s\nSubject: %s\n\n%s
    """ % (FROM, ", ".join(TO), SUBJECT, TEXT)
    try:
        server = smtplib.SMTP("smtp.gmail.com", 587)
        server.ehlo()
        server.starttls()
        server.login(gmail_user, gmail_pwd)
        server.sendmail(FROM, TO, message)
        server.close()
        print 'successfully sent the mail'
    except:
        print "failed to send mail"