Django: Send email with attachment

2 Comments

Usually send_mail() will suffice for most emailing functionality, but when you need to attach something, the helpful Django wrapper function won't allow it.

If you need to add attachments to your emails, you'll have to go deeper.

image

Alright, down to the nitty gritty.

01.from django.core.mail.message import EmailMessage
02. 
03.email = EmailMessage()
04.email.subject = "New shirt submitted"
05.email.body = html_message
06.email.from_email = "ThatAwesomeShirt! <no-reply@thatawesomeshirt.com>"
07.email.to = [ "somefakeaddress@hotmail.com", ] <p></p>
08. 
09.email.attach_file("hellokitty.jpg") # Attach a file directly
10. 
11.# Or alternatively, if you want to attach the contents directly
12. 
13.file = open("hellokitty.jpg", "rb")
14.email.attach(filename = "hellokitty.jpg", mimetype = "image/jpeg", content = file.read())
15.file.close()
16. 
17.email.send()

And that is all folks.

Source

Django docs: Sending email

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