我使用以下代码发送带有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()
答案 0 :(得分: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
。