Framework: Cannot set recipient name in notification mail

Created on 21 Mar 2017  路  5Comments  路  Source: laravel/framework

According to the L5.3 documentation here, it is only possible to set the recipient email address of a notification mail, and not the recipient name.
In the L5.4 documentation here, the to() method has even disappeared completely.

You would expect to be able to set the name of the recipient in the mail header, similar as with the old Mail::to($address, $name).

Most helpful comment

You can also do this:

Mail::to([['name' => $model->to->name, 'email'=> $model->to->email]])->send(
                (new MyMailable($content))
            );

This was a PITA to find out. Mail::to expects an array of to recipients and furthermore it expects the key (or object property) 'email' instead of 'address'.

All 5 comments

If you use mailables for your notification emails, you can specify the name using the "to" method of the mailable:

    public function toMail($notifiable)
    {
        return (new Mailable())->to($this->user->email, 'John Doe');
    }

email_with_name

I guess it's just a workaround, but thought it may help.

You can also do this:

Mail::to([['name' => $model->to->name, 'email'=> $model->to->email]])->send(
                (new MyMailable($content))
            );

This was a PITA to find out. Mail::to expects an array of to recipients and furthermore it expects the key (or object property) 'email' instead of 'address'.

Thank you @tpraxl. It helps a lot.

Another option is to set the receiver in the Mailable, I find that syntax a bit less confusing:

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        $sender = ...
        $receiver = ...

        return $this
            ->from($sender->email, $sender->name)
            ->to($receiver->email, $receiver->name)
            ...
            ;
    }
}

and then just do Mail::send(new MyMailable(...))

Just want to point out, after wasting 1 hour on this, and in Laravel 6 at least, the method routeNotificationForMail on the model which is used to customise the recipient can, in fact, be an array (not only a string as seen in the documentation)

Therefore, you can specify the field responsible for the recipient email as key and field responsible for the recipient name as value like so

    /**
     * Route notifications for the mail channel.
     *
     * @param Notification $notification
     * @return array
     */
    public function routeNotificationForMail($notification) : array {
        return [
            $this->the_email => $this->the_name
        ];
    }

where the_email and the_name are fields on the model (and in a table)

image

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Anahkiasen picture Anahkiasen  路  3Comments

JamborJan picture JamborJan  路  3Comments

kerbylav picture kerbylav  路  3Comments

iivanov2 picture iivanov2  路  3Comments

Fuzzyma picture Fuzzyma  路  3Comments