I want to send a mail via laravel. For some reason, I only want to set the cc before calling the send method:
Mail::cc($cc_mail)->send(new MyMailAlert());
Then I define the recipient (to) directly in the build method of my Mailable class:
$this->subject($subject)->to($to_email)->view('my-mail');
But it fails:
Symfony\Component\Debug\Exception\FatalThrowableError: Call to undefined method Illuminate\Mail\Mailer::cc()
How can I send a mail without knowing the recipient before sending it in the build method? In other word I want to set the recipient (to) directly in the build method and I don't know how to do this.
Here is a hack to deal with this problem:
Mail::to([])->cc($cc_mail)->send(new MyMailAlert());
So just add a to() method with an empty array and it works. It's still a hack, I'm not really sure it will work in the future.
cc is documented in Laravel Docs, but I can't find the method or property in the Illuminate\Mail\Mailer source code, neither in the Laravel API Documentation. So you can't use it this way.
But Illuminate\Mail\Mailable has the cc property. So, if you want to add the cc before sending and add the to on the build method, you need something like this:
MyMailAlert.php
class MyMailAlert extends Mailable implements ShouldQueue
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*/
public function __construct()
{
//
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this->subject($this->subject)->to($this->to)->view('my-mail');
}
}
In your controller:
$myMailAlert = new MyMailAlert();
$myMailAlert->cc = $cc_mail;
// At this point you have cc already setted.
Mail::send($myMailAlert); // Here you sends the mail
Note that the build method uses subject and to properties of the mailable instance, so you have to set it before sending.
I'm not sure from where are you retrieving your $subject and $to_email in your build method example, but for my example you have to give these values to $myMailAlert->subject and $myMailAlert->to. You can use your custom variables in the build method, but given that the class already has these properties, custom variables aren't needed.