Laravel send emails using sendgrid with example

Laravel send emails using sendgrid with example

In this article i am writing laravel send emails using sendgrid with an example. Emails play very important role for any business or communication. And we all know that sendgrid provides email feature to sen bulk emails, promotional emails etc.

So in this article we will learn to integrate sendgrid email in the laravel application.

For geting email smtp details, oyu will need to create an account on sendgrid website and will need to choose a plan which you suits for your requirement. After successfully creating a sendgrid account, you will have some SMTP details which will be needed in the intergration process.

So let’s start integrate sendgrid emails into our laravel application to send emails. Here i am assuming you have a working laravel application in which you want to integrate.

Step 1: Add Configuration

In the first step we will add smtp configurations into our application’s environment file. So open .env file placed on application’s root directory and add configurations as mentioned below –

MAIL_DRIVER=smtp

MAIL_HOST=smtp.sendgrid.net

MAIL_PORT=587

MAIL_USERNAME=your_sendgrid_username

MAIL_PASSWORD=your_sendgrid_password

Note: Don’t forget to replace your_sendgrid_username and your_sendgrid_password from your actual sendgrid account username and password.

Step2: Create route

For testing emails are going from laravel or not, we will create a route in application’s routes/web.php file. Open this file and copy following route .

Route::post('send-mail', 'HomeController@sendMail');

Step3: Added method to Controller

In this step we will create a method in the HomeController to handle the request and process of send email. So now add the following lines of code into HomeController.php

app/Http/Controllers/HomeController.php

public function sendMail()
{
    $user = User::find(1)->toArray();
    $mail = Mail::send('emails.email-template', $user, function($message) use ($user) {
        $message->to($user->email);
        $message->subject('Laravel send emails example');
    });
    if($mail){
      return 'Mail Send Successfully';
    }
    
}

Step4: Create Email Template

Now we will create an email template in the view. As written above we using emails.email-template in the controller. So let’s create this file and in this example we will write only a simple test message. You can write text message or html content into this file.

resources/views/emails/email-template.blade.php

Hello, This a sengrid test email from laravel application

After completing all the steps above you have successfully implemented laravel send emails feature for you laravel project through smtp details.