[Fixed]-Attaching pdf's to emails in django


The docs say (https://docs.djangoproject.com/en/dev/topics/email/#the-emailmessage-class):

Not all features of the EmailMessage class are available through the send_mail() and related wrapper functions. If you wish to use advanced features, such as BCC’ed recipients, file attachments, or multi-part email, you’ll need to create EmailMessage instances directly.

So you have to create an EmailMessage:

from django.core.mail import EmailMessage

email = EmailMessage(
    'Subject here', 'Here is the message.', 'from@me.com', ['email@to.com'])


If you want to attach a file that is stored in memory you use just attach

msg = EmailMultiAlternatives(mail_subject, text_content, settings.DEFAULT_FROM_EMAIL, [instance.email])
msg.attach_alternative(message, "text/html")
pdf = render_to_pdf('some_invoice.html')
msg.attach('invoice.pdf', pdf)


One scenario is that the file is kept on disk (for example, in a repository) and accessed via a fixed path. It is safer (and probably easier) to use the field in the model. Assuming that PDF file is stored in a FileField of some model_instance object:

from django.core.mail import EmailMessage

pdf_file = model_instance.file  # <- here I am accessing the file attribute, which is a FileField
message = EmailMessage(
    "Some body."
message.attach("document.pdf", pdf_file.read())

Leave a comment