Sending Email from Outlook365 with Yagmail in Python (Allowing SMTP access)

2.4k Views Asked by At

I can send emails via a Gmail account using the Yagmail module in Python but I am getting a SMTPAuthenticationError when I try to do it with an Outlook email address.

Gmail required me to allow "less secure apps" to access my account but I can't find any such option for Outlook365.

This is my code for Gmail with Yagmail:

import keyring
keyring.set_password('yagmail', '[email protected]', 'mypassword')

import yagmail
FROM = "[email protected]"
TO = "[email protected]"
SUBJECT = "test email"
TEXT = "details go here"

yagmail.SMTP(FROM).send(TO, SUBJECT, TEXT)
2

There are 2 best solutions below

3
On

I got it to work using the following:

import yagmail
FROM = '[email protected]'
TO = '[email protected]'
SUBJECT = 'test email'
TEXT = 'details go here'

yag = yagmail.SMTP('myO365email.com', 'myO365pw', host='smtp.office365.com', port=587, smtp_starttls=True, smtp_ssl=False)
yag.send(TO, SUBJECT, TEXT)

The trick was to configure the SMTP TLS/SSL options.

0
On

The answer of dnlbrky still works with 2FA. If you've activated 2FA you need to generate an app password, see here: Using app passwords with apps that don't support two-step verification

When generated, fill the second param here instead of your regular password:

yag = yagmail.SMTP('myO365email.com', 'mynewapppassword', host='smtp.office365.com', port=587, smtp_starttls=True, smtp_ssl=False)