5

我正在使用以下代码发送带有 pdf 附件的电子邮件。但是,这是一个错误 - “断言没有内容”。我不确定为什么会这样。我可以同步发送带有 pdf 的电子邮件,也可以异步发送不带 pdf 的电子邮件。(使用 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()
4

1 回答 1

1

想一想当您尝试发送不带附件的电子邮件时,您的代码会发生什么,这与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)

是的,您最终会尝试附加一个没有内容的文件。您需要确保仅在有要附加的东西时才附加。无论如何,这有什么意义?有些ticket.pdf是空字符串?

另外,我赞同使用django-mailer.

于 2012-12-06T04:24:31.263 回答