我正在使用以下代码发送带有 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()
最佳答案
想一想当您尝试发送没有附件的电子邮件时,您的代码会发生什么,正如 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
.
关于django - 在 Django 中使用附件异步发送电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13722802/