Search code examples
pythonpython-3.xsmtplib

smtplib timing out with correct credentials for office 365


I am creating a python script that uses our company's office 365 email domain to send emails.

However, I cannot establish a connection.

import smtplib

mailserver = smtplib.SMTP('smtp.office365.com',535, timeout=120)
mailserver.ehlo()
mailserver.starttls()
mailserver.login('user@company.com','Password')
mailserver.sendmail('another.user@company.com')
mailserver.quit()

The error I am getting is:

TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

I have absolutely no idea where I am going wrong. After reviewing the documentation it my code seems perfect.

Any input is greatly appreciated!


Solution

  • I found the answer for anyone else looking.

    I just had to enable SMTP on my O365 email: https://learn.microsoft.com/en-us/exchange/clients-and-mobile-in-exchange-online/authenticated-client-smtp-submission#:~:text=Open%20the%20Microsoft%20365%20admin,%3D%20disabled%2C%20checked%20%3D%20enabled.

    Luckily I had admin access here but you may need to contact your office 365 admin if you can't