Explain Codes LogoExplain Codes Logo

How to send email attachments?

python
email-attachments
smtplib
email-configuration
Nikita BarsukovbyNikita Barsukov·Jan 16, 2025
TLDR

Saddle up and get ready to send email attachments using Python's inbuilt smtplib and email.mime modules:

import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.base import MIMEBase from email import encoders # I'm ready to throw some emails in, are you? server_address = "smtp.yourprovider.com" server_port = 587 login, password = "your_email", "your_password" # Pretend it's a letter. Not the Hogwarts one though. msg = MIMEMultipart() msg['From'], msg['To'], msg['Subject'] = "your_email", "recipient_email", "Email Subject" msg.attach(MIMEText("Email body", 'plain')) # Rolling up the scroll for the barn owl... file_path = "path/to/your/file" with open(file_path, "rb") as file: part = MIMEBase('application', 'octet-stream') part.set_payload(file.read()) encoders.encode_base64(part) part.add_header('Content-Disposition', f"attachment; filename={file_path}") # Owl's taking flight! msg.attach(part) with smtplib.SMTP(server_address, server_port) as server: server.starttls() server.login(login, password) server.send_message(msg)

Replace the placeholders fitting to your situation. This concise code sample shows how to handle attachments and send emails using Python.

Pre-flight checklist: Configuration and security

Play it safe. Before taking off, make sure to tweak your email account to allow script-driven logins. Google trust issues? Enable access for less secure apps on your Gmail account. Not a fan of loopholes? Use OAuth for a fortified keep.

Positive grip: Authenticating and connecting to the server

Don't barge in, knock first. Initiate a secure handshake with your SMTP server using server.starttls(). This casts an encrypted protection spell on your communication. Ahoy! Utilize server.login(username, password) to authenticate:

with smtplib.SMTP(server_address, server_port) as server: server.starttls() server.login(login, password)

Drafting: Crafting the email

Crafting an email is like pottery. Take care of both plain text and HTML parts using MIMEText. Ensure your masterpiece is displayable on all devices. Potter's wheel spinning, mould these parts onto your MIMEMultipart message object with msg.attach().

Loading the quiver: Preparing files for attachment

Feed your attachment into the script using binary mode ("rb") to keep the data integrity intact. Every arrow in your quiver i.e., the MIMEBase object, grips the data of your attachment, encrypted into base64 to prevent data corruption over SMTP. Attach a tag with the Content-Disposition set to "attachment" and a filename parameter to specify names of your arrows:

with open(file_path, "rb") as file: # ...rest of the MIMEBase setup

Releasing the arrow: Firing the email

Pull back, aim and release! Use server.send_message(msg) to let your email fly. Once the raven has taken flight, close your server connection using server.quit(), making sure the resources are freed appropriately.

Cooking with attachments: Handling multiple ingredients

Just as our favourite bearded wizard can handle numerous spells, your email can handle multiple attachments. Extend the loop to include all files and create a MIMEBase object for each.

Addressing the recipient correctly: Ensuring recipient formatting

Be polite, format your To field well. A string split by commas for groups or a list for individual recipients.

msg['To'] = ", ".join(recipient_list) # For multiple recipients

Keeping your magic organized: Structuring attachments

Take the clean wizarding approach. Dedicate a function to create MIME objects for attachments. An organized spell book (or code), is incrementally manageable and modular, perfect for maintenance.