jlorente/laravel-sendgrid

Laravel 对 SendGrid PHP SDK 的集成。

1.0.4 2022-09-07 12:39 UTC

This package is auto-updated.

Last update: 2024-09-07 16:39:09 UTC


README

Laravel 对 SendGrid PHP SDK 的集成,包括一个通知通道。

安装

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

安装 composer 后,您可以使用以下命令安装扩展

$ php composer.phar require jlorente/laravel-sendgrid

或添加

...
    "require": {
        "jlorente/laravel-sendgrid": "*"
    }

到您的 composer.json 文件的 require 部分。

配置

  1. 在您的 config/app.php 服务提供者列表中注册 ServiceProvider。

config/app.php

return [
    //other stuff
    'providers' => [
        //other stuff
        \Jlorente\Laravel\SendGrid\SendGridServiceProvider::class,
    ];
];
  1. 将以下外观添加到 $aliases 部分。

config/app.php

return [
    //other stuff
    'aliases' => [
        //other stuff
        'SendGrid' => \Jlorente\Laravel\SendGrid\Facades\SendGrid::class,
    ];
];
  1. 发布包配置文件。
$ php artisan vendor:publish --provider='Jlorente\Laravel\SendGrid\SendGridServiceProvider'
  1. config/sendgrid.php 文件中设置 api_key 或使用预定义的 env 变量。

config/sendgrid.php

return [
    'api_key' => 'YOUR_API_KEY',
    //other configuration
];

或 .env

//other configurations
SENDGRID_API_KEY=<YOUR_API_KEY>

使用

您可以使用外观别名 SendGrid 执行 API 调用。认证参数将自动注入。

SendGrid::send($mail);

通知通道

此包包括一个通知通道,允许您集成 SendGrid 发送电子邮件服务。

有关 Laravel 通知的更多信息,请参阅 此页面

SendGridEmailChannel

如果您想通过 SendGrid 发送电子邮件,应在通知类中定义 toSendGrid 方法。此方法将接收一个 $notifiable 实例,并应返回一个 \SendGrid\Mail\Mail 实例。

/**
 * Get the Mail object instance.
 *
 * @param  mixed  $notifiable
 * @return \SendGrid\Mail\Mail
 */
public function toSendGrid($notifiable)
{
    $mail = new \SendGrid\Mail\Mail();
    $mail->setFrom();
    $mail->setTemplateId('d-4n23blaasjdgdg3242');
    $mail->addDynamicTemplateData('username', 'John');

    return $mail;
}

完成后,必须将通知通道添加到通知 via() 方法的数组中

/**
 * Get the notification channels.
 *
 * @param  mixed  $notifiable
 * @return array|string
 */
public function via($notifiable)
{
    return [SendGridEmailChannel::class];
}

通知路由

当通过 SendGrid 通道发送通知时,通知系统将自动在通知实体上查找电子邮件属性。如果您想自定义它,应在实体上定义 routeNotificationForSendGrid 方法

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * Route notifications for the SendGrid SMS channel.
     *
     * @param  \Illuminate\Notifications\Notification  $notification
     * @return string
     */
    public function routeNotificationForSendGrid($notification)
    {
        return $this->email;
    }
}

许可证

版权 © 2021 José Lorente Martín jose.lorente.martin@gmail.com.

根据 BSD 3-Clause 许可证授权。有关详细信息,请参阅 LICENSE.txt。