Python smtp.connect 连接不上

Python smtp.connect does not connect

我正在编写一个 python 小脚本来发送电子邮件,但我的代码甚至无法通过 smtp 连接。我正在使用以下代码,但我从未看到 "Connected"。此外,我没有看到抛出异常,所以我认为它挂在某些东西上。

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, and you should be using 587 (with starttls). (Also see this answer about SMTPS and MSA).

这些都可以工作:587 with 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()