Attach a File to the Email
You can attach files like PDFs, spreadsheets, or images to your email using Python. The process involves reading the file in binary mode and adding it to the message.
Step-by-Step Code Example
import os
file_path = "reports/weekly_report.pdf"
# Open the file in binary read mode
with open(file_path, "rb") as f:
file_data = f.read()
file_name = os.path.basename(file_path)
# Attach the file to the message
msg.add_attachment(
file_data,
maintype="application",
subtype="pdf",
filename=file_name
)
Explanation of Key Parts
-
open(file_path, "rb"): Opens the file in binary mode (rb= read binary) -
file_data: Stores the contents of the file to be sent -
file_name: Extracts just the filename (e.g.,weekly_report.pdf) from the full path usingos.path.basename() -
msg.add_attachment():-
maintype="application"tells the email client it’s a non-text file (like PDF, Word, etc.) -
subtype="pdf"specifies the file type -
filename=file_nameis what the recipient will see as the file name
-
Pro Tip:
You can change the subtype depending on the file:
-
"pdf"for PDF files -
"vnd.openxmlformats-officedocument.spreadsheetml.sheet"for Excel -
"msword"for Word documents -
"jpeg"or"png"for images
