Python smtp.connect 无法连接

标签 python email smtp

我正在编写一个小的 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/

相关文章:

python - 导入错误: Using the `Trainer` with `PyTorch` requires `accelerate`

php - 在 CakePHP 和 Postfix 中处理电子邮件退回

c# - 当 SMTP 服务器具有有效证书时获取 "The remote certificate is invalid according to the validation procedure"

github - 使用 Github Actions 发送电子邮件

c++ - 在 Linux 上使用 C++ 中的 SMTP 发送邮件

php - 什么是 SMTP 电子邮件的好 php 类?

python - 计数变量未在递归函数调用中更新

python - 从子列表中检索升序整数的所有可能组合

laravel - 如何通过gmail smtp使用laravel发送邮件?

python - 在Scrapy中创建可编辑的CrawlSpider规则