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.', '[email protected]', ['[email protected]'])
email.attach_file('Document.pdf')
email.send()

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()

Tags:

Django