19

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
1
  • where did you learn about x-mailgun-native-send? i can't seems to find any documentation on mailgun website. ta
    – gondo
    Commented May 12, 2016 at 10:35

4 Answers 4

24

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
  • hi, i am having the same issue with some email domains not acceptable, @comcast.net mail domains keep failing as well as others.. i am using mailgun with my laravel setup. I am still having this issue even with the code so, hopefully you can answer some of my questions. do you include the $headers in the Mail::send function() ? is there anything else needed? ports open? or anything i can check to make sure to get it working. any help would be great. Thankx
    – rbz
    Commented Oct 23, 2015 at 17:48
  • I can't get this to work. I keep getting syntax error, unexpected '$swiftMessage' (T_VARIABLE). Thoughts? Commented Dec 4, 2015 at 23:09
  • @timpeterson that's most likely a parsing error, which means you have a syntax error in your code.
    – Bogdan
    Commented Dec 5, 2015 at 1:13
9

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('[email protected]')
                ->view('emails.orders.shipped');
}

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

public function build()
{
   return $this->from('[email protected]')
                ->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

8

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');
});
2
3

For those who need to add this configuration to all emails (like me), there is a practical way using listeners.

  1. Create a Listener:

php artisan make:listener MessageSendingListener

  1. Add the following content to the 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. Add the configuration to the application's event mapping array in 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,
        ],

    ];
}

Obs.: Tested with Laravel 7.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.