perfectpanel/yii2-sendgrid

支持批量发送的 SendGrid 邮件扩展,用于 Yii2。此扩展旨在取代所有其他扩展!您唯一需要的 Yii2 SendGrid 扩展!

v2.1 2022-09-12 05:11 UTC

This package is not auto-updated.

Last update: 2024-09-23 15:54:28 UTC


README

支持批量发送的 SendGrid 邮件扩展,用于 Yii2。此扩展旨在取代所有其他扩展!您唯一需要的 Yii2 SendGrid 扩展!

安装

安装此扩展的首选方式是通过 composer

运行以下命令之一

php composer.phar require --prefer-dist perfectpanel/yii2-sendgrid

或将以下内容添加到您应用程序的 composer.json 文件的 require 部分中。

"perfectpanel/yii2-sendgrid": "1.0"

然后,按照如下方式在您的 main-local.php(高级)或 web.php(基本)中配置 mailer 组件

请记住将 apiKey 替换为您的 SendGrid API 密钥。它必须有发送电子邮件的权限。

'mailer' => [
    'class' => 'shulyak\sendgrid\Mailer',
    'viewPath' => '@common/mail',
    // send all mails to a file by default. You have to set
    // 'useFileTransport' to false and configure a transport
    // for the mailer to send real emails.
    'useFileTransport' => false,
    'apiKey' => '[YOUR_SENDGRID_API_KEY]',
],

使用

单次邮件发送

批量邮件发送

$user = \common\models\User::find()->select(['id', 'username', 'email'])->where(['id' => 1])->one();

$mailer = Yii::$app->mailer;
$message = $mailer->compose()
    ->setTo([$user->email => $user->username])      // or just $user->email
    ->setFrom(['alerts@example.com' => 'Alerts'])
    ->setReplyTo('noreply@example.com')
    ->setSubject('Hey -username-, Read This Email')
    ->setHtmlBody('Dear -username-,<br><br>My HTML message here')
    ->setTextBody('Dear -username-,\n\nMy Text message here')
    //->setTemplateId('1234')
    //->addSection('%section1%', 'This is my section1')
    //->addHeader('X-Track-UserType', 'admin')
    //->addHeader('X-Track-UID', Yii::$app->user->id)
    //->addCategory('tests')
    //->addCustomArg('test_arg', 'my custom arg')
    //->setSendAt(time() + (5 * 60))
    //->setBatchId(Yii::$app->mailer->createBatchId())
    //->setIpPoolName('7')
    //->attach(Yii::getAlias('@webroot/files/attachment.pdf'))
    ->addSubstitution('-username-', $user->username)
    ->send();

if ($message === true) {
    echo 'Success!';
    echo '<pre>' . print_r($mailer->getRawResponses(), true) . '</pre>';
} else {
    echo 'Error!<br>';
    echo '<pre>' . print_r($mailer->getErrors(), true) . '</pre>';
}

如果您要发送给多个收件人,您需要使用以下方法进行批量发送。

注意: SendGrid 支持的最大收件人数量为 1,000 人。这是收件人、密送和抄送地址的总数。我建议使用 500 作为批量大小。这应该足以高效处理数千封电子邮件,而不会因意外违反 1,000 个收件人规则而出现错误。如果您没有使用任何密送或抄送地址,您 可以 将批量数量稍微提高一些。理论上,您应该能够做到 1,000 人,但我可能会将其限制在 950 人,以留出一些余地。

$mailer = Yii::$app->mailer;
//$batchId = Yii::$app->mailer->createBatchId();
//$sendTime = time() + (5 * 60);      // 5 minutes from now

foreach (User::find()->select(['id', 'username', 'email'])->batch(500) as $users)
{

    $message = $mailer->compose()
        ->setFrom(['alerts@example.com' => 'Alerts'])
        ->setReplyTo('noreply@example.com')
        ->setSubject('Hey -username-, Read This Email')
        ->setHtmlBody('Dear -username-,<br><br>My HTML message here')
        ->setTextBody('Dear -username-,\n\nMy Text message here');
        //->setTemplateId('1234')
        //->addSection('%section1%', 'This is my section1')
        //->addHeader('X-Track-UserType', 'admin')
        //->addHeader('X-Track-UID', Yii::$app->user->id)
        //->addCategory('tests')
        //->addCustomArg('test_arg', 'my custom arg')
        //->setSendAt($sendTime)
        //->setBatchId($batchId)
        //->setIpPoolName('7')
        //->attach(Yii::getAlias('@webroot/files/attachment.pdf'));

    foreach ( $users as $user )
    {
        // A Personalization Object Helper would be nice here...
        $personalization = [
            'to' => [$user->email => $user->username],      // or just `email@example.com`
            //'cc' => 'cc@example.com',
            //'bcc' => 'bcc@example.com',
            //'subject' => 'Hey -username-, Custom message for you!',
            //'headers' => [
            //    'X-Track-RecipId' => $user->id,
            //],
            'substitutions' => [
                '-username-' => $user->username,
            ],
            //'custom_args' => [
            //    'user_id' => $user->id,
            //    'type' => 'marketing',
            //],
            //'send_at' => $sendTime,
        ];
        $message->addPersonalization($personalization);
    }

    $result = $message->send();
}

if ($result === true) {
    echo 'Success!';
    echo '<pre>' . print_r($mailer->getRawResponses(), true) . '</pre>';
} else {
    echo 'Error!<br>';
    echo '<pre>' . print_r($mailer->getErrors(), true) . '</pre>';
}

已知问题

addSection() - SendGrid API 中存在一个当前问题,导致部分无法正常工作。

  • setSendAt() - SendGrid API 中存在一个当前问题,使用 send_at 时显示的是队列时间,而不是实际发送邮件的时间。
  • setReplyTo() - SendGrid PHP API 中存在一个当前问题,回复地址只接受字符串形式的电子邮件地址。因此,您不能设置名称。
  • 待办事项

还有一些事情我没有完成

我还没有处理一些事情

  • ASM
  • 邮件设置
  • 跟踪设置

我计划在以后处理它们。如果您能帮忙,请随时提供帮助 :)