If you create a mailable class in Laravel, then you either create the content in the constructor, in the the blade or in both. If you want to send your mail in language X in queue then its relevant where the content is created at.

1. Content is in blade file

Assume you have your content of the mail in a blade file:


@component('mail::message')
@lang('welcome.message')

Then you can either use it on Mail facade


\Mail::to($user)->locale($locale)->queue($activeMail);

or on the Mailable object


 $test = new \App\Mail\ActiveMail();
 $test->locale('de')->send();

But if you use the Mailable, you have to use send from that object. This will not work:


\Mail::to($user)->queue($activeMail->locale($locale));

2. Content is setup in constructor

Lets assume the following is your constructor:


public function __construct($user)
{
      parent::__construct($user);
      $this->subject = __('list.emailWelcomeSubject', [':user' => $user->getName()]);
      $this->subject = __('list.emailWelcomeMessage');
}

In this case, the locale method of Mail facade or the Mailable object won’t work!
The language has to be set when the Mailable object calls the constructor. Something like this:


public function __construct($user)
{
      $tmp = \App::getLocale();
      \App::setLocale($user->getLang());
      parent::__construct($user);
      $this->subject = __('list.emailWelcomeSubject', [':user' => $user->getName()]);
      $this->subject = __('list.emailWelcomeMessage');
      \App::setLocale($tmp);
}

The solution for 1 & 2

However this might be a bit cumbersome if you need to do this for every mail. I ended up creating a static function that does this sort of things for me whenever I send a mail (which covers both 1 & 2 case):


  public static function to(Sendable $user, String $class, Array $params, $options = [])
  {
    $email    = $options['email']     ?? null;
    $lang     = $options['lang']      ?? null;
    $queue    = $options['queue']     ?? true;
    $restrict = $options['restrict']  ?? null;

    if(empty($email)) $email = $user->getEmail();

    $locale = (empty($lang)) ? $user->getLang() : $lang;

    if(!empty($restrict)){
      $locale = (in_array($locale, $restrict)) ? $locale : 'en';
    }

    $temp = \App::getLocale();
    \App::setLocale($locale);

    $reflection_class = new \ReflectionClass($class);
    $mailclass = $reflection_class->newInstanceArgs($params);

    // https://stackoverflow.com/a/50762190/2311074
    $receiver = new \stdClass();
    $receiver->email = $email;
    $receiver->name  = $user->getName();

    if($queue){
      \Mail::to($receiver)->locale($locale)->queue($mailclass);
    }
    else{
      \Mail::to($receiver)->locale($locale)->send($mailclass);
    }


    \App::setLocale($temp);
  }
adam