Django: Send email with attachment

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.

from django.core.mail.message import EmailMessage

email = EmailMessage()
email.subject = "New shirt submitted"
email.body = html_message
email.from_email = "ThatAwesomeShirt! <no-reply@thatawesomeshirt.com>"
email.to = [ "somefakeaddress@hotmail.com", ]



email.attach_file("hellokitty.jpg") # Attach a file directly

# Or alternatively, if you want to attach the contents directly

file = open("hellokitty.jpg", "rb")
email.attach(filename = "hellokitty.jpg", mimetype = "image/jpeg", content = file.read())
file.close()

email.send()

And that is all folks.

Source

Django docs: Sending email

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