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

1 投票
2 回答
1429 浏览
提问于 2025-04-17 08:34

我花了大约一个半小时在调试上,现在来跟你说说我的情况。


首先,这些是我关注的文件:

/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

好了,现在说说问题:

在本地环境下:

  • 从视图发送邮件是可以的
  • 从django命令行发送邮件也是可以的

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

  • 从视图发送邮件不行
  • 从django命令行发送邮件可以

本地环境下的django命令行输出:

# 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命令行输出:

# 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."之前,但这到底是什么问题呢?我没有头绪。

你有什么想法吗?

2 个回答

0

由于threading在使用uWSGI时出现了激活问题,你可以尝试在你的应用的uwsgi配置中添加以下内容:

lazy = true

这样你的代码将在子进程创建后加载。

3

你有没有在uWSGI中用--enable-threads这个选项开启线程功能?

撰写回答