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

16👍

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'])
email.attach_file('Document.pdf')
email.send()
👤xbello

8👍

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)
msg.send()

1👍

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(
    "Subject",
    "Some body."
    "From@example.com",
    [email_to],
)
message.attach("document.pdf", pdf_file.read())
message.send(fail_silently=False) 

Leave a comment