- To implement the Laravel mail send process, first, generate a Laravel mail file with the command:
php artisan make:mail UserCredentialsMail
This command will generate the Laravel mail file in the app/Mail directory.
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()));
- 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'),
];
}
- View file changes. Include in the view file:
{{ $messageBody }}