如何在Laravel 5.1中向电子邮件添加标题

时间:2015-09-01 18:47:05

标签: php laravel laravel-5

有没有办法在Laravel 5.1中为所有电子邮件添加默认标头?我希望使用以下标题发送所有电子邮件:

POST

4 个答案:

答案 0 :(得分:18)

Laravel uses SwiftMailer for mail sending.

When you use Mail facade to send an email, you call send() method and define a callback:

\Mail::send('emails.reminder', ['user' => $user], function ($m) use ($user) {
    $m->to($user->email, $user->name)->subject('Your Reminder!');
});

Callback receives $m variable that is an \Illuminate\Mail\Message object, that has getSwiftMessage() method that returns \Swift_Message object which you can use to set headers:

$swiftMessage = $m->getSwiftMessage();

$headers = $swiftMessage->getHeaders();
$headers->addTextHeader('x-mailgun-native-send', 'true');

答案 1 :(得分:3)

轻微修改@ maxim-lanin的答案。你可以像这样流利地使用它。

\Mail::send('email.view', ['user' => $user], function ($message) use ($user) {
    $message->to($user->email, $user->name)
        ->subject('your message')
        ->getSwiftMessage()
        ->getHeaders()
        ->addTextHeader('x-mailgun-native-send', 'true');
});

答案 2 :(得分:1)

我知道这是一篇过时的文章,但是我现在遇到了同样的问题,我认为这可能对其他人有用。

如果您使用的结构与Laravel(6.x和7.x)完全相同,则如下所示:

/**
 * Build the message.
 *
 * @return $this
 */
public function build()
{
    return $this->from('example@example.com')
                ->view('emails.orders.shipped');
}

您可以按以下格式在电子邮件中添加标题:

public function build()
{
   return $this->from('example@example.com')
                ->view('emails.orders.shipped')
                ->withSwiftMessage(function ($message) {
                    $message->getHeaders()
                        ->addTextHeader('Custom-Header', 'HeaderValue');
                });
}

我希望这会有用。

链接到当前文档:https://laravel.com/docs/7.x/mail#customizing-the-swiftmailer-message

答案 3 :(得分:0)

对于那些需要将此配置添加到所有电子邮件的人(如我),有一种使用侦听器的实用方法。

  1. 创建监听器:

php artisan make:listener MessageSendingListener

  1. 将以下内容添加到 MessageSendingListener
<?php

namespace App\Listeners;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Events\MessageSending;
use Illuminate\Queue\InteractsWithQueue;

class MessageSendingListener
{
    /**
     * Handle the event.
     *
     * @param  \Illuminate\Mail\Events\MessageSending $event
     * @return void
     */
    public function handle(MessageSending $event)
    {
        $event->message
            ->getHeaders()
            ->addTextHeader('x-mailgun-native-send', 'true');
    }
}
  1. 将配置添加到 EventServiceProvider 中应用程序的事件映射数组:
<?php

namespace App\Providers;

use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [

        // ...

        \Illuminate\Mail\Events\MessageSending::class => [
            \App\Listeners\MessageSendingListener::class,
        ],

    ];
}

观察:用 Laravel 7 测试。