How to Send Mail using Sendgrid in Laravel?

November 22, 2022
Laravel
How to Send Mail using Sendgrid in Laravel?

Do you want to send mail using Sendgrid in Laravel? If sounds like you are looking for the answer for that query, then you stumbled upon on the right article.

This article is a complete step-by-step guide on How to Send Mail using Sendgrid in Laravel.

You can easily follow these steps to send mail by using sendgrid in any laravel version such as laravel 9, laravel 8, laravel 7 or laravel 6 as well.

Let’s get started!

Step 1: Install Laravel

The first step is to install the laravel itself. Open up your terminal and write following command:

composer create-project --prefer-dist laravel/laravel examples/sendgrid_send_email

I am installing laravel in examples/sendgrid_send_email folder, you can name it whatever you want 🙂

Step 2: Create Mail Class

Now the second step is to create a mail class that will contain the logic of sending the email.

Type the following command:

php artisan make:mail SendWelcomeEmail

I am naming my mail class name SendWelcomeEmail, you can name it whatever you want.

You will see the following file in Mail/SendWelcomeEmail.php

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;


use Illuminate\Queue\SerializesModels;

class SendWelcomeEmail extends Mailable
{
    use Queueable, SerializesModels;

    public $details;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($details)
    {
        $this->details = $details;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
     
    }
}

Step 3: Modifying the Build function of Mail Class

Now in this step, we will modify the build function of SendWelcomeEmail mail class which we created in the previous step.

Add the following code in build function:

 public function build()
    {
        return $this->subject('This is Test Email via SendGrid')
            ->view('emails.sendgridWelcomeEmail');
    }

In the build function, we are passing the subject to be “This is Test Email via SendGrid” and binding with view sendgridWelcomeEmail which will be in the resources/views/emails folder. This means send the email with this subject and this view.

Step 4: Creating View for Email

In the previous step, we bind the sendgridWelcomeEmail view to the build function.

So you have to go to resources/views and create folder emails and then create file called sendgridWelcomeEmail.blade.php.

In that sendgridWelcomeEmail.blade.php add follwing html code:

<!DOCTYPE html>
<html>
<head>
    <title>ImpulsiveCode.com</title>
</head>
<body>
    <p>{{ $info['body'] }}</p>

</body>
</html>

This content will be the in the body of the email itself. You can see that we have a variable called $info from which are passing the body value.

In the next step, will explain where this $info variable comes from.

Step 5: Create Controller and Call Mail Class

Now in this step, we need to create a controller to call that SendWelcomeEmail Class.

Type the following command to create a controller:

 php artisan make:controller SendController

Now in the Controller which we created Http/Controllers/SendController.php , we need to create the index function to call the mail class SendWelcomeEmail

 public function index(){

        $info= [
            'body' => 'This is email testing using sendgrid'
        ];
        Mail::to('your_receiver_email@gmail.com')->send(new SendWelcomeEmail($info));

    }

So we are calling Mail in which are passing email to the to email and sending SendWelcomeEmail mail class which will eventually send the view and the subject added in the SendWelcomeEmail mail class.

Note the $info array we added here , that array we are passing to SendWelcomeEmail and that will be able to access the body variable in the view of sendgridWelcomeEmail.blade.php.

Step 6: Link the Controller with route

Now in this step, we need to link the controller SendController@index with the route send-mail.

Route::get('/send-mail', [\App\Http\Controllers\SendController::class,'index']);

Step 7: Create an account on Sendgrid

a) Now you need to create an account on sendgrid.com in order to get the SMTP details. In first step enter email and password.

b) In second step, add your personal information

c) After that you might need to enable 2FA for getting SMTP details.

d) After that you will see a dashboard like this:

Click On Start Button of Integrate using our Web API or SMTP Relay.

e) You will see first step of Integrate using our Web API or SMTP Relay.

Now Click on Choose of SMTP Relay.

f) Now you will see the Screen Where you will need to enter API Key Name to get the details

After Entering Key Name, Press Create Key Button.

g) Now you will see all the details of SMTP details that we need.

Step 8: Copy SMTP details and update ENV

Now the SMTP details that you got from the last step you need to update .ENV based on that

Update MAIL_MAILER, MAIL_HOST, MAIL_PORT, MAIL_USERNAME, MAIL_PASSWORD from the SendGrid Account.

Step 9: Run Application and Call Route we Created Before

Now its finally time to run the application, run the following command in the terminal:

php artisan serve

Now if you type http://127.0.0.1:8000/send-mail in the browser. You should be able to receive email at your email address.

Hurray! You were successfully able to integrate SendGrid Sending Email into your laravel project.

Possible SSL error on Localhost while sending email

By any chance, if you are trying to send email from your local machine, chances are due to not having SSL certficate, you might get following error of Unable to connect with STARTTLS:

In order to fix this, you need to install the SSL certificate on your machine or in config/mail.php in the SMTP array you need to add the 'auth_mode' => null, and 'verify_peer' => false, .

After that step, you will be able to send an email locally. Note these changes auth_mode and verify_peer are not recommended on live server and domain.

On live server domains, mostly have SSL certificates installed so no need to do these changes on live server.

Conclusion

In the above article, we have step by step taught you how to send mail using SendGrid in Laravel.

Let me know if need any help. Cheers!

Write a Reply or Comment

Your email address will not be published. Required fields are marked *


Icon