ingenerator/mailhook

从本地 postfix 服务器收集邮件,以便您可以在开发期间检查、断言以及对发送的邮件进行其他操作。

v1.2.1 2023-08-08 20:16 UTC

This package is auto-updated.

Last update: 2024-09-08 22:30:51 UTC


README

License Build status Scrutinizer Code Quality Latest Stable Version Total Downloads Latest Unstable Version

A php library that collects email from a local postfix server so you can inspect, assert and otherwise mess around with emails sent during development.

安装

将 mailhook 添加到 composer.json 中的开发依赖项

{
  "require-dev": {
    "ingenerator/mailhook" : "~0.1@dev"
  }
}

您还需要配置 postfix 将所有外发邮件发送到本地文件。如果您使用 chef,请参阅我们的 postfix-relay cookbook,并将 "postfix_relay.allow_live_email" 属性配置为 false。要手动安装,请执行 apt-get install postfix,然后按以下方式追加到 postfix 配置文件。

# /etc/postfix/main.cf
default_transport = fs_mail
# /etc/postfix/master.cf

#
# fs_mail sends all outgoing mail to a single local file
#
fs_mail    unix  -       n       n       -       -       pipe
   flags=FB user=ubuntu argv=tee -a /tmp/outgoing_mail.dump

使用 mailhook 检查消息

显然,您通常会使用 mailhook 在某种类型的测试框架中(例如 Behat)。但这个非常简单的例子应该能给您一个如何使用它的想法

$mailhook = new \Ingenerator\Mailhook\Mailhook('/tmp/outgoing_mail.dump');
// You'll usually want to purge the file before your tests, to ensure you have a clean state
$mailhook->purge();

run_my_code_that_should_send_emails();

$mailhook->refresh();

$mails = $mailhook->getEmails();
assert(count($mails) === 1, 'An email was sent');

获取更多细节

您可能想知道的不仅仅是发送了包含某些内容的邮件给某个用户。例如,您可能想断言已向特定用户发送了邮件。为此,您可以使用包内构建的匹配/断言框架

$mail   = $mailhook->assert()->firstEmailMatching(new EmailSentToMatcher('test@ingenerator.com'));
$emails = $mailhook->assert()->emailsMatching(new EmailSentToMatcher('test@ingenerator.com'));
$mailhook->assert()->noEmailMatching(new AnyEmailMatcher);

这些断言方法在失败时抛出异常,在成功时返回匹配的邮件。您可以通过实现 EmailMatcher 接口并提供类的实例来添加自己的自定义标准。

您可以将多个匹配器传递给断言发送了符合所有标准的邮件。例如,如果您正在测试常见的“密码重置邮件”功能,您可以执行类似以下操作

$mailhook = new \Ingenerator\Mailhook\Mailhook('/tmp/outgoing_mail.dump');
$mailhook->purge();

submit_my_password_reset_form();

$mail = $mailhook->assert()->firstEmailMatching(
    new EmailSentToMatcher('test@ingenerator.com'),
    new EmailWithLinkMatcher('/reset/')
);
$links  = $mail->getLinksMatching('/reset/');

visit_page_and_reset_password($links[0]->getUrl());

测试和开发

mailhook 有一个 PhpSpec 规范套件。使用 bin/phpspec run 运行它们。只有当贡献伴随着良好结构的规范时,才会接受贡献。使用 composer 安装应该会为您提供一个工作所需的所有内容。

许可证

mailhook 版权所有 2012-2014 inGenerator Ltd,并使用 BSD 许可证 发布。