Python: Send Email with File Attachment Using SMTP

In this tutorial, we will introduce you on how to send email with file attachment in python.

Python - Send Email with File Attachment Using SMTP

If you want to use outlook email to send attachment, you can refer this tutorial:

Send Email with Attachments by Outlook Email – Python SMTP Tutorial

1.Import library

import smtplib 

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

2.Define email sender and recipient addresses

fromaddr = 'SENDER EMAIL ADDRESS'
toaddr = 'RECIPIENT EMAIL ADDRESS'

3.Create an instance of MIMEMultipart() class

msg = MIMEMultipart()

4.Build email message

msg['From'] = fromaddr

msg['To'] = toaddr

msg['Subject'] = 'This is the subject of my email'
body = 'This is the body of my email'

msg.attach(MIMEText(body))

5.Add file attachment to email

files = ['PATH TO FILE 1', 'PATH TO FILE 2', 'OTHER FILES']
for filename in files:

    attachment = open(filename, 'rb')

    part = MIMEBase("application", "octet-stream")

    part.set_payload(attachment.read())

    encoders.encode_base64(part)

    part.add_header("Content-Disposition",
    f"attachment; filename= {filename}")

    msg.attach(part)

msg = msg.as_string()

6.Start to send email

try:
    server = smtplib.SMTP('smtp.gmail.com:587')
    server.ehlo()
    server.starttls()
    server.login(fromaddr, 'gpjeukeadncvznul')
    server.sendmail(fromaddr, toaddr, msg)
    server.quit()
    print('Email sent successfully')
except:
    print("Email couldn't be sent")