How to add headers to email in Laravel 5.1

2019-04-04 04:34发布

Is there a way to add default headers to all emails in Laravel 5.1? I want all emails to be sent with the following header:

x-mailgun-native-send: true

2条回答
我欲成王,谁敢阻挡
2楼-- · 2019-04-04 04:55

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');
查看更多
贼婆χ
3楼-- · 2019-04-04 05:04

Slight modification to @maxim-lanin's answer. You can use it like this, fluently.

\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');
});
查看更多
登录 后发表回答