aliobeidat/yii2-sendgrid

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

安装: 20

依赖项: 0

建议者: 0

安全性: 0

星标: 0

关注者: 2

分支: 0

开放性问题: 0

类型:yii2-extension

dev-master 2022-12-01 15:36 UTC

This package is auto-updated.

Last update: 2024-09-29 06:09:09 UTC


README

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

安装

通过以下方式安装此扩展:通过 composer

运行以下命令之一:

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

或者

"aliobeidat/yii2-sendgrid": "dev-master"

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

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

'mailer' => [
    'class' => 'aliobeidat\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]',
],

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

用法

单次发送

$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>';
}

批量发送

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

$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>';
}

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

待办事项

还有一些事情我没有完成

  • ASM
  • mail_settings
  • tracking_settings

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