How to send email with file attachment via SMTP in Python
Deutsch
English
This example shows how to send an email with an attachment in Python, with the attachment being read from a file from the filesystem:
send_email_attachment.py
#!/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'] = 'sender@domain.com'
msg['To'] = 'recipient@domain.com'
# 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', 'sender@domain.com', 'sae7ooka0S')The utility functions in this code are:
email_utils.py
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_email_msg.py
# Create message and set text content
msg = EmailMessage()
msg['Subject'] = 'This email contains an attachment'
msg['From'] = 'sender@domain.com'
msg['To'] = 'recipient@domain.com'
# Set text content
msg.set_content('Please see attached file')and then attach the file like this:
attach_example.py
attach_file_to_email(msg, "myfile.pdf")and send the email using
send_email_example.py
send_mail_smtp(msg, 'smtp.my-domain.com', 'sender@domain.com', 'sae7ooka0S')Check out similar posts by category:
Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow