Laravel use MailMessage in Mailable
Publish notifications from vendor and you can send it in markdown
public function __construct($user)
{
$this->user = $user;
$this->message = (new MailMessage)
->greeting('Bonjour '.$user->name)
->line('Nous vous remercions de votre inscription.')
->line('Pour rappel voici vos informations :')
->line('Mail: '.$user->email)
->line('Password: '.$user->password);
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this->markdown('vendor.notifications.email', $this->message->data());
}
I used this in Laravel 8, not sure if it is still compatible with previous versions of Laravel.
The point is to use the html
method in the Mailable
.
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Queue\SerializesModels;
class MyMail extends Mailable
{
use Queueable, SerializesModels;
public function build()
{
return $this->subject('My Subject')
->html((new MailMessage)
->line('The introduction to the notification.')
->action('Notification Action', url('/'))
->line('Thank you for using our application!')
->render()
);
}
}
You are mixing 2 separate Laravel concepts, Notifications and Mailers. Notifications can be Mailers, but Mailers can not be Notifications.
The MailMessage
class is a notification message, but cannot be the message for a Mailable
. To send a MailMessage
mailer you should extend the Notification
class:
<?php
namespace App\Notifications;
use Illuminate\Notifications\Notification;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Bus\Queueable;
class WelcomeNotification extends Notification implements ShouldQueue
{
use Queueable, SerializesModels;
public $user;
public function __construct($user)
{
// The $notifiable is already a User instance so not really necessary to pass it here
$this->user = $user;
}
public function via($notifiable)
{
return ['mail'];
}
public function toMail($notifiable)
{
return (new MailMessage)
->greeting('Bonjour '.$this->user->name)
->line('Nous vous remercions de votre inscription.')
->line('Pour rappel voici vos informations :')
->line('Mail: '.$this->user->email)
->line('Password: '.$this->user->password);
}
}
Also, see Laravel's ResetPassword
notification as example.
To send the notification to a user:
$user->notify(new WelcomeNotification($user));
In this manner you can create generic mail messages using the default mail notification template.