Tuesday, January 17, 2012

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

0 comments:

Post a Comment

Leave your thoughts ...

---
If you are having trouble with copy/pasting in comments, you need to sign in or click 'Preview'.

For more information about this Firefox bug, see here.