You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Laravel中向SendGrid邮件列表添加注册用户邮箱?

解决方案

1. 基础准备

  • 安装sendgrid/sendgrid-php包:
    composer require sendgrid/sendgrid-php
    
  • 在SendGrid后台获取API密钥(需拥有邮件列表管理权限),以及目标邮件列表的List ID(路径:Marketing > Contacts > Lists)
  • 在Laravel的.env文件中配置密钥和列表ID:
    SENDGRID_API_KEY=你的API密钥
    SENDGRID_LIST_ID=你的邮件列表ID
    

2. 注册时添加邮箱到SendGrid列表

Laravel用户注册默认会触发Illuminate\Auth\Events\Registered事件,推荐通过事件监听实现逻辑,也可直接修改注册控制器。

方法一:事件监听器实现

  1. 生成监听器文件:
    php artisan make:listener AddUserToSendGridList --event=Illuminate\Auth\Events\Registered
    
  2. 在app/Listeners/AddUserToSendGridList.php中编写核心逻辑:
    <?php
    
    namespace App\Listeners;
    
    use Illuminate\Auth\Events\Registered;
    use SendGrid;
    use SendGrid\Contacts\Recipient;
    
    class AddUserToSendGridList
    {
        public function handle(Registered $event)
        {
            $user = $event->user;
            
            // 初始化SendGrid客户端
            $sendgrid = new SendGrid(env('SENDGRID_API_KEY'));
            
            // 构建收件人对象
            $recipient = new Recipient();
            $recipient->setEmail($user->email);
            // 可选:添加用户姓名等额外属性
            $recipient->setFirstName($user->name);
            
            // 组装请求体,将用户添加到指定列表
            $requestBody = [
                'list_ids' => [env('SENDGRID_LIST_ID')],
                'recipients' => [$recipient->jsonSerialize()]
            ];
            
            try {
                $response = $sendgrid->client->marketing()->contacts()->put($requestBody);
                // 可选:记录日志,比如 info('SendGrid添加用户成功', ['code' => $response->statusCode()]);
            } catch (\Exception $e) {
                // 捕获异常,避免打断注册流程,可记录错误日志
                report($e);
            }
        }
    }
    
  3. 在app/Providers/EventServiceProvider.php中注册监听器:
    protected $listen = [
        \Illuminate\Auth\Events\Registered::class => [
            \App\Listeners\AddUserToSendGridList::class,
        ],
    ];
    

方法二:直接修改注册控制器

如果不需要解耦逻辑,可直接在app/Http/Controllers/Auth/RegisteredUserController.php的store方法末尾添加代码:

// ... 原有注册逻辑,用户保存完成后 ...

// 添加到SendGrid邮件列表
$sendgrid = new SendGrid(env('SENDGRID_API_KEY'));
$recipient = new \SendGrid\Contacts\Recipient();
$recipient->setEmail($user->email);

$requestBody = [
    'list_ids' => [env('SENDGRID_LIST_ID')],
    'recipients' => [$recipient->jsonSerialize()]
];

try {
    $sendgrid->client->marketing()->contacts()->put($requestBody);
} catch (\Exception $e) {
    report($e);
}

// ... 原有后续代码 ...

3. 关键提示

  • 这里调用的是SendGrid的Marketing Contacts API,该接口会自动忽略已存在于列表中的邮箱,无需额外判断重复
  • 建议将SendGrid相关逻辑封装为独立服务类(比如SendGridService),提升代码可维护性
  • 生产环境必须保留异常捕获,避免因SendGrid API故障导致注册流程中断

内容的提问来源于stack exchange,提问作者Md Nazmul Hossain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 20:25:22