Send Email to Others by Outlook Email – Python SMTP Tutorial

By | June 7, 2019

In this tutorial, we introduce you how to use your outlook email to send emails to others by using python. Here is an example.

To use your outlook email to send email to others, you should know:

1. Outlook email SMTP server host and port.

smtpHost = 'smtp.office365.com'
smtpPort = 587

2. Your outlook email and password.

sender = 'youremail@outlook.com'
password = "youremailpassword"

3. Who you want to send email to

receivers = ['others@163.com']

You should note: receivers should be a list, which means you can send one email to some persons.

4. How to create a email content.

The format of email is should be:

From: sender
To: receivers
Subject: email subject

email content

5. Login to outlook email server using SMTP and send email.

Here is full example:

#!/usr/bin/python

import smtplib
sender = 'youremail@outlook.com'
receivers = ['others@163.com']

#smtp
smtpHost = 'smtp.office365.com'
smtpPort = 587
password = "youremailpassword" 

subject = "outlook email test"
# Add the From: and To: headers at the start!
message = ("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n"
       % (sender, ", ".join(receivers), subject))

message += """This is a test e-mail message."""

print (message)

try:
    smtpObj = smtplib.SMTP(smtpHost, smtpPort)
    #smtpObj.set_debuglevel(1)
    smtpObj.ehlo()
    smtpObj.starttls()
    smtpObj.ehlo()    

    smtpObj.login(sender,password)
    smtpObj.sendmail(sender, receivers, message)
    smtpObj.quit()
    print ("Successfully sent email")
except SMTPException:
    print ("Error: unable to send email")

Run code above, you will find this example works fine.

Note: If this example reports: smtplib.SMTPNotSupportedError: SMTP AUTH extension not supported by server.

You can read Fix smtplib.SMTPNotSupportedError: SMTP AUTH extension not supported by server