Skip to content

Sending HTML Emails and Attachments

HTML email + attachment

smtp_html_attachment.py
import os
import smtplib
from email.message import EmailMessage
from pathlib import Path
 
 
def send_html_with_attachment(to: str, subject: str, html: str, attachment: Path):
    user = os.environ["SMTP_USER"]
    password = os.environ["SMTP_PASS"]
 
    msg = EmailMessage()
    msg["From"] = user
    msg["To"] = to
    msg["Subject"] = subject
 
    msg.set_content("Your email client does not support HTML.")
    msg.add_alternative(html, subtype="html")
 
    data = attachment.read_bytes()
    msg.add_attachment(
        data,
        maintype="application",
        subtype="octet-stream",
        filename=attachment.name,
    )
 
    with smtplib.SMTP("smtp.gmail.com", 587) as smtp:
        smtp.starttls()
        smtp.login(user, password)
        smtp.send_message(msg)
 
 
# send_html_with_attachment("to@example.com", "Report", "<h1>Hi</h1>", Path("report.pdf"))
smtp_html_attachment.py
import os
import smtplib
from email.message import EmailMessage
from pathlib import Path
 
 
def send_html_with_attachment(to: str, subject: str, html: str, attachment: Path):
    user = os.environ["SMTP_USER"]
    password = os.environ["SMTP_PASS"]
 
    msg = EmailMessage()
    msg["From"] = user
    msg["To"] = to
    msg["Subject"] = subject
 
    msg.set_content("Your email client does not support HTML.")
    msg.add_alternative(html, subtype="html")
 
    data = attachment.read_bytes()
    msg.add_attachment(
        data,
        maintype="application",
        subtype="octet-stream",
        filename=attachment.name,
    )
 
    with smtplib.SMTP("smtp.gmail.com", 587) as smtp:
        smtp.starttls()
        smtp.login(user, password)
        smtp.send_message(msg)
 
 
# send_html_with_attachment("to@example.com", "Report", "<h1>Hi</h1>", Path("report.pdf"))

If this helped you, consider buying me a coffee ☕

Buy me a coffee

Was this page helpful?

Let us know how we did