Categories
Linux Networking Programming

Sending an email via Microsoft O365 SMTP Servers using Python

This is a simple script to send an email via MS’s O365 Service:

#!/usr/bin/env python3

import ssl
import smtplib
from smtplib import SMTP
from getpass import getpass


email = '''From: example-service@example.org <example-service@example.org>
To: Jay Tuckey <jay.tuckey@example.org>
Subject: Test email

Hi there, testing testing
'''



with SMTP("smtp.office365.com", port=587) as s:
    sslcontext = ssl.create_default_context()
    s.starttls(context=sslcontext)
    p = getpass('Password for example-service@example.org: ')
    s.login('example-service@example.org', p)

    s.sendmail('example-service@example.org', ["jay.tuckey@example.org"], email)

Note how you need to set up an SSL context and perform .starttls() to properly create a secure connection.

Leave a Reply

Your email address will not be published. Required fields are marked *