与Django + uWSGI +发送电子邮件的神秘问题

时间:2011-12-18 02:12:10

标签: python django uwsgi amazon-ses django-email

经过大约1.5小时的硬调试后,我来这里给你写信。


首先,这些是感兴趣的文件:

/project/app/utils.py

from django.core.mail import EmailMultiAlternatives
import threading

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

    def run(self):
        msg = EmailMultiAlternatives(self.subject, self.body, self.from_email, self.recipient_list)
        if self.html:
            msg.attach_alternative(self.html, "text/html")
        print "sending message"
        msg.send(self.fail_silently)
        print "sent."

def send_html_mail(subject, body, from_email, recipient_list, fail_silently=False, html=None, *args, **kwargs):
    EmailThread(subject, body, from_email, [recipient_list], fail_silently, html).start()

/project/app/views.py

[...]
import utils

def my_view(request):
    [...]
    utils.send_html_mail('subject', '<h1>cool things.</h1>', 'Test <test@example.org>', 'my_email@example.org', html='<h1>cool things.</h1>')

/project/app/settings.py

# I use Amazon SES

[...]
EMAIL_BACKEND = 'backends.smtp.SSLEmailBackend'
EMAIL_HOST = 'amazon-server'
EMAIL_PORT = 465
EMAIL_HOST_USER = 'user'
EMAIL_HOST_PASSWORD = 'pass'
EMAIL_USE_TLS = True
[...]

/project/backends/smtp.py

# taken from https://gist.github.com/1486891

import smtplib

from django.core.mail.utils import DNS_NAME
from django.core.mail.backends.smtp import EmailBackend

class SSLEmailBackend(EmailBackend):
    def open(self):
        if self.connection:
            return False
        try:
            self.connection = smtplib.SMTP_SSL(self.host, self.port,
                                           local_hostname=DNS_NAME.get_fqdn())
            if self.username and self.password:
                self.connection.login(self.username, self.password)
            return True
        except:
            if not self.fail_silently:
                raise

好的,现在问题是:

在localhost中

  • 从视图工作
  • 发送电子邮件
  • 从django shell发送电子邮件工作

在我服务器上的部署应用中:

  • 从视图中发送电子邮件无法使用
  • 从django shell发送电子邮件工作

localhost 中的Django shell输出:

# utils.send_html_mail('subject', '<h1>cool things.</h1>', 'Test <test@example.org>', 'my_email@example.org', html='<h1>cool things.</h1>')
sending email
sent.

部署应用中的Django shell输出:

# utils.send_html_mail('subject', '<h1>cool things.</h1>', 'Test <test@example.org>', 'my_email@example.org', html='<h1>cool things.</h1>')
sending email

相同的代码,相同的提交。问题出在msg.send(self.fail_silently)方法print "sent."之前,可能是{{1}},但它是什么?我没有想法。

你呢?

2 个答案:

答案 0 :(得分:3)

您是否已使用--enable-threads?

在uWSGI中启用了线程

答案 1 :(得分:0)

由于threadinguWSGI激活问题,您可以尝试将其添加到您应用的uwsgi配置中:

lazy = true

所以你的代码将在童工分叉后加载。