How to add headers to email in Laravel 5.1

前端 未结 3 608
遇见更好的自我
遇见更好的自我 2021-02-13 00:21

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
         


        
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-13 00:51

    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');
    

提交回复
热议问题