1

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 Answer 1

1
  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 }}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.