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

0 Comments

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.

01.from django.core.mail.message import EmailMessage
02. 
03.email = EmailMessage()
04.email.subject = "New shirt submitted"
05.email.body = message
06.email.from_email = "ThatAwesomeShirt! <noreply@thatawesomeshirt.com>"
07.email.to = [ "whoever@whatever.com", ]
08. 
09.# Save the file to a temporary file because that's how email attachments work
10.output = StringIO.StringIO()
11.image.save(output, format = "PNG")
12.email.attach(filename = "test.png", mimetype = "image/png", content = output.getvalue())
13.output.close()
14. 
15.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