jorisvaesen/cakephp-sendgrid

CakePHP 的 Sendgrid 封装器

安装: 262

依赖者: 0

建议者: 0

安全: 0

星标: 0

关注者: 1

分支: 0

公开问题: 0

类型:cakephp-plugin

0.3.3 2019-09-14 18:47 UTC

This package is auto-updated.

Last update: 2024-09-15 06:21:08 UTC


README

安装

您可以使用 composer 将此插件安装到您的 CakePHP 应用程序中。

安装 composer 包的推荐方法是

composer require jorisvaesen/cakephp-sendgrid

config/bootstrap.php 中加载插件

Plugin::load('JorisVaesen/Sendgrid', ['bootstrap' => true]);

配置

方法 1(使用 ENV)

插件从 dotenv 加载以下内容

SENDGRID_API_KEY="your_sendgrid_api_key"

方法 2(使用 app.php)

在 app.php 中设置 Sendgrid API 密钥

'Sendgrid' => [
    'apiKey' => 'your_sendgrid_api_key',
],

方法 3(硬编码)

在您的 app.php 文件中,在 EmailTransport 项中添加

'EmailTransport' => [
        ...
        'sendgrid' => [
            'className' => '\JorisVaesen\Sendgrid\Mailer\Transport\SendgridTransport',
            'password' => 'your_sendgrid_api_key',
        ],
        ...
    ],

要默认使用它,请在 app.php 中将默认传输设置为 sendgrid

'Email' => [
    'default' => [
        'transport' => 'sendgrid',
    ],
],

回调

如果您想使用 Sendgrid API 方法,而这些方法在 CakePHP 中没有等效方法,您可以使用回调配置

'EmailTransport' => [
        ...
        'sendgrid' => [
            'className' => '\JorisVaesen\Sendgrid\Mailer\Transport\SendgridTransport',
            'password' => 'your_sendgrid_api_key',
            'callback' => function (\SendGrid\Mail\Mail $sendgridEmail, \Cake\Mailer\Email $cakephpEmail) {
                if ($cakephpEmail->getSubject() === 'If you open this mail...') {
                    $sendgridEmail->setOpenTracking(true);
                }
                
                return $sendgridEmail;
            },
        ],
        ...
    ],

用法

$email = new Email('default');
$email->viewBuilder()->setLayout('default);
/* @var \Sendgrid\Response $response */
$response = $email
    ->setProfile('sendgrid')    // optional when you've set sendgrid as the default transport in configuration
    ->setEmailFormat('html')
    ->setSender('noreply@example.com', 'Example sender')
    ->setFrom('from@example.com', 'Example From')
    ->setReplyTo('replyTo@example.com', 'Example ReplyTo')
    ->setTo('to@example.com', 'Example To')
    ->setSubject('Sample email')
    ->setTemplate('default')
    ->setViewVars([])
    ->send();
    
return $response->statusCode() === 202;

www.datrix.be