How to Send Emails from Gmail Using Python
Sending emails programmatically is a valuable skill for automation, communication, and data-driven workflows. Python makes this easy with its built-in smtplib library, which allows you to interact with the SMTP (Simple Mail Transfer Protocol) server to send emails.
Prerequisites
Before you start, ensure the following:
- Python Installed
Make sure Python 3 is installed on your system. You can download it from the official Python website. - Email Account with SMTP Access
You need an email account (like Gmail) and its SMTP credentials. Gmail usessmtp.gmail.comas the server and port587for TLS.
Understanding SMTP
SMTP is the protocol used to send emails over the internet. Python’s smtplib library allows you to:
- Connect to an email server.
- Authenticate with your email credentials.
- Send messages to recipients.
Steps to Send Email Using Python
Step 1: Import the smtplib library
import smtplib
Step 2: Create an SMTP session
s = smtplib.SMTP('smtp.gmail.com', 587)
'smtp.gmail.com'→ Gmail SMTP server587→ Port number for TLS encryption
Step 3: Start TLS for security
s.starttls()
TLS encrypts the communication between your Python script and the SMTP server.
Step 4: Authenticate
s.login("sender_email_id", "sender_email_password")
- Replace
"sender_email_id"and"sender_email_password"with your Gmail credentials.
Step 5: Prepare and Send the Message
message = "Message_you_need_to_send"
s.sendmail("sender_email_id", "receiver_email_id", message)
- Parameters: sender, receiver, and message.
Step 6: Terminate the SMTP Session
s.quit()
Send Email to Multiple Recipients
To send the same message to multiple email addresses, you can use a for loop:
import smtplib
email_list = ["[email protected]", "[email protected]"]
for dest in email_list:
s = smtplib.SMTP('smtp.gmail.com', 587)
s.starttls()
s.login("sender_email_id", "sender_email_password")
message = "Message_you_need_to_send"
s.sendmail("sender_email_id", dest, message)
s.quit()
Important Notes
- This method sends plain text emails without attachments or subjects.
- Gmail usually delivers these emails to the primary inbox, not spam.
- You can extend this by reading recipient email IDs from a file or sending emails with attachments.
- For attachments, you can use Python’s
emaillibrary to build MIME messages.
Next Steps
- Learn how to send emails with subjects and HTML content.
- Automate sending reports or notifications with Python scripts.
- Integrate with Excel or CSV files to send personalized emails in bulk.