Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we use MailMessage API in Mailable class?

In notification email, we can use some API to write the mail rapidly using methods like greeting(), line() etc..

https://laravel.com/docs/5.4/notifications#mail-notifications

Can we use the same API in Mailable class?

Thanks

like image 425
Parth Vora Avatar asked Feb 18 '26 18:02

Parth Vora


1 Answers

No. The Mailable class does not implement the same methods as the MailMessage class.

You can use the MailMessage class outside of notifications, if you need to, but you'll have to send the mail object yourself.

$message = (new \Illuminate\Notifications\Messages\MailMessage())
    ->to(/* */)
    ->subject(/* */)
    ->line(/* */)
    ->action(/* */)
    ->line(/* */);

// most of this code is copied from \Illuminate\Notifications\Channels\MailChannel
Mail::send($message->view, $message->data(), function ($m) use ($message) {
    if (!empty($message->from)) {
        $m->from($message->from[0], isset($message->from[1]) ? $message->from[1] : null);
    }

    $m->to($message->to);

    if ($message->cc) {
        $m->cc($message->cc);
    }

    if (!empty($message->replyTo)) {
        $m->replyTo($message->replyTo[0], isset($message->replyTo[1]) ? $message->replyTo[1] : null);
    }

    $m->subject($message->subject ?: 'Default Subject');

    foreach ($message->attachments as $attachment) {
        $m->attach($attachment['file'], $attachment['options']);
    }

    foreach ($message->rawAttachments as $attachment) {
        $m->attachData($attachment['data'], $attachment['name'], $attachment['options']);
    }

    if (!is_null($message->priority)) {
        $m->setPriority($message->priority);
    }
});

NB: this is untested, but I think it should work.

like image 103
patricus Avatar answered Feb 21 '26 13:02

patricus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!