Search code examples
laravellaravel-5smtpswiftmaileremail-headers

SMTP: Change Message-ID domain in sending emails from Laravel 5.7 (Swift Mailer)


Laravel 5.7 sends emails using Swift Mailer.

By default, all sent emails will have the Message-ID header with the domain swift.generated (eg. Message-ID: <90b9835f38bb441bea134d3ac815dd6f@swift.generated>).

I would like to change the domain swift.generated to for example my-domain.com.

How can I change this for all emails?


Solution

    1. Edit the file config/mail.php and define your domain near the end:
        'domain' => 'yourdomain.com',
    
    1. In the command line, create a new listener:
        php artisan make:listener -e 'Illuminate\Mail\Events\MessageSending' MessageSendingListener
    
    1. Edit the newly created listener and make it look as follows (do NOT implement ShouldQueue):
        <?php
        /**
         * Set the domain part in the message-id generated by Swift Mailer
         */
    
        namespace App\Listeners;
    
        use Illuminate\Mail\Events\MessageSending;
        use Swift_Mime_IdGenerator;
    
        class MessageSendingListener
        {
            /**
             * Create the event listener.
             *
             * @return void
             */
            public function __construct()
            {
                //
            }
    
            /**
             * Handle the event.
             *
             * @param  MessageSending  $event
             * @return void
             */
            public function handle(MessageSending $event)
            {
                $event->message->setId((new Swift_Mime_IdGenerator(config('mail.domain')))->generateId());
            }
        }
    
    1. Register the listener in app/Providers/EventServiceProvider:
            protected $listen = [
    
               // [...]
    
                \Illuminate\Mail\Events\MessageSending::class => [
                     \App\Listeners\MessageSendingListener::class,
                ],
             ];
    

    That's it, enjoy! :)