Sendgrid Email Send Tutorial Laravel/PHP/cURL Example

  • 17-10-2022
  • 1800
  • Laravel 9
  • Haresh Chauhan

In this comprehensive example, we will learn how to send emails using SendGrid with different examples. SendGrid is one of the better email service providers using SMPT and API. Using SendGrid we just need to create an API key for the sending email.

Email sending using SendGrid is a little difficult and confusing for every developer, the SendGrid email setup is very simple but you must need to understand they to send in a different way using SendGrid API.

So How to send emails using SendGrid API in this post we will learn, also we will learn how to set up SendGrid email credentials in laravel, how to send emails using the composer package, and how to send emails to the user using cURL API post request.

So let's start understanding how the different ways we can send email using third-party SendGrid API in our application with different setups and examples.

Example 1. Using Install Package

In this example we will send emails using the composer package, therefor first we need to install a SendGrid mail send the package in our application. goto your "composer.json" file and add this provided line in your require section.

We will add a sendgrid/sendgrid": "~7" package name in composer.json file. After that, we will open the terminal and update the composer. If you are using laravel then you just press the composer update command in your application terminal.

{
    "require": {
        "sendgrid/sendgrid": "~7"
    }
}

This is a code sample, to use in your application where you wan to send an email and setup your all credentials with this code, and send an email.

$email = new \SendGrid\Mail\Mail();
$email->setFrom("test@example.com", "Example User");
$email->setSubject("Sending with Twilio SendGrid is Fun");
$email->addTo("test@example.com", "Example User");
$email->addContent("text/plain", "and easy to do anywhere, even with PHP");
$email->addContent(
    "text/html", "and easy to do anywhere, even with PHP"
);

$sendgrid = new \SendGrid(getenv('SENDGRID_API_KEY'));

try {

    $response = $sendgrid->send($email);
    print $response->statusCode() . "\n";
    print_r($response->headers());
    print $response->body() . "\n";
} catch (Exception $e) {

    echo 'Caught exception: '. $e->getMessage() ."\n";
}

Example 2. Using SMTP

Laravel mail sending using SMTP with SendGrid is very simple. you just need to create an API from the SendGrid account, copy your API key from there and paste it into your MAIL_PASSWORD. In laravel this your API key will work as a password. left all mail details will be statically put as per the below-given credentials.

MAIL_MAILER=smtp
# MAIL_DRIVER=smtp # for laravel < 7
MAIL_HOST=smtp.sendgrid.net
MAIL_PORT=587 // 465
MAIL_USERNAME=apikey  // YOUR USERNAME WILL BE "apiKey" (NOT KEY) FOR SENDGRID
MAIL_PASSWORD=sendgrid_api_key
MAIL_ENCRYPTION=tls // ssl
MAIL_FROM_NAME="John Smith"
MAIL_FROM_ADDRESS=from@example.com

Look at this sample example, setup credentials in your .env file. use your API key as a password, MAIL_USERNAME will be apiKey here you must note this thing. many developers make this mistake when they integrate SendGrid into their applications.

Email Send Using Queue In Laravel

MAIL_MAILER='smtp'
MAIL_HOST='smtp.sendgrid.net'
MAIL_PORT=587
MAIL_USERNAME='apikey'
MAIL_PASSWORD='SG.X8prXD-XQWasrHBG7l_leg.Yrh2eFjHtG.................'
MAIL_ENCRYPTION='tls'
MAIL_FROM_NAME="sender id verified name"
MAIL_FROM_ADDRESS="sender id verified mail"

For example use it in your application, just for test email send or verify the sending email. this is for testing purposes only. You can use the mail class in your application.

Route::get('/', function() {
    $data = array('name'=>"Webappfix");
    
    Mail::send(['text'=>'mail'], $data, function($message) {
        $message->to('example@gmail.com', 'Webappfix')->subject('Webappfix Laravel Basic Testing Mail');
        $message->from('example@gmail.com','example@example.example');
    });

    dd("Basic Email Sent. Check your inbox.");
});

Example 3. Using cURL

For all web apps, this is very simple to send email using a cURL request. using cURL will apply everywhere you don't need to do any extra setup. make a cURL request and send a post request with the encoded data.

<?php

$url = "https://api.sendgrid.com/v3/mail/send";

$headers = array(
        "Authorization: Bearer YOUR_API_KEY",
        'Content-Type: application/json'
);

$data = '{"personalizations": [{"to": [{"email": "recipient@example.com"}]}],"from": {"email": "sendeexampexample@example.com"},"subject": "Hello, World!","content": [{"type": "text/plain", "value": "Heya!"}]}';

$curl = curl_init($url);

curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

// HEADER SEND
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

// POST DATA SEND 
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

// FOR DEBUG ONLY!
{{-- curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); --}}

$resp = curl_exec($curl);

curl_close($curl);

// FURTHER PROCESSING ...
if ($resp == "OK") { ... } else { ... }

Laravel Email Send

Simple WhatsApp Messages Send Using Chat API In PHP


We always thanks to you for reading our blogs.


dharmesh-image

Dharmesh Chauhan

(Swapinfoway Founder)

Hello Sir, We are brothers origin from Gujarat India, Fullstack developers working together since 2016. We have lots of skills in web development in different technologies here I mention PHP, Laravel, Javascript, Vuejs, Ajax, API, Payment Gateway Integration, Database, HTML5, CSS3, and Server Administration. So you need our service Please Contact Us

haresh-image

Haresh Chauhan

(Co-Founder)


We Are Also Recommending You :