How to add headers to email in Laravel 5.1

前端 未结 3 553
离开以前
离开以前 2021-02-13 00:41

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 01:00

    I know this is an old post, but I'm passing by the same problem right now and I think this could be useful to others.

    If you're using a structure exactly as shown in Laravel (6.x and 7.x), like this:

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

    you could add headers to the E-mail in the format below:

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

    I hope this could be useful.

    link to the current documentation:https://laravel.com/docs/7.x/mail#customizing-the-swiftmailer-message

    0 讨论(0)
  • 2021-02-13 01:02

    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');
    
    0 讨论(0)
  • 2021-02-13 01:11

    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');
    });
    
    0 讨论(0)
提交回复
热议问题