Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending email asynchronously with attachment in Django

Tags:

email

django

I am using below code to send email with pdf attachment. But, it is thowing an error - "assertion no content". I am not sure why it is so. I am able to send the email with pdf synchronously as well as send email async with no pdf. (Using Django 1.3)

from django.core.mail import EmailMultiAlternatives
import threading
from django.core.mail import send_mail

class EmailThread(threading.Thread):
    def __init__(self, subject, body, from_email, recipient_list, fail_silently, html,pdf):
        self.subject = subject
        self.body = body
        self.recipient_list = recipient_list
        self.from_email = from_email
        self.fail_silently = fail_silently
        self.html = html
        self.pdf = pdf
        threading.Thread.__init__(self)

    def run(self):
        msg = EmailMultiAlternatives(self.subject, self.body, self.from_email, self.recipient_list)
        msg.attach('ticket.pdf',self.pdf,'application/pdf')
        if self.html:
            msg.attach_alternative(self.html, "text/html")
        msg.send(self.fail_silently)


def send_mail(subject, body, from_email, recipient_list, fail_silently=True, html=None,pdf=None, *args, **kwargs):
    EmailThread(subject, body, from_email, recipient_list, fail_silently, html, pdf).start()
like image 593
John Avatar asked Nov 12 '22 16:11

John


1 Answers

Think about what happens with your code when you try to send an email without an attachment, as is quite expected with send_mail.

  def run(self):
        msg = EmailMultiAlternatives(self.subject, self.body, self.from_email, self.recipient_list)
        msg.attach('ticket.pdf',self.pdf,'application/pdf')
        #                       ^^^^^^^^ is None. 
        if self.html:
            msg.attach_alternative(self.html, "text/html")
        msg.send(self.fail_silently)

Yes, you would end up trying to attach a file with no content. You need to make sure you only attach only if there's something to attach. What would be the point anyways? Some ticket.pdf that's an empty string?

Also, I second the idea of using django-mailer.

like image 68
Yuji 'Tomita' Tomita Avatar answered Nov 15 '22 05:11

Yuji 'Tomita' Tomita