Sending emails programmatically is a common requirement for many applications, whether it’s to send notifications, alerts, or verification emails. In Python, you can send emails using the SMTP (Simple Mail Transfer Protocol) with the help of the built-in smtplib
library. This article will guide you through the steps to send an email using SMTP in Python.
What is SMTP?
SMTP (Simple Mail Transfer Protocol) is a communication protocol used for sending emails over the internet. It allows your application to connect to an email server and transmit messages to recipients.
Prerequisites
Before you start sending emails, you’ll need:
- An SMTP server address (e.g.,
smtp.gmail.com
for Gmail). - A valid email account (sender’s email address).
- The recipient’s email address.
- SMTP authentication credentials (email and password for the sender’s account).
Steps to Send an Email Using SMTP in Python
Here’s a step-by-step guide:
1. Import Required Libraries
The main library used is smtplib
, and for composing the email, you can use email.message
or email.mime
modules.
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
2. Set Up SMTP Server Details
Define the SMTP server and port number. Common SMTP servers include:
- Gmail:
smtp.gmail.com
(port587
for TLS or465
for SSL) - Outlook:
smtp.office365.com
- Yahoo:
smtp.mail.yahoo.com
3. Write Your Email
Create the email’s content, including the sender, recipient, subject, and message body. Use MIMEMultipart
for more flexibility (e.g., adding attachments or formatting).
4. Authenticate and Send
Log in to the SMTP server with your credentials and send the email.
Code Example: Sending a Simple Email
Here’s a full example of sending an email using Gmail’s SMTP server:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# Sender and Receiver Email Addresses
sender_email = "[email protected]"
receiver_email = "[email protected]"
password = "your_email_password"
# Create the Email
subject = "Test Email from Python"
body = "This is a test email sent using Python and SMTP."
# Create a MIME object
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject
# Attach the email body
message.attach(MIMEText(body, "plain"))
# Connect to SMTP Server and Send Email
try:
# Use Gmail's SMTP server with TLS
with smtplib.SMTP("smtp.gmail.com", 587) as server:
server.starttls() # Start TLS encryption
server.login(sender_email, password) # Login to your account
server.sendmail(sender_email, receiver_email, message.as_string()) # Send email
print("Email sent successfully!")
except Exception as e:
print(f"Failed to send email: {e}")
Code Breakdown
- Set Up Sender and Receiver Details:
- Replace
[email protected]
and[email protected]
with actual email addresses. - Replace
your_email_password
with the sender’s email account password.
- Replace
- Create the Email:
- Use
MIMEMultipart
to build the email structure (e.g., adding subject, body, attachments). - Attach the plain text body using
MIMEText
.
- Use
- Connect to the SMTP Server:
- Use the
smtplib.SMTP
class to connect to the server. - Use
starttls()
to enable encryption. - Log in using
server.login()
.
- Use the
- Send the Email:
- Call
server.sendmail()
with the sender, receiver, and email content.
- Call
Sending Emails with Attachments
To send an email with an attachment, include the following steps:
- Import the
MIMEBase
andencoders
modules. - Add the file as an attachment using
MIMEBase
. - Encode the file and attach it to the email.
Example:
from email.mime.base import MIMEBase
from email import encoders
# Add an attachment
filename = "example.pdf" # Replace with your file path
with open(filename, "rb") as attachment:
part = MIMEBase("application", "octet-stream")
part.set_payload(attachment.read())
# Encode the file in ASCII
encoders.encode_base64(part)
part.add_header(
"Content-Disposition",
f"attachment; filename= {filename}",
)
# Attach the file to the email
message.attach(part)
Notes:
- Enable Less Secure Apps:
- Some email services (like Gmail) require you to enable “less secure app access” to allow SMTP connections. Alternatively, use App Passwords for enhanced security.
- Check your email provider’s settings for specific configurations.
- Avoid Hardcoding Passwords:
- Use environment variables or secret management tools to store sensitive credentials.
- Rate Limits:
- Be aware of rate limits imposed by email providers to avoid being blocked.
Using SMTP in Python with the smtplib
library is a straightforward way to send emails programmatically. By setting up the SMTP server details, creating the email content, and authenticating with the server, you can easily send plain text emails or even emails with attachments. For secure and scalable implementations, always follow best practices for handling sensitive information.