没有使用smtplib发送电子邮件 - python

时间:2014-01-12 14:49:07

标签: python email smtp gmail smtplib

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,我提供了错误。

1 个答案:

答案 0 :(得分: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.