Django: Sending out a HTML email... with attachments

The usual django mail.send_mail() is sufficient for most cases if you're sending by plain text. It does leave a little to be desired, such as changing it to a HTML format or something.

However, if you're after an email with attachments, you'll have to get a little busy.

from django.core.mail.message import EmailMessage

email = EmailMessage()
email.subject = "New shirt submitted"
email.body = message
email.from_email = "ThatAwesomeShirt! <noreply@thatawesomeshirt.com>"
email.to = [ "whoever@whatever.com", ]

# Save the file to a temporary file because that's how email attachments work
output = StringIO.StringIO()
image.save(output, format = "PNG")
email.attach(filename = "test.png", mimetype = "image/png", content = output.getvalue())
output.close()

email.send()

Optionally, you can add email.content_subtype = "html" to set the email to be a HTML email.

tumblr_lyegh0j09a1qdlh1io1_400

No more trying to force people into reading plain text emails!

Source

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog