metarush/email-fallback

通过SMTP主机发送邮件,如果失败,则回退/故障转移到另一个SMTP主机。还支持轮询模式,将负载分配到所有SMTP主机。

v4.2.0 2023-09-06 15:01 UTC

This package is auto-updated.

Last update: 2024-09-06 17:14:08 UTC


README

通过SMTP主机发送邮件,如果失败,则回退/故障转移到另一个SMTP主机。还支持轮询模式,将负载分配到所有SMTP主机。

注意:此库使用PHPMailer

安装

使用composer安装为metarush/email-fallback

使用方法

定义您的SMTP服务器。您可以添加任意多个。

<?php

use MetaRush\EmailFallback;

$servers = [
    0 => (new EmailFallback\Server)
        ->setHost('host1')
        ->setUser('user1')
        ->setPass('pass2')
        ->setPort(25)
        ->setEncr('TLS'),
    1 => (new EmailFallback\Server)
        ->setHost('host2')
        ->setUser('user2')
        ->setPass('pass2')
        ->setPort(25)
        ->setEncr('TLS')
];

回退服务器将按照定义的顺序使用。您必须从0开始数组键,然后递增1

初始化库

$mailer = (new EmailFallback\Builder)
    ->setServers($servers) // array of Server objects
    ->setFromEmail(string) // "From" email
    ->setTos(array) // array of "To" email
    ->setSubject(string) // email subject
    ->setBody(string) // email body
    ->setFromName(string) // optional: "From Name"
    ->setCcs(array) // optional: array of "CC" emails
    ->setBccs(array) // optional: array of "BCC" emails
    ->setReplyTos(array) // optional: array of "Reply to" emails
    ->setAttachments(array) // optional: array of files already on the server
    ->setDebugLevel(int) // optional: PHPMailer debug level from 0 - 4. Default: 0
    ->setAdminEmails(array) // optional: array of emails that will be notified if fallback occurs
    ->setNotificationFromEmail(string) // if you set an admin email, you must set a "from" email for notifications
    ->setAppName(string) // optional: app name used on notifications
    ->setCustomHeaders(array) // optional: set/add custom headers
    ->build();

重要:您必须使用以下方法发送具有回退的电子邮件

$mailer->sendEmailFallback();

SMTP服务器选择器

如果您想使用不同的服务器,请输入参数中的服务器键

$mailer->sendEmailFallback(1); // send using server with key 1

如果服务器0没有失败但电子邮件发送缓慢,这很有用。例如,在“忘记密码”用户界面中,如果用户可以通过创建“重试”用户界面并使用备用服务器再次发送电子邮件来更快地收到电子邮件。

注意

回退可以回到起点。如果您定义了3个服务器(012)并选择了服务器2来发送电子邮件,它可以回退到服务器0然后是1。如果您输入的键在配置中不存在,则使用0

如果所有服务器都失败,则sendEmailFallback()将抛出异常EmailFallback\Exception

轮询模式

使用轮询模式将负载分配到所有SMTP主机。

要启用轮询模式,您必须使用存储驱动程序来跟踪发送电子邮件时使用的最后服务器。

可用的驱动程序及其配置

文件

$driver = 'files';
$driverConfig = [
    'path' => '/var/www/example/emailFallbackCache/'
];

memcached

$driver = 'memcached';
$driverConfig = [
    'host'         => '127.0.0.1',
    'port'         => 11211,
    'saslUser'     => '',
    'saslPassword' => ''
];

注意:目前仅支持单个服务器/非分布式memcached。

redis

$driver = 'redis';
$driverConfig = [
    'host'      => '127.0.0.1',
    'port'      => 6379,
    'password'  => '',
    'database'  => 0
];

注意:如果可用,请使用memcachedredis,因为不推荐在重用场景中使用files

选择驱动程序后,在->build();方法之前设置以下内容

->setRoundRobinMode(true)
->setRoundRobinDriver($driver)
->setRoundRobinDriverConfig($driverConfig)