How to send email with file attachment via SMTP in Python
This example shows how to send an email with an attachment in Python, with the attachment being read from a file from the filesystem:
#!/usr/bin/env python3
import smtplib
import mimetypes
from email.message import EmailMessage
# Create message and set text content
msg = EmailMessage()
msg['Subject'] = 'This email contains an attachment'
msg['From'] = '[email protected]'
msg['To'] = '[email protected]'
# Set text content
msg.set_content('Please see attached file')
def attach_file_to_email(email, filename):
"""Attach a file identified by filename, to an email message"""
with open(filename, 'rb') as fp:
file_data = fp.read()
maintype, _, subtype = (mimetypes.guess_type(filename)[0] or 'application/octet-stream').partition("/")
email.add_attachment(file_data, maintype=maintype, subtype=subtype, filename=filename)
# Attach files
attach_file_to_email(msg, "myfile.pdf")
def send_mail_smtp(mail, host, username, password):
s = smtplib.SMTP(host)
s.starttls()
s.login(username, password)
s.send_message(mail)
s.quit()
send_mail_smtp(msg, 'smtp.my-domain.com', '[email protected]', 'sae7ooka0S')
The utility functions in this code are:
import smtplib
import mimetypes
def attach_file_to_email(email, filename):
"""Attach a file identified by filename, to an email message"""
with open(filename, 'rb') as fp:
file_data = fp.read()
maintype, _, subtype = (mimetypes.guess_type(filename)[0] or 'application/octet-stream').partition("/")
email.add_attachment(file_data, maintype=maintype, subtype=subtype, filename=filename)
def send_mail_smtp(mail, host, username, password):
s = smtplib.SMTP(host)
s.starttls()
s.login(username, password)
s.send_message(mail)
s.quit()
Initialize your email like this:
# Create message and set text content
msg = EmailMessage()
msg['Subject'] = 'This email contains an attachment'
msg['From'] = '[email protected]'
msg['To'] = '[email protected]'
# Set text content
msg.set_content('Please see attached file')
and then attach the file like this:
attach_file_to_email(msg, "myfile.pdf")
and send the email using
send_mail_smtp(msg, 'smtp.my-domain.com', '[email protected]', 'sae7ooka0S')