Python: when sending email, always blocked in the clause: smtpserver = smtplib.SMTP(“smtp.gmail.com”,587)

孤者浪人 提交于 2019-12-02 01:06:43

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)

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)

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!