Send Emails with Python: smtplib, MIME and Attachments
Python's smtplib and email modules let you send emails from any SMTP provider: Gmail, Outlook, SendGrid, or your own server. Supports plain text, HTML, and file attachments.
Simple Text Email with smtplib
import smtplib
from email.mime.text import MIMEText
def send_email(to, subject, body, sender, password,
smtp_host="smtp.gmail.com", smtp_port=587):
msg = MIMEText(body, "plain", "utf-8")
msg["Subject"] = subject
msg["From"] = sender
msg["To"] = to
with smtplib.SMTP(smtp_host, smtp_port) as server:
server.ehlo()
server.starttls()
server.login(sender, password)
server.sendmail(sender, [to], msg.as_string())
print(f"Email sent to {to}")
# Gmail: use an App Password (not your account password)
send_email(
to="customer@example.com",
subject="Your order is ready",
body="Hello,\n\nYour order has been processed successfully.\n\nBest regards.",
sender="mybusiness@gmail.com",
password="abcd efgh ijkl mnop" # 16-character app password
)
HTML Email with Plain Text Fallback
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def send_html_email(to, subject, html, plain_text, sender, password):
msg = MIMEMultipart("alternative")
msg["Subject"] = subject
msg["From"] = sender
msg["To"] = to
msg.attach(MIMEText(plain_text, "plain", "utf-8"))
msg.attach(MIMEText(html, "html", "utf-8"))
with smtplib.SMTP("smtp.gmail.com", 587) as s:
s.starttls()
s.login(sender, password)
s.sendmail(sender, [to], msg.as_string())
print(f"HTML email sent to {to}")
html = """
<html><body>
<h2 style="color:#4a9eff">Your Order #1234</h2>
<p>Your order has been <strong>confirmed</strong> and is on its way.</p>
<a href="https://mystore.com/orders/1234" style="background:#4a9eff;color:white;padding:10px 20px;text-decoration:none;border-radius:4px">View Order</a>
</body></html>
"""
plain = "Your order #1234 has been confirmed.\nView: https://mystore.com/orders/1234"
send_html_email("customer@example.com", "Order Confirmed", html, plain,
"mystore@gmail.com", "app_password")
Send with File Attachments
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
import os
def send_with_attachments(to, subject, body, attachment_paths, sender, password):
msg = MIMEMultipart()
msg["Subject"] = subject
msg["From"] = sender
msg["To"] = to
msg.attach(MIMEText(body, "plain", "utf-8"))
for path in attachment_paths:
with open(path, "rb") as f:
part = MIMEBase("application", "octet-stream")
part.set_payload(f.read())
encoders.encode_base64(part)
name = os.path.basename(path)
part.add_header("Content-Disposition", f'attachment; filename="{name}"')
msg.attach(part)
with smtplib.SMTP("smtp.gmail.com", 587) as s:
s.starttls()
s.login(sender, password)
s.sendmail(sender, [to], msg.as_string())
print(f"Email with {len(attachment_paths)} attachments sent to {to}")
send_with_attachments(
"customer@example.com",
"Your Invoice",
"Please find your invoice attached.",
["invoice_april.pdf", "summary.xlsx"],
"mybusiness@gmail.com",
"app_password"
)
Bulk Mailing from CSV Template
import smtplib
from email.mime.text import MIMEText
import csv
def bulk_mail(csv_contacts, subject_tpl, body_tpl, sender, password):
with open(csv_contacts, encoding="utf-8") as f:
contacts = list(csv.DictReader(f)) # columns: name, email
sent = 0
with smtplib.SMTP("smtp.gmail.com", 587) as server:
server.starttls()
server.login(sender, password)
for c in contacts:
subject = subject_tpl.replace("{name}", c["name"])
body = body_tpl.replace("{name}", c["name"])
msg = MIMEText(body, "plain", "utf-8")
msg["Subject"] = subject
msg["From"] = sender
msg["To"] = c["email"]
try:
server.sendmail(sender, [c["email"]], msg.as_string())
sent += 1
print(f" [{sent}] Sent to {c['email']}")
except Exception as e:
print(f" ERROR {c['email']}: {e}")
print(f"Total sent: {sent}/{len(contacts)}")
bulk_mail(
"customers.csv",
"Hi {name}, we have news for you",
"Hi {name},\n\nWe're reaching out with some exciting updates.\n\nBest regards.",
"newsletter@mycompany.com",
"app_password"
)
SMTP Provider Reference
| Provider | SMTP Host | Port | Method |
|---|---|---|---|
| Gmail | smtp.gmail.com | 587 | STARTTLS |
| Outlook/Hotmail | smtp.office365.com | 587 | STARTTLS |
| Yahoo | smtp.mail.yahoo.com | 587 | STARTTLS |
| Amazon SES | email-smtp.us-east-1.amazonaws.com | 587 | STARTTLS |
| SendGrid | smtp.sendgrid.net | 587 | STARTTLS |
Additional Resource
For converting email attachments between PDF, DOCX, JPG and other formats without any coding, use KaijuConverter — free and no registration required.
Related conversions
Frequent conversions across the catalogue: