如何使用django发送异步电子邮件

时间:2010-12-15 05:48:22

标签: python django email asynchronous

这是我的代码:

class EmailThread(threading.Thread):
    def __init__(self, subject, html_content, recipient_list):
        self.subject = subject
        self.recipient_list = recipient_list
        self.html_content = html_content
        threading.Thread.__init__(self)

    def run (self):
        msg = EmailMultiAlternatives(self.subject, self.html_content, EMAIL_HOST_USER, self.recipient_list)
        #if self.html_content:
        msg.attach_alternative(True, "text/html")
        msg.send()

def send_mail(subject, html_content, recipient_list):
    EmailThread(subject, html_content, recipient_list).start()

它不发送电子邮件。我该怎么办?

3 个答案:

答案 0 :(得分:26)

现在好了;

class EmailThread(threading.Thread):
    def __init__(self, subject, html_content, recipient_list):
        self.subject = subject
        self.recipient_list = recipient_list
        self.html_content = html_content
        threading.Thread.__init__(self)

    def run (self):
        msg = EmailMessage(self.subject, self.html_content, EMAIL_HOST_USER, self.recipient_list)
        msg.content_subtype = "html"
        msg.send()

def send_html_mail(subject, html_content, recipient_list):
    EmailThread(subject, html_content, recipient_list).start()

答案 1 :(得分:12)

从长远来看,使用第三方Django应用程序(例如django-mailer)来处理各种异步电子邮件发送/管理要求可能是一个很好的决定。

答案 2 :(得分:1)

在查看基于芹菜等的更复杂的解决方案后,我发现了django-post_office(https://github.com/ui/django-post_office)这是一个非常简单的数据库+ cron作业插件,需要5分钟才能启动并运行。在我的本地开发机器和Heroku上都能很好地工作。