How to send emails with attachments with Python by using Microsoft Outlook or Office365 SMTP server.

Michael King
3 min readDec 26, 2019

This piece of code is very short, but it is highly effective and it helped me multiple times to deliver automatic email notifications in corporate environment.

Photo by Mathyas Kurmann on Unsplash

Let’s start with a import of required Python libraries

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import os.path

Now, we will create a new function which will handle the whole email sending process. The function send_email() has 3 arguments: email_recipient as String, email_subject as String and an optional argument attachment_location as String.

def send_email(email_recipient, email_subject, email_message, attachment_location = ''):

Let’s add few more lines inside the function send_email(), so we can define the email content.

email_sender = 'your_email_address@your_server.com'

msg = MIMEMultipart()
msg['From'] = email_sender
msg['To'] = email_recipient
msg['Subject'] = email_subject

--

--

Michael King

💫DevOps Pro & AI Junkie🤖 5X Awarded Writer 🏆 🤖🖼️🎨📚📖 👉 Midjourney AI: Automation Bot (with Privacy Mode)! ⬇️ https://kingmichael.gumroad.com/l/ewuso