Errors when using SMTPLIB SSL email with a 365 email address

独自空忆成欢 提交于 2020-01-25 07:55:07

问题


context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.office365.com", 587, context=context) as server:

(587) When I run this I get an SSL error: [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1056).

(465) I get a timeout error.

I tried using ports 465 and 587. I get different errors when I use different ports. I did try 995 just for the heck of it and still no luck. If I use my gmail account, I have no issues.

Is there something I need to do to my email account so it works. I also tried .SMTP() and still no luck.

smtp = smtplib.SMTP("smtp.office365.com",587)
context = ssl.create_default_context()
with smtp.starttls(context=context) as server:
    server.login(from_address, password)

    for i, r in newhire[mask].iterrows():     
            server.sendmail(
                from_address,
                r["Email"],
                message.format(Employee=r["Employee Name"],
                   StartDate=r["StartDate"],
                               PC=r["PC"],
                               Title=r["Title"],
                               Email=r["Email"], 


                )
            )


回答1:


From the documentation of SMTP_SSL:

SMTP_SSL should be used for situations where SSL is required from the beginning of the connection and using starttls() is not appropriate.

Thus, SMTP_SSL is for implicit SMTP and the common port for this is 465. Port 587 is instead used for explicit SMTP where a plain connect is done and later an upgrade to SSL with the STARTTLS command.

What happens here is that the client tries to speak SSL/TLS to a server which does not expect SSL/TLS at this stage and thus replies with non-TLS data. These get interpreted as TlS nonetheless which results in this strange [SSL: WRONG_VERSION_NUMBER].

To fix this either use port 465 (and not 587) with SMTP_SSL (not supported by Office365) or use port 587 but with starttls:

with smtplib.SMTP("smtp.office365.com", 587) as server:
     server.starttls(context=context)


来源:https://stackoverflow.com/questions/59635516/errors-when-using-smtplib-ssl-email-with-a-365-email-address

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