【问题标题】:Unable to send email from python无法从 python 发送电子邮件
【发布时间】:2016-04-09 01:46:21
【问题描述】:

我正在使用以下代码从本地主机中的 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 文档。

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

我想知道,除了这段代码,我是否需要在其他任何地方进行一些其他配置。

我没有看到任何错误。

我正在使用python 2.7

这是Sending HTML email using Python中的解决方案

【问题讨论】:

  • 您的代码正在尝试使用 SMTP 服务器在 localhost 的 5000 端口上发送电子邮件。
  • @TimothéeJeannin 抱歉,我对这一切都很陌生,你能告诉我该怎么做吗?

标签: python email localhost


【解决方案1】:

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

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

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

我从http://email.about.com/od/accessinggmail/f/Gmail_SMTP_Settings.htm得到它们

另外,您需要确保在执行此操作时不要启用 gmail 的 2 步身份验证,否则会失败。此外,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"

【讨论】:

  • 我收到了smtplib.SMTPAuthenticationError
  • 您使用server.login() 登录了吗?如果您不登录 gmail 会告诉您未经授权从您的帐户发送邮件。
  • 其实我已经登录了我的gmail账号
  • 您在哪里登录了您的 gmail 帐户?如果您在浏览器中登录您的 gmail 帐户,这不算数 - 因为 python 脚本不知道它。 python脚本需要给gmail你的密码才能被允许发送电子邮件。
  • 我刚收到一封来自 gmail 的 sign-in attempt prevented 邮件。我需要在gmail中设置一些权限吗?我正确地传递了usernamepassword
猜你喜欢
  • 2015-03-24
  • 2012-03-08
  • 2012-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-09
  • 2018-11-08
  • 2016-06-21
相关资源
最近更新 更多