Python: Send Email via Office 365

Tutorial on how to use Python 3 to send email via Office 365 SMTP Server

Enable Authenticated client SMTP submission in Office 365

The SMTP AUTH protocol is used for client SMTP email submission via TCP Port 587 and is DISABLED by default in Office 365 now.

Refer to Enable or disable authenticated client SMTP submission (SMTP AUTH) in Exchange Online for more information

Login to Exchange Online to verify SMTP AUTH is disabled by default for mailbox called O365Admin

Get-CASMailbox O365Admin

Name    ActiveSyncEnabled OWAEnabled PopEnabled ImapEnabled MapiEnabled SmtpClientAuthenticationDisabled
----    ----------------- ---------- ---------- ----------- ----------- --------------------------------
o365admin True              True       True       True        True                                        

Enabled SMTP_AUTH by setting SmtpClientAuthenticationDisabled = False

Get-CASMailbox o365admin | Set-CASMailbox -SmtpClientAuthenticationDisabled $false

Get-CASMailbox o365admin

Name    ActiveSyncEnabled OWAEnabled PopEnabled ImapEnabled MapiEnabled SmtpClientAuthenticationDisabled
----    ----------------- ---------- ---------- ----------- ----------- --------------------------------
o365admin True              True       True       True        True        False                           

O365Admin with SMTP_AUTH enabled can be used to send email via TCP Port 587 in Python 3 and PowerShell now

Send Email via Office 365 with Python 3.8

Import the required module

import smtplib
from email.message import EmailMessage

Define smtp.office365.com which is the SMTP Server for Office 365 with username & password

password = 'XXXXXXXXXXX'
smtpsrv = "smtp.office365.com"
smtpserver = smtplib.SMTP(smtpsrv,587)

Define the sender, receiver, and subject

msg = EmailMessage()

msg['Subject'] = 'Email Testing with Python'
msg['From'] = '[email protected]'
msg['To'] = '[email protected]'

Send the Email Message

smtpserver.ehlo()
smtpserver.starttls()
smtpserver.login(user, password)
smtpserver.send_message (msg)
smtpserver.close()

Send Email via Office 365 with PowerShell

Send Email via TCP Port 587 with PowerShell Script

$UserName = "[email protected]" 
$Password = ConvertTo-SecureString "XXXXXXXXXXXXXXXXX" -AsPlainText -Force
$credential = New-Object System.Management.Automation.PsCredential($UserName,$Password)

$To = "[email protected]"
$From = "[email protected]com"
$Subject = "Email Testing from PowerShell via Port 587"
$Body = "Testing Email"
$SMTPServer = "smtp.office365.com"

Send-MailMessage -To $To -From $From -Subject $Subject -Body $Body -Credential $credential -SmtpServer $SMTPServer -Port 587 -UseSsl

Verify Test Email is delivered

A test email will be delivered to the recipient inbox

Send Email via Office 365

Leave a Comment

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

Scroll to Top