Email automation is essential for businesses and individuals to send notifications, newsletters, reports, and alerts. Python provides multiple libraries to automate email sending, including:
smtplib
– Sending emails via SMTP
email
– Formatting emails with attachments
yagmail
– Simplifying email automation
schedule
– Automating email tasks
2. Setting Up Email Automation
A. Using SMTP for Sending Emails
SMTP (Simple Mail Transfer Protocol) is a standard for sending emails.
Gmail SMTP Server Details:
- SMTP Server:
smtp.gmail.com
- Port:
587
B. Enable SMTP Access for Gmail
Before using Gmail, enable Less Secure Apps or generate an App Password:
1️⃣ Go to Google App Passwords
2️⃣ Generate a password for “Mail”
3️⃣ Use the generated password instead of your Gmail password
3. Sending Simple Emails Using smtplib
Install Dependencies
pip install smtplib email
Send an Email
import smtplib
from email.mime.text import MIMEText
# Email Configuration
SMTP_SERVER = "smtp.gmail.com"
SMTP_PORT = 587
EMAIL_SENDER = "your_email@gmail.com"
EMAIL_PASSWORD = "your_app_password"
EMAIL_RECEIVER = "recipient_email@gmail.com"
# Email Content
subject = "Automated Email from Python"
body = "Hello, this is a test email sent using Python."
# Create Email Message
msg = MIMEText(body)
msg["Subject"] = subject
msg["From"] = EMAIL_SENDER
msg["To"] = EMAIL_RECEIVER
# Send Email
try:
server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
server.starttls() # Secure the connection
server.login(EMAIL_SENDER, EMAIL_PASSWORD)
server.sendmail(EMAIL_SENDER, EMAIL_RECEIVER, msg.as_string())
server.quit()
print("Email sent successfully!")
except Exception as e:
print(f"Error: {e}")
This sends a simple email using Python!
4. Sending Emails with Attachments
To send files (PDFs, images, etc.), use MIMEApplication
.
Send an Email with an Attachment
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
import os
def send_email_with_attachment():
msg = MIMEMultipart()
msg["Subject"] = "Email with Attachment"
msg["From"] = EMAIL_SENDER
msg["To"] = EMAIL_RECEIVER
# Email Body
msg.attach(MIMEText("Please find the attached file.", "plain"))
# Attach File
filename = "document.pdf"
with open(filename, "rb") as file:
attachment = MIMEApplication(file.read(), Name=os.path.basename(filename))
attachment["Content-Disposition"] = f'attachment; filename="{filename}"'
msg.attach(attachment)
# Send Email
server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
server.starttls()
server.login(EMAIL_SENDER, EMAIL_PASSWORD)
server.sendmail(EMAIL_SENDER, EMAIL_RECEIVER, msg.as_string())
server.quit()
print("Email with attachment sent!")
send_email_with_attachment()
Now you can send emails with attachments!
5. Sending HTML Emails
Emails with formatting, images, and buttons can be sent using HTML.
Send an HTML Email
html_content = """
<html>
<body>
<h2 style='color:blue;'>Hello from Python!</h2>
<p>This is an <b>automated HTML email</b>.</p>
<a href='https://www.python.org'>Visit Python</a>
</body>
</html>
"""
msg = MIMEMultipart()
msg.attach(MIMEText(html_content, "html"))
# Send as before...
This improves email appearance!
6. Automating Emails with schedule
To send emails at specific times, use the schedule
library.
Install schedule
pip install schedule
Automate Sending Emails Daily at 9 AM
import schedule
import time
def send_daily_email():
send_email() # Call your email function
# Schedule the email
schedule.every().day.at("09:00").do(send_daily_email)
while True:
schedule.run_pending()
time.sleep(60) # Check every minute
Now, emails send automatically every day!
7. Using yagmail
for Simpler Automation
The yagmail
library simplifies email automation.
Install yagmail
pip install yagmail
Send an Email Easily
import yagmail
yag = yagmail.SMTP("your_email@gmail.com", "your_app_password")
yag.send(to="recipient_email@gmail.com", subject="Hello!", contents="This is an automated email.")
Less code, easy to use!
8. Deploying Email Automation in the Cloud
To send emails 24/7, deploy your script on a server.
A. Using PythonAnywhere
1️⃣ Sign up at pythonanywhere.com
2️⃣ Upload your script
3️⃣ Schedule execution using PythonAnywhere Tasks
Cloud-based email automation!
B. Using AWS Lambda (Serverless)
For event-driven emails (e.g., alerts when a system fails), use AWS Lambda + SES (Simple Email Service).