【问题标题】:No email sending using smtplib - python没有使用 smtplib 发送电子邮件 - python
【发布时间】:2014-01-31 07:07:18
【问题描述】:
import smtplib

sender = 'den.callanan@gmail.com'
receiver = ['callanden@gmail.com']

message = """From: From Person <den.callanan@gmail.com>
To: To Person <callanden@gmail.com>
Subject: SMTP e-mail test

This is a test e-mail message.
"""

try:

    print("trying host and port...")

    smtpObj = smtplib.SMTP('smtp.gmail.com', 465)

    print("sending mail...")

    smtpObj.sendmail(sender, receiver, message)

    print("Succesfully sent email")

except SMTPException:

    print("Error: unable to send email")

我在同一台服务器 (gmail) 上创建了两个新的电子邮件帐户(上图)来测试这一点。 它达到了打印“正在尝试主机和端口...”的地步,并且不再继续。所以问题应该出在我输入的地址和端口号上。但根据 gmail 的外发邮件服务器详细信息,我已正确输入它们。有什么想法吗?

如果我删除端口号或尝试其他端口号,例如 587,则会收到错误消息。

【问题讨论】:

  • 启用来自smtplib 的诊断,这样您就可以看到哪里出了问题。在这个细节层次上,我们所能做的就是猜测。我的猜测是 Gmail 需要身份验证,在这种情况下,请查看任何近乎重复的帝国垃圾。

标签: python email smtp gmail smtplib


【解决方案1】:

Sending email via Gmail's SMTP servers requires TLS 和身份验证。要进行身份验证,您需要make an application-specific password for your account

这个脚本对我有用(尽管我使用了自己的 GMail 电子邮件地址和自己的应用程序专用密码)。在下面的代码中,将 APPLICATION_SPECIFIC_PASSWORD 替换为您生成的密码。

import smtplib

sender = 'den.callanan@gmail.com'
receiver = ['callanden@gmail.com']

message = """From: From Person <den.callanan@gmail.com>
To: To Person <callanden@gmail.com>
Subject: SMTP e-mail test

This is a test e-mail message.
"""

try:
    print("trying host and port...")

    smtpObj = smtplib.SMTP_SSL('smtp.gmail.com', 465)
    smtpObj.login("den.callanan@gmail.com", "APPLICATION_SPECIFIC_PASSWORD")

    print("sending mail...")

    smtpObj.sendmail(sender, receiver, message)

    print("Succesfully sent email")

except smtplib.SMTPException:
    print("Error: unable to send email")
    import traceback
    traceback.print_exc()

(为了调试问题,我在except语句中添加了print-traceback代码。异常有关于如何让它工作的具体信息。访问端口465时代码挂起,我认为是因为TLS协商的问题,所以我不得不尝试使用端口 587;然后我得到了很好的调试信息,解释了该怎么做。)

You can see info on the SMTP_SSL object here.

【讨论】:

    猜你喜欢
    • 2021-04-26
    • 1970-01-01
    • 2023-02-11
    • 2011-02-12
    • 2018-12-09
    • 2015-09-07
    • 2017-09-20
    • 2021-06-19
    • 1970-01-01
    相关资源
    最近更新 更多