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

Laravel 10自定义通知收件人,避免重要邮件发至自定义邮箱

解决方案

针对你遇到的问题,有两种可行的处理方式,既能让特定告警通知发送到自定义邮箱,又能保证密码重置等重要邮件发送到用户账号默认邮箱:

方案一:在User模型中根据通知类型动态选择收件邮箱

修改User模型的routeNotificationForMail方法,通过判断通知类的类型来返回对应的邮箱地址:

/**
 * Route notifications for the mail channel.
 *
 * @param  \Illuminate\Notifications\Notification  $notification
 * @return array|string
 */
public function routeNotificationForMail(Notification $notification)
{
    // 仅DomainExpiry类的通知使用自定义告警邮箱
    if ($notification instanceof \App\Notifications\DomainExpiry) {
        return $this->notification_email;
    }

    // 所有其他通知(如密码重置)使用用户账号默认邮箱
    return $this->email;
}

这种方式在模型层统一控制路由规则,适合有多个告警类通知需要使用自定义邮箱的场景。

方案二:在指定通知类的toMail方法中直接指定收件人

Laravel的MailMessage类提供了to()方法,可以直接在通知的邮件构建逻辑中指定收件人。这种方式无需全局修改模型的路由规则,仅针对单个通知生效:

  1. 先将User模型的routeNotificationForMail恢复为默认逻辑:
/**
 * Route notifications for the mail channel.
 *
 * @return array|string
 */
public function routeNotificationForMail(Notification $notification)
{
    return $this->email;
}
  1. 修改DomainExpiry通知类的toMail方法,添加->to()指定自定义邮箱:
public function toMail($notifiable)
{
    $domain = isset($this->emailData[0]['domain']) ? $this->emailData[0]['domain'] : '';
    $domain = htmlspecialchars($domain);

    $data = [
        'is_subscribed' => $notifiable->is_subscribed,
        'first_name' => $notifiable['first_name'],
        'domains' => json_encode($this->emailData),
    ];

    try {
        $this->createHistoryEntry('mail', 'Domain Expiry', $data, $notifiable);
    } catch (\Exception $e) {
    }

    return (new MailMessage)
                ->to($notifiable->notification_email) // 直接指定自定义收件邮箱
                ->subject(isset($domain) && ! empty($domain) ? "Domain Expiry Alert: $domain" : 'Domain Expiry Alert')
                ->markdown('emails.domains.expiry', $data);
}

这种方式更灵活,适合只有少数特定通知需要发送到自定义邮箱的场景。

补充说明

你提到的toRecipient方法并不存在,但MailMessage的to()方法完全可以满足需求——它支持传入单个邮箱字符串、多个邮箱数组,甚至包含email属性的对象。

内容的提问来源于stack exchange,提问作者Ryan H

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 20:45:17