How to implement mail using Laravel mail service in Laravel 9 or 10?

189 views Asked by At

I want to implement Laravel mail service to send mail to user and attach file with that like dompdf package granted pdf.

I tried to implement a mail service to send mail in the controller and did it successfully but when I try to implement that in laravel genrated mail file I am not able to implement it properly

1

There are 1 answers

0
Dark knight On
  1. To implement the Laravel mail send process, first, generate a Laravel mail file with the command:
php artisan make:mail UserCredentialsMail
  1. This command will generate the Laravel mail file in the app/Mail directory.

  2. To send mail, include the mail send code in the file or block of code from where you trigger the mail:

// Include at the top
use App\Mail\UserCredentialsMail;
use Mail, PDF;

// Include in the function
$pdf = PDF::loadView('invoices.invoice_template', $data);
$details = [
    'FUll_NAME' => $user->name,
    'EMAIL' => $user->email,
    'PASSWORD' => $password,
];

// $user->email on which you want to send mail
Mail::to($user->email)->send(new SendCredentialsToUserMail($details, $pdf->output()));
  1. Now, make changes to the generated mail file:
// Include at the top
use Illuminate\Mail\Mailables\Attachment;
use Illuminate\Mail\Markdown;

public $user;
public $pdf;
public $messageBody;
public $subject;

public function __construct($user, $pdf)
{
    $this->user = $user;
    $this->pdf = $pdf;
}

public function content()
{
    $messageBody = '<!doctype html><html lang="en"><meta charset="UTF-8"><meta content="width=device-width,initial-scale=1" name="viewport"><title>User Credentials</title><p>Hello ' . $this->user->FUll_NAME . ',<p>Your credentials:<ul><li>Email:  ' . $this->user->EMAIL . ' <li>Password: ' . $this->user->PASSWORD . ' </ul>';

    $this->messageBody = $messageBody;
    $this->subject = $subject;

    return new Content(
        view: 'Mail.Template',
    );
}

public function attachments()
{
    return [
        Attachment::fromData(fn () => $this->pdf, 'fileName.pdf')
            ->withMime('application/pdf'),
    ];
}
  1. View file changes. Include in the view file:
{{ $messageBody }}