Sending Emails with Python
Send emails programmatically with Python's smtplib and email modules. Automate reports, notifications, and alerts.
15 min•By Priygop Team•Updated 2026
Sending Emails
Sending Emails
# Python email sending (actual code):
# import smtplib
# from email.mime.text import MIMEText
# from email.mime.multipart import MIMEMultipart
#
# msg = MIMEMultipart()
# msg["Subject"] = "Test Email"
# msg["From"] = "sender@gmail.com"
# msg["To"] = "recipient@email.com"
# msg.attach(MIMEText("Hello from Python!", "plain"))
#
# with smtplib.SMTP("smtp.gmail.com", 587) as server:
# server.starttls()
# server.login("sender@gmail.com", "app_password")
# server.send_message(msg)
# Demo: Email builder
class EmailBuilder:
def __init__(self):
self.subject = ""
self.sender = ""
self.recipients = []
self.body = ""
self.attachments = []
def set_subject(self, subject):
self.subject = subject
return self
def set_from(self, sender):
self.sender = sender
return self
def add_to(self, recipient):
self.recipients.append(recipient)
return self
def set_body(self, body):
self.body = body
return self
def preview(self):
print("=== Email Preview ===")
print(f" From: {self.sender}")
print(f" To: {', '.join(self.recipients)}")
print(f" Subject: {self.subject}")
print(f" Body: {self.body[:100]}...")
print(f" Attachments: {len(self.attachments)}")
# Usage (builder pattern)
email = (EmailBuilder()
.set_from("admin@company.com")
.add_to("alice@email.com")
.add_to("bob@email.com")
.set_subject("Weekly Report — Python Course Progress")
.set_body("Hi team, here is the weekly course progress report. "
"All modules are on track. Students completed 85% of assignments."))
email.preview()
# Automated report email
print("\n=== Automated Report ===")
stats = {"enrolled": 150, "completed": 85, "avg_score": 78.5}
report_body = f"""Course Statistics:
Enrolled: {stats['enrolled']}
Completed: {stats['completed']}
Completion Rate: {stats['completed']/stats['enrolled']*100:.1f}%
Average Score: {stats['avg_score']}"""
print(report_body)Tip
Tip
Use Jinja2 templates for generating HTML reports. Add CSS styling for professional-looking output.
Diagram
Loading diagram…
Every website works on this model
Common Mistake
Warning
Not handling missing or malformed data in reports. Always validate and clean data before generating output.
Quick Quiz
Practice Task
Note
(1) Generate an HTML report from data. (2) Add charts with matplotlib. (3) Export to PDF using a library like reportlab.