I have a custom Microsoft 365 business email domain and an email account of myemail@secretdomain.ca
. Using the Python code below I am not able to send an email to another user due to an SMTP authentication failure:
import smtplib, ssl
port = 587 # For starttls
smtp_server = 'smtp.office365.com'
sender_email = 'myemail@secretdomain.ca'
receiver_email = 'receiver@hotmail.ca'
password = 'mysecretpassword'
message = """\
Subject: Hi there
This message is sent from Python."""
context = ssl.create_default_context()
with smtplib.SMTP(smtp_server, port) as server:
server.ehlo() # Can be omitted
server.starttls(context=context)
server.ehlo() # Can be omitted
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message)`
The exact error is as follows:
smtplib.SMTPAuthenticationError: (535, b'5.7.139 Authentication unsuccessful, the request did not meet the criteria to be authenticated successfully. Contact your administrator
Things I've tried:
- Checked that the email and password are correct.
- Verified that there is no firewall issue and that there is nothing wrong with the code above by swapping the sender and receiver emails (and of course changing the password too) - in this case it works normally and the authentication succeeds. Since the domain was hotmail.ca the SMTP server was changed to
smtp-mail.outlook.com
too. - Verified SMTP settings via outlook settings -> Mail -> Sync Email -> SMTP setting
- Checked the Settings -> Mail Flow -> Turn Off SMTP AUTH Protocol (unchecked)
- Checked the Active Users ->
myemail@secretdomain.ca
-> Mail -> Managed Email Apps -> Authenticated SMTP (checked) - Checked that multifactor authentication is disabled, thereby not needing an app key
- Added a connector from my organizations email server to office 365 with a domain name of *.secretdomain.ca
As you can see I've gone above and beyond what one should reasonably need to do to get SMTP functional, but Microsoft does not seem to go above and beyond to make sure their service is easy to use. What have I (or they) done wrong?