Python 测试邮件发送

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3728528/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:26:52  来源:igfitidea点击:

Testing email sending

pythondjangoemailsmtpdjango-testing

提问by RadiantHex

Any tips on testing email sending? Other than maybe creating a gmailaccount, especially for receiving those emails?

关于测试电子邮件发送的任何提示?除了可能创建一个Gmail帐户,尤其是为了接收这些电子邮件?

I would like to, maybe, store the emails locally, within a folder as they are sent.

我想,也许,在发送电子邮件时将它们存储在一个文件夹中。

采纳答案by Bernhard Vallant

You can use a file backend for sending emailswhich is a very handy solution for development and testing; emails are not sent but stored in a folder you can specify!

您可以使用文件后端发送电子邮件,这是一个非常方便的开发和测试解决方案;电子邮件不会发送,而是存储在您可以指定的文件夹中!

回答by pyfunc

Patching SMTPLib for testing purposes can help test sending mails without sending them.

为测试目的修补 SMTPLib 可以帮助测试发送邮件而不发送邮件。

回答by Steve Jalim

For any project that doesn't require sending attachments, I use django-mailer, which has the benefit of all outbound emails ending up in a queue until I trigger their sending, and even after they've been sent, they are then logged - all of which is visible in the Admin, making it easy to quickly check what you emailing code is trying to fire off into the intertubes.

对于不需要发送附件的任何项目,我使用django-mailer,它的好处是所有出站电子邮件都在队列中结束,直到我触发它们的发送,甚至在它们被发送之后,它们也会被记录 -所有这些都在 Admin 中可见,因此可以轻松快速地检查您通过电子邮件发送的代码试图发射到 intertubes 中的内容。

回答by Davor Lucic

Django test framework has some built in helpers to aid you with testing e-mail service.

Django 测试框架有一些内置的帮助程序来帮助你测试电子邮件服务

Example from docs (short version):

来自文档的示例(简短版本):

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

class EmailTest(TestCase):
    def test_send_email(self):
        mail.send_mail('Subject here', 'Here is the message.',
            '[email protected]', ['[email protected]'],
            fail_silently=False)
        self.assertEqual(len(mail.outbox), 1)
        self.assertEqual(mail.outbox[0].subject, 'Subject here')

回答by Josh K

Django also has an in-memory email backend. More details in the docs under In-memory backend. This is present in Django 1.6 not sure if it's present in anything earlier.

Django 也有一个内存电子邮件后端。更多详细信息,请参阅In-memory backend下的文档。这存在于 Django 1.6 中,不确定它是否存在于更早的版本中。

回答by kiril

If you are into unit-testing the best solution is to use the In-memory backendprovided by django.

如果您进行单元测试,最好的解决方案是使用django 提供的内存后端

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

Take the case of use it as a py.testfixture

以将其用作py.test夹具为例

@pytest.fixture(autouse=True)
def email_backend_setup(self, settings):
    settings.EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend'  

In each test, the mail.outboxis reset with the server, so there are no side effects between tests.

在每次测试中,mail.outbox都与服务器一起重置,因此测试之间没有副作用。

from django.core import mail

def test_send(self):
    mail.send_mail('subject', 'body.', '[email protected]', ['[email protected]'])
    assert len(mail.outbox) == 1

def test_send_again(self):
    mail.send_mail('subject', 'body.', '[email protected]', ['[email protected]'])
    assert len(mail.outbox) == 1

回答by Greg Dubicki

Use MailHog

使用MailHog

Inspired by MailCatcher, easier to install.

Built with Go - MailHog runs without installation on multiple platforms.

受 MailCatcher 启发,更易于安装。

使用 Go 构建 - MailHog 无需安装即可在多个平台上运行。



Also, it has a component called Jim, the MailHog Chaos Monkey, which enables you to test sending emails with various problems happening:

此外,它还有一个名为Jim的组件,即MailHog Chaos Monkey,它使您能够测试在发生各种问题时发送电子邮件:

What can Jim do?

  • Reject connections
  • Rate limit connections
  • Reject authentication
  • Reject senders
  • Reject recipients

