可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I am writing a Python program to send an email. But every time when executing the clause:
smtpserver = smtplib.SMTP("smtp.gmail.com",587)
it will block here and always stay the executing status without any prompts and errors. I don't know why. And can anyone help me?
The code is as following: import 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()
回答1:
Maybe I am 4 years late, but this is what worked for me and might help someone else!
server = smtplib.SMTP("smtp.gmail.com", 587, None, 30)
回答2:
There may be some issue with the connection (maybe it is being blocked by your proxy or firewall?) and the timeout may be pretty big for you to do not see it going further.
The documentation of smtplib.SMTP
says:
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).
Try specifying the timeout yourself:
smtpserver = smtplib.SMTP("smtp.gmail.com", 587, timeout=30)
回答3:
For reference, cpython smtplib is blocking. That is, it blocks the GIL (ie Python) while connecting. Despite the claims the GIL is released on I/O, it is only released on some I/O, and SMTP connections are not such. To make it async, you need to hand the mail send to another process or thread, depending on your situation.