Sending Email with attachment in Python

Photo of author

By Jackson Taylor

Home » Programming » Sending Email with attachment in Python

Python can send an email with a file attached using only its standard library. You do not need to install anything. The two modules you need are smtplib, which talks to the mail server, and email, which builds the message and packs the file into it.

This guide shows a short, working approach, explains each step, and lists the problems people most often run into. If you have never written a script before, read about getting started with Python first. If you only need text, our guide to sending a plain email in Python covers the basics.

What you need before you start

  • Python 3 installed on your computer.
  • An email account that allows SMTP access, and the address of its SMTP server.
  • The file you want to attach, for example a PDF, image or text file.
  • The recipient’s email address.

Most providers no longer accept your normal password for scripts. Gmail, for example, normally requires 2-step verification to be on and a separate app password to be created for the script. Check your provider’s help pages for the exact steps, and never type a real password straight into code you plan to share.

How an email attachment works

An email is a text message with a structure called MIME. A message with an attachment has several parts: the readable body, and one or more parts that hold the file as encoded data, along with its name and type. The modern EmailMessage class in Python handles this encoding for you, so you only need to give it the bytes of the file, the file type and a file name.

Hardware Hack

Stop Buying New Batteries for Your Tech

Electronics are expensive, but their power sources don't have to be. Discover the simple engineering trick to recondition dead batteries and bring your gadgets back to 100% capacity.

Watch the Free Video

Step-by-step: send an email with an attachment

1. Import the modules

import smtplib

import mimetypes

from pathlib import Path

from email.message import EmailMessage

2. Set your details

sender = “you@example.com”

password = “your-app-password”

recipient = “friend@example.com”

path = “report.pdf”

Replace these values with your own. A better habit is to read the password from an environment variable instead of writing it into the file. If you want the script to ask for the file name each time, see how reading input in Python works.

See also
PYTHON & OpenCV

3. Create the message and the body

msg = EmailMessage()

Sustainable Tech

Keep Toxic E-Waste Out of Landfills

Don't throw away your failing laptop, phone, or car batteries. Learn how to recondition them at home in just a few hours. It's better for the planet—and your wallet.

Learn How It Works

msg[“Subject”] = “Report attached”

msg[“From”] = sender

msg[“To”] = recipient

msg.set_content(“Hello, please find the report attached.”)

The body can be built from variables if you want to personalise it. That is mostly a matter of joining strings together or using f-strings.

4. Read the file and attach it

data = Path(path).read_bytes()

ctype, _ = mimetypes.guess_type(path)

maintype, subtype = (ctype or “application/octet-stream”).split(“/”, 1)

msg.add_attachment(data, maintype=maintype, subtype=subtype, filename=Path(path).name)

The file is read in binary mode, so this works for images, PDFs, zip files and text alike. The mimetypes module guesses the file type from its extension. If it cannot, the code falls back to a generic binary type, which mail programs still handle as a download.

5. Connect to the server and send

server = smtplib.SMTP_SSL(“smtp.gmail.com”, 465)

server.login(sender, password)

server.send_message(msg)

server.quit()

The Ultimate Money-Saving DIY Skill

From power tools and solar banks to your car, batteries are the most expensive part of your gear. Master the step-by-step DIY system to bring dead batteries back to life.

Get the Step-by-Step Guide

This example uses Gmail’s server with an encrypted connection on port 465. For another provider, use the server name and port in its documentation. Many servers use port 587 with STARTTLS instead. In that case, create the connection with smtplib.SMTP(host, 587), call server.starttls(), and then log in.

Sending more than one attachment

Call add_attachment once for each file. A simple way is to keep the paths in a list and repeat steps 4 for each item. Remember that mail servers limit the total message size, and attachments grow by roughly a third when encoded. If your files are large, upload them somewhere and send a link instead.

Sending to several recipients

Set the To header to a string of addresses separated by commas, for example "a@example.com, b@example.com". The send_message method reads the recipients from the headers. To send a hidden copy, add a Bcc header. Python uses it for delivery and does not include it in the message that recipients see.

Common errors and how to fix them

  • SMTPAuthenticationError: the login was rejected. Use an app password if your provider requires one, and check that SMTP access is enabled for the account.
  • FileNotFoundError: the path is wrong. Use a full path, or run the script from the folder that holds the file.
  • Connection timed out or refused: the server name or port is wrong, or a firewall or network is blocking outgoing SMTP traffic.
  • The attachment opens as garbage or has no name: make sure you read the file in binary mode and pass the filename argument.
  • The email lands in spam: avoid empty subjects, send from an address that matches the account you log in to, and do not send bulk mail from a personal account.
See also
Sending Email with attachment in Python

Good practice

  • Keep credentials out of your code. Use environment variables or a separate configuration file that is not shared.
  • Test by sending to your own address first.
  • Use with smtplib.SMTP_SSL(...) as server: if you prefer the connection to close automatically, even when an error occurs.
  • Wrap the sending code in try and except so a failure gives a clear message instead of a long traceback.

Once this works, it is easy to reuse. A script can email a log file, a camera snapshot or a daily report. If you build small devices, many Raspberry Pi Python projects can use the same code to send alerts with a photo or data file attached.

Frequently asked questions

Do I need to install a library to send attachments in Python?

No. The smtplib, email, mimetypes and pathlib modules all come with Python 3. Third-party libraries exist, but they are optional.

Why does Gmail reject my password in the script?

Google generally blocks sign-ins from scripts that use your normal account password. Turn on 2-step verification, create an app password, and use that in your code.

Can I attach images, PDFs and zip files with the same code?

Yes. The code reads any file as bytes and attaches it with the type guessed from its extension, so the same steps work for all of these formats.

What is the difference between SMTP_SSL and starttls?

Both encrypt the connection. SMTP_SSL starts encrypted from the first moment, usually on port 465. With starttls, you connect normally, usually on port 587, and then upgrade to an encrypted connection before logging in.

Revive Your Dead Electronics

Got a drawer full of dead gadgets or a failing car battery? Instead of paying a premium for replacements, use this simple trick to easily recondition them right from home.

See How It Works