Search code examples
phplaravellumenmailer

BindingResolutionException when sending mails in Lumen Jobs


I have no problem sending synchronous mails, but the ones that get executed on a queue using Mail::queue throw the next error:

Illuminate\Contracts\Container\BindingResolutionException: Target [Swift_Transport] is not instantiable while building [Illuminate\Mail\Mailer, Swift_Mailer]. in /var/www/myapp.dev/vendor/illuminate/container/Container.php:804

Everything is configured correctly as emails are being sent when I do it synchronously


Solution

  • After having so much trouble with sending emails inside of Lumen Jobs, I encapsulated the email sending in a Job which works with mailables like this:

    MailDispatcher.php

    <?php
    
    namespace App\Jobs;
    
    use Illuminate\Contracts\Mail\Mailable;
    use Illuminate\Support\Facades\Mail;
    
    class MailDispatcher extends Job {
    
        public $mail;
    
        public function __construct(Mailable $mail) {
            $this->mail = $mail;
        }
    
        public function handle() {
            Mail::send($this->mail);
        }
    }
    

    Then when I want to queue a mail...

    $mail = new MyMailableMail($user);
    dispatch(new MailDispatcher($mail));
    

    And it works correctly