3

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?

checker284
  • 1,286
  • 3
  • 14
  • 29

2 Answers2

6
  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! :)

SBurina
  • 76
  • 1
  • 2
  • Awesome! Works perfect, thank you! This should be already included in Laravel like this. Maybe in Laravel 6.0. :) – checker284 Aug 31 '19 at 23:09
  • It is included in laravel 7.0 for sure, just need to do the first step, the rest is already done – Tofandel Jul 07 '20 at 16:25
2

Just found a correct way to change @swift.generated in message ID.

Add this code to your AppServiceProvider->boot() method:

\Swift_DependencyContainer::getInstance()
        ->register('mime.idgenerator.idright')
        ->asValue(config('mail.domain'));

config('mail.domain') is a custom config entry so you can change it to whatever you want.

Tested in Laravel 6, maybe will work with 5.* versions too.

Also you can find many interesting configs in this file: vendor/swiftmailer/swiftmailer/lib/dependency_maps/mime_deps.php

Swayok
  • 436
  • 3
  • 12