我正在编写一个小的 python 脚本来发送电子邮件,但我的代码甚至无法通过 smtp 连接。我正在使用以下代码,但我从未看到“已连接”。此外,我没有看到抛出异常,所以我认为它卡在某些东西上。
import os
import platform
import smtplib
#Define our SMTP server. We use gmail. Try to connect.
try:
server = smtplib.SMTP()
print "Defined server"
server.connect("smtp.gmail.com",465)
print "Connected"
server.ehlo()
server.starttls()
server.ehlo()
print "Complete Initiation"
except Exception, R:
print R
最佳答案
端口 465 用于 SMTPS;要连接到 SMTPS,您需要使用 SMTP_SSL;然而SMTPS is deprecated ,并且您应该使用 587(带有 starttls
)。 (还有see this answer about SMTPS and MSA)。
其中任何一个都可以:587 与 starttls
:
server = smtplib.SMTP()
print("Defined server")
server.connect("smtp.gmail.com",587)
print("Connected")
server.ehlo()
server.starttls()
server.ehlo()
或 465 与 SMTP_SSL
。
server = smtplib.SMTP_SSL()
print("Defined server")
server.connect("smtp.gmail.com", 465)
print("Connected")
server.ehlo()
关于Python smtp.connect 无法连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28949303/