如何通过Django / Python正确发送电子邮件?

时间:2011-03-21 07:18:26

标签: python django

我需要知道,如果正确发送电子邮件以执行多项操作,但该函数始终返回True。

有什么想法吗?

谢谢你。

4 个答案:

答案 0 :(得分:7)

无法检查是否实际收到过邮件。这不是因为Django失败,而是电子邮件工作方式的结果。

如果您需要某种形式的明确送货确认,则需要使用电子邮件之外的其他内容。

答案 1 :(得分:7)

运行单元测试时,电子邮件将EmailMessage对象存储在django.core.mail.outbox的列表中,然后您可以在测试类中执行所需的任何检查。以下是django's docs的示例。

from django.core import mail
from django.test import TestCase

class EmailTest(TestCase):
    def test_send_email(self):
        # Send message.
        mail.send_mail('Subject here', 'Here is the message.',
            'from@example.com', ['to@example.com'],
            fail_silently=False)

        # Test that one message has been sent.
        self.assertEqual(len(mail.outbox), 1)

        # Verify that the subject of the first message is correct.
        self.assertEqual(mail.outbox[0].subject, 'Subject here')

或者,如果您只是想在开发期间目视检查电子邮件的内容,可以将EMAIL_BACKEND设置为:

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

然后看看你的控制台。

EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend'
EMAIL_FILE_PATH = '/tmp/app-messages' # change this to a proper location

然后检查文件。

答案 2 :(得分:3)

关于将Django与This post集成的

Postmark描述了如何跟进电子邮件传递。

答案 3 :(得分:2)

如果出现错误,send_mail应引发异常。 fail_silently参数可以忽略该错误。你错误地启用了这个选项吗?

我希望它有所帮助