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

gro*_*ser 2 python django

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

任何的想法?

谢谢.

Dan*_*man 8

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

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

  • 2019年有什么变化吗?还是没有办法检查? (2认同)

Nei*_*eil 7

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

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')
Run Code Online (Sandbox Code Playgroud)

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

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
Run Code Online (Sandbox Code Playgroud)

然后看看你的控制台.

要么

EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend'
EMAIL_FILE_PATH = '/tmp/app-messages' # change this to a proper location
Run Code Online (Sandbox Code Playgroud)

然后检查文件.