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),则会出现错误。
请您参考如下方法:
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;然后我得到了很好的调试信息,解释了要做什么。)
