Skip to main content
How are we doing? Please help us improve Twilio. Take our short survey
789

SendGrid integration in Laravel

Created
Active
Viewed 1k times
5 min read
Part of Twilio Collective
1

enter image description here

Why SendGrid ?

SendGrid provides a cloud-based service that assists businesses with email delivery. The service manages various types of email including shipping notifications, friend requests, sign-up confirmations, and email newsletters.

To configure SendGrid in Laravel. We need to signup with SendGrid and perform few actions in SendGrid which we will see below,

Steps :

  1. Registration

  2. Single Sender Creation

  3. Dynamic Template Creation

  4. Generate API Key

  5. Laravel integration

Step 1 : Registration

Initially we need to signup and verify our SendGrid account. For that, Get into SendGrid's official website by clicking the link below,

https://sendgrid.com

Then click on `Start for free` button which takes you to sign up page.

enter image description here

From there you will be taken to a registration page.

enter image description here

Once If the registration process is over. You will be asked to fill few details,

enter image description here

Step 2 : Single Sender Creation

After that, You will be taken to the dashboard.

enter image description here

Where you need to create a single sender. A single sender is a name which will be displayed in the from part of the page.

enter image description here

After filling the form, A single sender will be created but will be in unverified state.

enter image description here

A verification mail will also sent to the registered mail id for the Single Sender verification.

enter image description here

By clicking on the `Verify Single Sender` button, The Single Sender created will be verified and is ready to send the mail.

enter image description here

Step 3 : Dynamic Template Creation

You can find Dynamic Template in the navbar of SendGrid dashboard. Click on the Add Version to create a new template.

enter image description here

From there, you can start by clicking on the Blank Template like below,

enter image description here

After that, You will be asked whether to proceed with Design Editor or Code Editor. You can choose anyone you are convinient with. But, In this article we will be proceeding only with the Code Editor since I already have a template ready with me.

enter image description here

You will be provided with the code editor where you can write the code and preview will be displayed there itself.

enter image description here

Now you can either write the code directly in the code editor or copy and paste the template code that you have written locally.

enter image description here

Before saving, Provide the name and subject of the mail. If you want the subject to be dynamic

enter image description here

Once If you save the template, a template id will be generated which will be used during the integration.

enter image description here

Step 4 : Generate API Key

For generating API key, We need to get into the Integration Guide which will be available on the navbar of SendGrid portal. Once after entering into Integration Guide. You will be asked whether to proceed with Web API or SMTP Relay. Choose Web API, So that we can use the generated key in API's.

enter image description here

After selecting the Web API, You can generate the API key by providing a name. Copy and paste the API key in some place so that you can use it during the integration.

enter image description here

Step 5 : Laravel integration

Create a Laravel project with the following command,

composer create-project laravel/laravel --prefer-dist sendgrid

After creating the project, Enter into the project folder and create a controller in which we will be writing the code for sending mail,

php artisan make:controller SendmailController

Open your .env file and declare few global variables,

[email protected]
SENDGRID_APIKEY=YOUR_API_KEY
SENDGRID_WILDLIFE_TEMP=YOUR_TEMPLATE_ID

To use the variables created in the .env file. You need to create a file inside config folder like config/sendgrid.php . Add the below code in the file created,

<?php
return [
  'SENDGRID_EMAIL' => env('SENDGRID_EMAIL'),
  'SENDGRID_APIKEY' => env('SENDGRID_APIKEY'),
  'SENDGRID_WILDLIFE_TEMP' => env('SENDGRID_WILDLIFE_TEMP'),
];
?>

Now inside your controller, write the following curl code in order to send mail,

public function sendmail() {
        $toemail = "[email protected]";
        $apiCode = config('sendgrid.SENDGRID_APIKEY');
        $sender = config('sendgrid.SENDGRID_EMAIL');
        $temp = config('sendgrid.SENDGRID_WILDLIFE_TEMP');
        $emailtitle = "WILDLIFE CONSERVATION";
        $description = "Ensure the world’s most iconic species, including tigers, rhinos, and elephants, are secured and recovering in the wild";

        $subject = "Wildlife Conservation";
        

            $dynamicContent = '{"personalizations": 
                [{"to": [{"email":"'.$toemail.'"}] ,  "dynamic_template_data": {
                  "emailtitle":"'.$emailtitle.'",
                  "description": "'.$description.'",
                  "subject": "'.$subject.'"
                },
                }],"from": {"email": "'.$sender.'"},
                "template_id": "'.$temp.'"}';
            
        $sendgridurl = 'https://api.sendgrid.com/v3/mail/send';
                
        $sendmail = curl_init();
        curl_setopt($sendmail, CURLOPT_POST, 1);
        curl_setopt($sendmail, CURLOPT_POSTFIELDS, $dynamicContent);
        curl_setopt($sendmail, CURLOPT_URL,  $sendgridurl);
        curl_setopt($sendmail, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($sendmail, CURLOPT_HTTPHEADER, array("Authorization: Bearer $apiCode", "Content-Type: application/json;charset=UTF-8"));
        curl_setopt($sendmail, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
        $createResult = curl_exec($sendmail);
        curl_close($sendmail);
        $result = json_decode($createResult);
        return response()->json(["result" => $result, "message"=>"Mail sent successfully"], 200);
}

After writing the curl function, We need to configure the function in api.php . So open routes/api.php and write the below code,

Route::post('sendmail', [SendmailController::class, 'sendmail']);

Now we can run the application and check whether it is working fine,

php artisan serve

Open your postman and type,

http://localhost:8000/api/sendmail

If you get the below output,

{
    "result": null,
    "message": "Mail sent successfully"
}

Then, You would have received the mail, else you will be getting an error message in the result.

Thank you for reading.