13
votes

I have a contact form where someone provides his name and email. I want to send him an email now with Laravel.

I found in the docs

To send a message, use the to method on the Mail facade. The to method accepts an email address, a user instance, or a collection of users.

and in fact

\Mail::to('[email protected]')->send(new \App\Mail\Hello);

works. But is it also possible to provide the name for the email receipt?

I wanted to look that up in the Laravel API for the Mail Facade but to my surprise the facade has no to function?

So how can I find out what the to function really does and if I can pass a name parameter as well?

6
are you looking for this public function to($address, $name = null, $override = false)Bugfixer
The Mail facade gets a Mailer instance: you can find the docs here. laravel.com/api/5.5/Illuminate/Mail/Mailer.htmlEmile Pels
@Bugfixer YES! Thanks! Where can I find this line in the code? I could not find this function in the Mailer class?Adam
vendor/laravel/framework/src/Illuminate/Mail/Message.phpBugfixer
use third param $callback of public function send() to give name with recipient email.Bugfixer

6 Answers

26
votes

In laravel 5.6, answer to your question is: use associative array for every recpient with 'email' and 'name' keys, should work with $to, $cc, $bcc

$to = [
    [
        'email' => $email, 
        'name' => $name,
    ]
];
\Mail::to($to)->send(new \App\Mail\Hello);
5
votes

You can use the Mail::send() function that inject a Message class in the callable. The Message class has a function to($email, $name) with the signature you're searching, i.e.:

Mail::send($view, $data, function($message) use ($email, $name) {
    $m->to($email,  $name);
    $m->from('[email protected]', 'Your Name'); 
    $m->subject('Hi there');
})

The $view could be a string (an actual view) or an array like these:

['text'=> 'body here']
['html'=> 'body here']
['raw'=> 'body here']

The $data argument will be passed to the $view.

2
votes

You can use Mailable class in Laravel: https://laravel.com/docs/5.5/mail

php artisan make:mail YouMail

These classes are stored in the app/Mail directory.

In config/mail.php you can configue email settings:

'from' => ['address' => '[email protected]', 'name' => 'App Name'],
2
votes

I prefer this solution as more readable (no need to use arrays and static string keys).

\Mail::send((new \App\Mail\Hello)
    ->to('[email protected]', 'John Doe');
1
votes

For Laravel < 5.6 one can use this:

$object = new \stdClass();
$object->email = $email;
$object->name  = $user->getName();

\Mail::to($object)->queue($mailclass);

see here

0
votes

for Laravel 8 is like this:

$user = new User;
$user->email = '[email protected]';
Mail::to($user)->send(new YourMail);

YourMail is Mailable class created by php artisan make:mail YourMail