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 :
Registration
Single Sender Creation
Dynamic Template Creation
Generate API Key
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,
Then click on `Start for free` button which takes you to sign up page.
From there you will be taken to a registration page.
Once If the registration process is over. You will be asked to fill few details,
Step 2 : Single Sender Creation
After that, You will be taken to the dashboard.
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.
After filling the form, A single sender will be created but will be in unverified state.
A verification mail will also sent to the registered mail id for the Single Sender verification.
By clicking on the `Verify Single Sender` button, The Single Sender created will be verified and is ready to send the mail.
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.
From there, you can start by clicking on the Blank Template like below,
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.
You will be provided with the code editor where you can write the code and preview will be displayed there itself.
Now you can either write the code directly in the code editor or copy and paste the template code that you have written locally.
Before saving, Provide the name and subject of the mail. If you want the subject to be dynamic
Once If you save the template, a template id
will be generated which will be used during the integration.
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.
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.
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.