Sending HTML Emails and Attachments
flowchart TD A["multipart/mixed"] --> B["multipart/alternative"] A --> C["text/csv -- data.csv"] B --> D["text/plain -- the fallback"] B --> E["text/html -- the rich version"] D -.->|"a text-only client shows this"| F["readable everywhere"] E -.->|"a normal client shows this"| G["the client picks the LAST part it can render"] C --> H["Content-Disposition: attachment"]
HTML email + attachment
Section titled “HTML email + attachment”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"))pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading