Python:发送电子邮件时,始终在子句中阻止:smtpserver = smtplib.SMTP ("smtp.gmail.com",587)

标签 python email smtp gmail

我正在编写一个 Python 程序来发送电子邮件。但是每次执行子句时:

smtpserver = smtplib.SMTP("smtp.gmail.com",587)

它会在这里阻塞并始终保持执行状态,没有任何提示和错误。我不知道为什么。谁能帮助我?

代码如下:
导入 smtplib
to = 'toemail@gmail.com'
gmail_user = 'user@gmail.com'
gmail_pwd = 'password'
smtpserver = smtplib.SMTP("smtp.gmail.com",587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo
smtpserver.login(gmail_user, gmail_pwd)
header = 'To:' + to + '\n' + 'From: ' + gmail_user + '\n' + 'Subject:testing \n'
print header
msg = header + '\n this is test msg from mkyong.com \n\n'
smtpserver.sendmail(gmail_user, to, msg)
print 'done!'
smtpserver.close()

最佳答案

连接可能存在一些问题(可能它被您的代理或防火墙阻止了?)并且超时可能非常大,您看不到它的进一步发展。
The documentation of smtplib.SMTP 说:

class smtplib.SMTP([host[, port[, local_hostname[, timeout]]]])

(...) An SMTPConnectError is raised if the specified host doesn’t respond correctly. The optional timeout parameter specifies a timeout in seconds for blocking operations like the connection attempt (if not specified, the global default timeout setting will be used).


尝试自己指定超时:
smtpserver = smtplib.SMTP("smtp.gmail.com", 587, timeout=30)

关于Python:发送电子邮件时,始终在子句中阻止:smtpserver = smtplib.SMTP ("smtp.gmail.com",587),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11981907/

相关文章:

python - 运算符优先级对字符串的工作方式与对数字的工作方式相同吗?

c# - 如何检查收件人电子邮件地址域是否已实现 TLS?

java - 发件人地址不正确

python - 使用 Python 创建 D3 嵌套 JSON 数据

网络中的远程计算机无法访问 Python Flask 应用程序

php - 如何在 PHP 中获取值 contentEditable

Python 套接字.gaierror : [Errno 11001] getaddrinfo failed

linux - Jenkins : "javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;"

ruby-on-rails - Rails 和 Gmail SMTP,如何使用自定义发件人地址

python - 有关为Vexed关卡编写解算器的建议