6

有人知道如何在通过Laravel 通知系统发送的电子邮件中添加标题吗?

我不是在谈论可以通过该方法设置标头的MailablewithSwiftMessage()

MailMessage一旦我有很多使用line,方法构建的电子邮件,我也想继续使用greetings

任何人有任何线索?

有我的代码以防有人需要查看任何东西!

<?php

namespace PumpMyLead\Notifications\Tenants\Auth;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;

class AccountActivation extends Notification
{
    use Queueable;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['mail'];
    }

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        return (new MailMessage)
            ->subject('My email subject')
            ->greeting('Just a greeting')
            ->line('Line 1')
            ->line('Line 2')
            ->action('CTA wanted', 'http://www.pumpmylead.com')
            ->line('Byebye');
    }
}

提前致谢!

4

4 回答 4

8

实际上,我找到了两种附加标题的方法。

当通过邮件通道发送通知时,Illuminate\Mail\Events\MessageSending会触发一个事件。

向它附加一个侦听器。在handle()你会得到Swift_Message对象。

或者在AppServiceProvider'sregister()方法中用您自己的方法覆盖MailChannel并在方法中附加标头send()

$this->app->bind(
    \Illuminate\Notifications\Channels\MailChannel::class,
    MyMailChannel::class
);
于 2017-04-27T09:20:22.200 回答
2

在 ./app/Notifications/myNotification.php 中,将此代码添加到您的 __construct() 函数中:

$this->callbacks[]=( function($message){
    $message->getHeaders()->addTextHeader('x-mailgun-native-send', 'true');
});

将“x-mailgun-native-send”替换为您希望添加的任何标头,并将“true”替换为所需的值。

https://github.com/laravel/ideas/issues/475

于 2018-09-19T19:42:59.700 回答
0

Debbie V 有一个非常接近的答案,但并不完全正确。她引用的问题很清楚,但她错过了解决方案提供的必要背景。

默认情况下,Laravel 中的 Notification 使用MailMessage,但是你也可以让它返回 a Mailable。仅当您:a)创建自定义可邮寄,并且 b)使用它而不是MailMessage将应用回调。

更完整的解决方案是:

  1. 创建自定义可邮寄类php artisan make:mail MyMailable
  2. 更新您的public function toMail($notifiable)方法以使用新的Mailable.
  3. 将回调添加到MyMailable类的构造函数中。

在那之后你应该一切都好。最困难的部分只是调整MailMessage您使用的电流以适应Mailable.

于 2019-05-03T15:55:09.493 回答
0

如果上述方法不起作用,这是一个现代的 2022 替代方案,在 Laravel 8 中进行了测试。

使用withSwiftMessage()

public function toMail($notifiable)
{
    return (new MailMessage)
        ->subject($subject)
        ->greeting($greeting)
        ->line($line1)
        ->line($line2)
        ->withSwiftMessage(function($message) use ($value1, $value2) {
            $message->getHeaders()->addTextHeader('X-MJ-CustomID', json_encode([
                'key1' => $value1,
                'key2' => $value2,
            ]));
        })
}
于 2022-02-16T00:33:18.580 回答