吉姆能做什么?

  • 拒绝连接
  • 速率限制连接
  • 拒绝身份验证
  • 拒绝发件人
  • 拒绝收件人

Read more about it here.

在此处阅读更多相关信息。



(Unlike original mailcatcher, which failed on me when sending emails with emoji, encoded in UTF-8and it WASN'T really fixed in the current release, MailHog just works.)

(与原始的 mailcatcher 不同,它在发送带有表情符号的电子邮件时失败了,以 UTF-8 编码,并且在当前版本中并没有真正修复,MailHog 可以正常工作。)

回答by frogcoder

Why not start your own really simple SMTP Server by inherit from smtpd.SMTPServerand threading.Thread:

为什么不通过继承自smtpd.SMTPServer和来启动您自己的非常简单的 SMTP 服务器threading.Thread

class TestingSMTPServer(smtpd.SMTPServer, threading.Thread):
    def __init__(self, port=25):
        smtpd.SMTPServer.__init__(
            self,
            ('localhost', port),
            ('localhost', port),
            decode_data=False
        )
        threading.Thread.__init__(self)

    def process_message(self, peer, mailfrom, rcpttos, data, **kwargs):
        self.received_peer = peer
        self.received_mailfrom = mailfrom
        self.received_rcpttos = rcpttos
        self.received_data = data

    def run(self):
        asyncore.loop()

process_message is called whenever your SMTP Server receive a mail request, you can do whatever you want there.

每当您的 SMTP 服务器收到邮件请求时都会调用 process_message,您可以在那里做任何您想做的事情。

In the testing code, do something like this:

在测试代​​码中,执行以下操作:

smtp_server = TestingSMTPServer()
smtp_server.start()
do_thing_that_would_send_a_mail()
smtp_server.close()
self.assertIn(b'hello', smtp_server.received_data)

Just remember to close()the asyncore.dispatcherby calling smtp_server.close()to end the asyncore loop(stop the server from listening).

只记得close()asyncore.dispatcher调用smtp_server.close()结束asyncore循环(停止从听音服务器)。

回答by AgilePro

If you have a TomCat server available, or other servlet engine, then a nice approach is "Post Hoc" which is a small server that looks to the application exactly like a SMTP server, but it includes a user interface that allows you to view and inspect the email messages that were sent. It is open source and freely available.

如果您有可用的 TomCat 服务器或其他 servlet 引擎,那么一个不错的方法是“Post Hoc”,它是一个看起来与 SMTP 服务器完全一样的应用程序的小型服务器,但它包含一个用户界面,允许您查看和检查发送的电子邮件。它是开源的,可以免费获得。

Find it at: Post Hoc GitHub Site

在以下位置找到它:Post Hoc GitHub 站点

See the blog post: PostHoc: Testing Apps that Send Email

请参阅博客文章: PostHoc:测试发送电子邮件的应用程序

回答by shacker

Tying a few of the pieces here together, here's a straightforward setup based on filebased.EmailBackend. This renders a list view linking to the individual log files, which have conveniently timestamped filenames. Clicking a link in the list displays that message in the browser (raw):

将这里的一些部分联系在一起,这是一个基于filebased.EmailBackend. 这将呈现链接到单个日志文件的列表视图,这些文件具有方便的时间戳文件名。单击列表中的链接会在浏览器中显示该消息(原始):

Settings

设置

EMAIL_BACKEND = "django.core.mail.backends.filebased.EmailBackend"
EMAIL_FILE_PATH = f"{MEDIA_ROOT}/email_out"

View

看法

import os

from django.conf import settings
from django.shortcuts import render

def mailcheck(request):

    path = f"{settings.MEDIA_ROOT}/email_out"
    mail_list = os.listdir(path)

    return render(request, "mailcheck.html", context={"mail_list": mail_list})

Template

模板

{% if mail_list %}
  <ul>
  {% for msg in mail_list %}
    <li>
      <a href="{{ MEDIA_URL }}email_out/{{msg}}">{{ msg }}</a>
    </li>
  {% endfor %}
  </ul>
{% else %}
  No messages found.
{% endif %}

urls

网址

path("mailcheck/", view=mailcheck, name="mailcheck"),