Laravel 11 Send Email with Attachment Example

Laravel 11 Send Email with Attachment Example

Laravel 11 Send Email with Attachment Example

Laravel 11 Send Email with Attachment Example

Demo Video: Laravel 11 Send Email with Attachment Example

Laravel 11 Send Email with Attachment Example

Sending emails with Laravel 11 comprises a few basic steps. Primarily, set up your email configuration to prepare the content of the email and process other email attachments.

Here are steps to send email with attachments using SMTP and mailable class:

 Step 1: Install Laravel 11

If you have not created the Laravel app, then you may go ahead and execute the below command:

composer create-project laravel/laravel SendMailPdf

Step 2: Configure your mail settings

In the second step, you have to add the mail configuration. Set the mail driver as "gmail" or whatever you choose as driver, the mail host, mail port, mail username, and mail password. Laravel 11 will use these sender details for emails. You can simply add them as follows.

Open the .env File

Open the .env file in the root directory of your Laravel application, and configure mail server details in it; Something like this:

MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
MAIL_USERNAME=Add your email name here
MAIL_PASSWORD=Add your password here
MAIL_ENCRYPTION=tls
[email protected]
MAIL_FROM_NAME="${APP_NAME}"

Update config/mail.php

Ensure that config/mail.php is configured to use the settings from the .env file. Laravel should handle this automatically, but verify if needed.

Step 3 – Create a Controller File

Run the following command to make a controller file to handle the email sending process:

php artisan make:controller SendPdfController

Open a SendPdfController.php controller file from app/http/controller folder and update the following code into it:

<?php

namespace App\Http\Controllers;

use App\Mail\SendReportEmail;
use Illuminate\Support\Facades\Mail;

class SendPdfController extends Controller
{
    public function sendEmailPDF()
    {
        $title = 'PDF Mail from xdevspace.com';
        $body = 'Here is attachement file from xdevspace.com';

        Mail::to('[email protected]')->send(new SendReportEmail($title, $body));

        return "Email with pdf has been sent successfully!";
    }
}

Step 4 – Define Route

Define a route in the web.php file to handle the request to send mail; Something like this:

use App\Http\Controllers\SendPdfController;

Route::get('send-email-pdf', [SendPdfController::class, 'sendEmailPDF']);

 

Step 5: Create a Mailable Class

1- Generate Mailable Class:

– Use Artisan to create a new mailable class:

php artisan make:mail SendReportEmail
  • This command generates a class in app/Mail/SendReportEmail.php

 

2- Define the Mailable Class:

– Open app/Mail/SendReportEmail.php and configure it to handle attachments and email content:

namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class SendReportEmail extends Mailable
{
    use Queueable, SerializesModels;
    public $subject;
    public $content;
    /**
     * Create a new message instance.
     *
     * @param  string  $subject
     * @param  string  $content
     * @return void
     */
    public function __construct($subject, $content)
    {
        $this->subject = $subject;
        $this->content = $content;
    }
    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->view('emails.report')
                    ->subject($this->subject)
                    ->with([
                        'content' => $this->content,
                    ])
                    ->attach(public_path('/files/report.pdf'), [
                        'as' => 'report.pdf',
                        'mime' => 'application/pdf',
                    ]);
    }
}

3 - Explanation:

  • public_path('/files/report.pdf'): Path to the attachment.
  • 'as' => 'report.pdf': Name of the attachment file as it will appear to the recipient.
  • 'mime' => 'application/pdf': MIME type of the attachment.

Step 6: Create the Email View

Create Email View:

Create a Blade template for your email content at : resources/views/emails/report.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>{{ $subject }}</title>
</head>
<body>
    <h1>{{ $subject }}</h1>
    <p>{{ $content }}</p>
</body>
</html>

This template uses the variables passed from the SendReportEmail class.

Step 7: Send the Email

Sending Email from a Controller or a Job:      

You can send the email from anywhere in your application, be it from a controller or even from a job. You will now see an example of how you will send it from a controller.         

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Mail\SendReportEmail;
use Illuminate\Support\Facades\Mail;

class SendPdfController extends Controller
{
    public function sendEmail()
    {
        $subject = 'Monthly Report';
        $content = 'Please find the attached monthly report.';

        Mail::to('[email protected]')
            ->send(new SendReportEmail($subject, $content));

        return 'Email sent successfully!';
    }
}

Testing of Sending Email:

What you want to do now, in order to check if it does send the email with attachment, is actually visiting the route or endpoint that corresponds to the method named sendEmail.

Step 8: Handling Different File Types and Multiple Attachments

Add More Attachments:

– You can add more attachments by chaining ->attach() methods:

public function build()
{
    return $this->view('emails.report')
                ->subject($this->subject)
                ->with([
                    'content' => $this->content,
                ])
                ->attach(public_path('/files/report.pdf'), [
                    'as' => 'report.pdf',
                    'mime' => 'application/pdf',
                ])
                ->attach(public_path('/files/another-file.jpg'), [
                    'as' => 'another-file.jpg',
                    'mime' => 'image/jpeg',
                ]);
}

Handling Different MIME Types:

Ensure the MIME type corresponds to the type of file you are attaching (e.g., application/zip for ZIP files).

Step 9: Test Application

Run artisan serve command to start the application server for testing:

php artisan serve

Open browser with URL http://127.0.0.1:8000/send-email-pdf to send mail with pdf from laravel 11 application.

All Comments