This is done by following these steps.
Want to send an email using Python?
You don't need to be an expert programmer. You don't need to install a bunch of complicated packages. And you don't need to build an entire email application from scratch.
Python already has everything you need to get started.
In this guide, I'll show you exactly how to send email with Python, step by step.
You'll learn how to:
- Send a basic email using Python.
- Send email through Gmail.
- Send HTML emails.
- Send emails with file attachments.
- Send emails to multiple recipients.
- Automate email sending with Python.
- Fix common Python email errors.
Let's get started.
How to Send Email With Python (The Quick Answer)
The easiest way to send email with Python is to use two built-in Python modules:
smtplib– Connects to an email server and sends your message.email.message– Creates the email, including the subject, recipient, and message body.
You don't need to install either module.
Here's a simple example:
python
import smtplib
import ssl
from email.message import EmailMessage
sender_email = "your_email@example.com"
receiver_email = "recipient@example.com"
password = "YOUR_EMAIL_PASSWORD"
message = EmailMessage()
message["Subject"] = "My First Python Email"
message["From"] = sender_email
message["To"] = receiver_email
message.set_content("Hello! This email was sent using Python.")
context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.example.com", 465, context=context) as server:
server.login(sender_email, password)
server.send_message(message)
print("Email sent successfully!")
Replace the example email addresses, password, and SMTP server with the details provided by your email provider.
That's it!
Your Python script can now send an email.
But let's walk through everything so you understand how it works.
Step 1: Make Sure Python Is Installed
Before sending an email with Python, you'll need Python installed on your computer.
If you already have Python installed, you can skip this step.
If not, download it from:
https://www.python.org/downloads/
Once Python is installed, open your terminal or command prompt and run:
python --version
Depending on your operating system, you may need:
bash
python3 --version
You should see your installed Python version.
Now you're ready to write your first email script.
Step 2: Import Python's Email Modules
Python makes sending emails surprisingly simple.
You only need a few imports:
python
import smtplib
import ssl
from email.message import EmailMessage
Here's what each module does:
smtplib
This module allows Python to communicate with an SMTP server.
SMTP stands for Simple Mail Transfer Protocol. It's the standard protocol used to send emails between mail servers.
ssl
This module helps create a secure, encrypted connection to your email server.
EmailMessage
This module helps you build your email message.
It lets you add:
- A sender.
- A recipient.
- A subject line.
- Plain-text content.
- HTML content.
- File attachments.
These three imports are enough to handle most basic email-sending tasks.
Step 3: Create Your Email Message
Now let's create the actual email.
Start with this code:
python
from email.message import EmailMessage
message = EmailMessage()
message["Subject"] = "Hello From Python"
message["From"] = "your_email@example.com"
message["To"] = "recipient@example.com"
message.set_content("Hello! This email was sent using Python.")
Let's break it down.
Subject
This is the subject line your recipient will see.
From
This is the email address sending the message.
To
This is the email address receiving the message.
set_content()
This is where you add the actual email message.
You can put almost anything here, including plain text, personalized messages, and information generated by your Python script.
You've now created an email.
Next, you need to send it.
Step 4: Connect Python to an Email Server
Python needs an email server to deliver your message.
Most email providers support SMTP.
You'll need three things:
- SMTP server address.
- SMTP port.
- Login credentials or another supported authentication method.
For example, Gmail uses:
| Setting | Gmail |
|---|---|
| SMTP server | smtp.gmail.com |
| SSL port | 465 |
| TLS port | 587 |
| Username | Your Gmail address |
There are two common ways to create a secure SMTP connection.
Option 1: Use SMTP_SSL
python
with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=ssl.create_default_context()) as server:
server.login(sender_email, password)
server.send_message(message)
Option 2: Use STARTTLS
python
with smtplib.SMTP("smtp.gmail.com", 587) as server:
server.ehlo()
server.starttls(context=ssl.create_default_context())
server.ehlo()
server.login(sender_email, password)
server.send_message(message)
Both methods encrypt the connection before your credentials are sent.
Just remember:
- Port 465 uses
SMTP_SSL. - Port 587 uses
SMTPfollowed bystarttls().
Don't mix the two connection methods.
Step 5: Send an Email With Python Using Gmail
Want to send email using Python and Gmail?
Here's how.
First, you'll need to configure your Google account to allow your Python application to authenticate.
Google doesn't allow you to simply use your normal Gmail password for traditional SMTP login.
For accounts that support app passwords, you'll need to:
- Enable 2-Step Verification on your Google account.
- Open your Google Account security settings.
- Find the App Passwords section.
- Generate an app password for your Python application.
- Store that password securely.
Google may require OAuth authentication for some accounts or organizational configurations.
Now, let's put everything together.
Complete Python Gmail Email Script
python
import os
import smtplib
import ssl
from email.message import EmailMessage
sender_email = os.environ["GMAIL_USER"]
receiver_email = "recipient@example.com"
password = os.environ["GMAIL_APP_PASSWORD"]
message = EmailMessage()
message["Subject"] = "My First Gmail Message From Python"
message["From"] = sender_email
message["To"] = receiver_email
message.set_content("""
Hello!
This email was sent using Python and Gmail.
Pretty simple, right?
Have a great day!
""")
context = ssl.create_default_context()
with smtplib.SMTP_SSL(
"smtp.gmail.com",
465,
context=context,
timeout=30
) as server:
server.login(sender_email, password)
server.send_message(message)
print("Gmail message sent successfully!")
Before running the script, set your environment variables.
On macOS or Linux:
bash
export GMAIL_USER="your_email@gmail.com"
export GMAIL_APP_PASSWORD="your_app_password"
On Windows PowerShell:
powershell
$env:GMAIL_USER="your_email@gmail.com"
$env:GMAIL_APP_PASSWORD="your_app_password"
Run your Python script.
If everything is configured correctly, your email should arrive in the recipient's inbox.
Important: Never publish your email password or app password in your Python code, GitHub repository, or public projects.
Step 6: Send HTML Emails With Python
Plain-text emails are great.
But what if you want to send an email with formatting?
Maybe you want:
- Bold text.
- Different colors.
- Clickable links.
- Headings.
- Styled buttons.
- HTML layouts.
You can do that with Python, too.
The EmailMessage module makes it easy.
Here's an example:
python
import smtplib
import ssl
from email.message import EmailMessage
message = EmailMessage()
message["Subject"] = "Your Python HTML Email"
message["From"] = "your_email@example.com"
message["To"] = "recipient@example.com"
message.set_content(
"Your email client does not support HTML."
)
html_content = """
<html>
<body>
<h1>Hello!</h1>
<p>This email was sent using Python.</p>
<p>
<strong>Pretty cool, right?</strong>
</p>
<p>
<a href="https://www.python.org/">
Visit Python.org
</a>
</p>
</body>
</html>
"""
message.add_alternative(html_content, subtype="html")
context = ssl.create_default_context()
with smtplib.SMTP_SSL(
"smtp.example.com",
465,
context=context
) as server:
server.login("your_email@example.com", "YOUR_PASSWORD")
server.send_message(message)
print("HTML email sent!")
The important part is:
python
message.add_alternative(html_content, subtype="html")
This tells Python to include an HTML version of your email.
Notice that we also included a plain-text version.
That's a good practice because some email clients don't display HTML messages.
Step 7: Send Emails With Attachments Using Python
Want to send a PDF, image, spreadsheet, or another file?
No problem.
Python can attach files to emails using add_attachment().
Here's an example:
python
import smtplib
import ssl
from email.message import EmailMessage
message = EmailMessage()
message["Subject"] = "Here Is Your File"
message["From"] = "your_email@example.com"
message["To"] = "recipient@example.com"
message.set_content("Hi! I've attached the file you requested.")
with open("report.pdf", "rb") as file:
message.add_attachment(
file.read(),
maintype="application",
subtype="pdf",
filename="report.pdf"
)
context = ssl.create_default_context()
with smtplib.SMTP_SSL(
"smtp.example.com",
465,
context=context
) as server:
server.login("your_email@example.com", "YOUR_PASSWORD")
server.send_message(message)
print("Email with attachment sent!")
A few things to notice:
The rb setting
This opens the file in binary mode, which is important when attaching files.
The add_attachment() method
This adds your file to the email.
The filename
This controls the name your recipient sees when downloading the attachment.
You can use the same approach for PDFs, images, Excel files, Word documents, and many other file types.
Step 8: Send Emails to Multiple Recipients With Python
What if you want to send the same email to multiple people?
You don't need to create a separate email script for every recipient.
You can use a list.
Here's how:
python
import smtplib
import ssl
from email.message import EmailMessage
sender_email = "your_email@example.com"
recipients = [
"person1@example.com",
"person2@example.com",
"person3@example.com"
]
message = EmailMessage()
message["Subject"] = "Hello From Python"
message["From"] = sender_email
message["To"] = ", ".join(recipients)
message.set_content(
"Hello everyone! This email was sent using Python."
)
context = ssl.create_default_context()
with smtplib.SMTP_SSL(
"smtp.example.com",
465,
context=context
) as server:
server.login(sender_email, "YOUR_PASSWORD")
server.send_message(message)
print("Emails sent successfully!")
This sends one email addressed to all three recipients.
Privacy tip: If recipients shouldn't see each other's email addresses, use the BCC field instead.
For larger mailing lists, use a dedicated email delivery service with unsubscribe management and appropriate consent practices.
Step 9: Automate Email Sending With Python
Now here's where things get interesting.
You can use Python to automatically send emails whenever something happens.
For example:
- Send a daily report.
- Send an email when a file is uploaded.
- Notify yourself when a website goes down.
- Send an order confirmation.
- Send a reminder.
- Notify a team when a script finishes running.
Here's a simple example of an automated notification:
python
def send_notification(subject, body, recipient):
import os
import smtplib
import ssl
from email.message import EmailMessage
message = EmailMessage()
message["Subject"] = subject
message["From"] = os.environ["EMAIL_USER"]
message["To"] = recipient
message.set_content(body)
context = ssl.create_default_context()
with smtplib.SMTP_SSL(
"smtp.example.com",
465,
context=context,
timeout=30
) as server:
server.login(
os.environ["EMAIL_USER"],
os.environ["EMAIL_PASSWORD"]
)
server.send_message(message)
send_notification(
"Python Script Completed",
"Your automated Python task has finished successfully.",
"recipient@example.com"
)
Now you have a reusable email function.
You can call it whenever your Python application needs to send a notification.
For recurring emails, you can schedule your script using cron on Linux and macOS or Task Scheduler on Windows.
Step 10: Common Python Email Errors (And How to Fix Them)
Sometimes your first attempt won't work.
That's normal.
Here are some common problems you might encounter when sending email with Python.
SMTPAuthenticationError
What it means:
Your email provider rejected your login credentials.
How to fix it:
- Check your email address.
- Verify your password or app password.
- Check whether your account requires OAuth authentication.
- Make sure the account allows the authentication method you're using.
For Gmail, a normal account password won't work with traditional SMTP login.
SMTPConnectError
What it means:
Python couldn't establish a connection to your SMTP server.
How to fix it:
- Check your SMTP server address.
- Verify your port number.
- Check your internet connection.
- Check whether your network or hosting provider blocks SMTP connections.
Connection Timed Out
What it means:
Your script couldn't connect to the email server within the allowed time.
How to fix it:
- Check your firewall settings.
- Verify the SMTP server and port.
- Check whether your hosting provider restricts outbound SMTP traffic.
- Try a supported alternative email API.
Email Goes to Spam
What it means:
Your email was accepted for delivery but ended up in the recipient's spam folder.
How to fix it:
- Use a properly authenticated sending domain.
- Configure SPF, DKIM, and DMARC.
- Use a reputable email provider.
- Include accurate sender information.
- Avoid misleading subject lines.
- Send messages only to people who expect them.
Remember, successfully sending an email doesn't guarantee that it will land in the inbox.
1. Can you send emails with Python?
Yes!
Python includes a built-in module called smtplib that allows you to connect to an SMTP server and send emails.
You can use it to send plain-text emails, HTML emails, attachments, and automated notifications.
2. How do I send an email with Python without installing anything?
Use Python's built-in smtplib, ssl, and email.message modules.
You don't need to install additional packages to send a basic SMTP email.
You'll still need access to an email provider or SMTP server.
3. Can Python send emails through Gmail?
Yes.
You can use Gmail's SMTP server with Python.
For traditional SMTP authentication, eligible accounts can use an app password with 2-Step Verification enabled. Other accounts may require OAuth authentication.
4. What is the best Python library for sending emails?
For basic email sending, Python's built-in smtplib module is a great option.
For more complex applications, you can also use an email provider's API or a third-party library.
The best option depends on your project.
5. Can Python send emails with attachments?
Absolutely.
Use the EmailMessage class and its add_attachment() method.
You can attach PDFs, images, spreadsheets, and other files.
6. Can Python send automatic emails?
Yes.
Python can send emails automatically when a script runs or when a specific event occurs.
You can also schedule Python scripts to run at specific times using cron or Windows Task Scheduler.
7. Can Python send bulk emails?
Yes, but you should use an appropriate email delivery provider for larger sending volumes.
A personal Gmail account is not designed for unrestricted bulk email.
For marketing emails, follow applicable anti-spam laws, obtain the necessary consent, and provide unsubscribe functionality.
8. Is SMTP required to send emails with Python?
No.
SMTP is one option.
You can also send emails using an email provider's HTTP API. This can be a better choice for production applications that need delivery tracking, bounce handling, and higher-volume sending.
As you can see, sending email with Python isn't complicated.
You just need to understand a few basic things:
smtplibconnects to your email server.EmailMessagecreates your email.sslhelps secure your connection.- SMTP credentials or another supported authentication method allow your application to send messages.
Once you understand these basics, you can do much more than send a simple email.
You can automate reports, send notifications, deliver attachments, create HTML emails, and build email functionality directly into your Python applications.
The best part?
You can get started using Python's built-in libraries without installing anything.
So grab your favorite code editor, try the examples above, and send your first email with Python!