我正在编写一个 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 specifiedhost
doesn’t respond correctly. The optionaltimeout
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/