Send Email Using Sendgrid in PHP: Bulk, HTML, Attachments

How to Send Email Using Sendgrid in PHP Code Example

We must perform the following steps to send emails with Sendgrid in PHP.

  1. Sign up for a SendGrid account.
  2. Enable Two-factor authentication.
  3. Create and store a SendGrid API key.
  4. Complete Single Sender Verification.
  5. Create a project.
  6. Install Composer.
  7. Code implementation.

PHP Code Example to Send Emails in PHP with Sendgrid

<?php

require 'vendor/autoload.php';
 
use \SendGrid\Mail\Mail;
 
$email = new Mail();
// To Replace the email address and name with your verified sender
$email->setFrom(
    'youreamil@gmail.com',
    'Sender'
);
$email->setSubject('Sending with Twilio SendGrid is Fun');
// To Replace the email address and name with your recipient
$email->addTo(
    'youremail@gmail.com',
    'Receiver'
);
$email->addContent(
    'text/html',
    '<strong>and fast with the PHP helper library.</strong>'
);
$sendgrid = new \SendGrid(getenv('SENDGRID_API_KEY'));
try {
    $response = $sendgrid->send($email);
    printf("Response status: %d\n\n", $response->statusCode());
 
    $headers = array_filter($response->headers());
    echo "Response Headers\n\n";
    foreach ($headers as $header) {
        echo '- ' . $header . "\n";
    }
} catch (Exception $e) {
    echo 'Caught exception: '. $e->getMessage() ."\n";
}

Overview | How to Send Email in PHP?

FuelingPHP features “Send Email with PHP – mail, PHPMailer, SendGrid, Mailgun, etc.” which overviews options available to send Emails in PHP. We recommend you go through it first if you have not seen it yet. It will help you decide which Email service serves you the best.

If you’ve already made up your mind about SendGrid, carry on with this article, and by the end, you’ll have a good idea of using SendGrid in PHP.

Sign up for SendGrid Account

We can sign up for a free SendGrid account and will be able to send 100 emails a day.

Send an Email with Sendgrid in PHP
Create SendGrid Account

Note: You may need to provide additional information about the purpose of use and your company and usually someone from Twilio would send an Email requiring that information. So be mindful that it is not a one-step process and could take a while.

Enable The Two-factor authentication

The Twilio SendGrid requires customers to enable Two-factor authentication. So, we need to enable it to send an email using Sendgrid in PHP. We can enable 2FA via SMS or by using the Authy app. 

Create and Store a SendGrid API key

The API key is authorized to perform a limited scope of actions, unlike username and password that allow access to our full account. So, if our API key is compromised or lost, we can still cycle it or delete or create another one without changing the account credentials. 

To send an email using SendGrid, we need to create a restricted access API key with Mail Send > Full Access permissions only. This will allow us to send an email and schedule emails to be sent later. We can also edit the permissions assigned to the API key later on.

Send an Email with Sendgrid in PHP
Create API Key

After creating the SendGrid account, we must create the SendGrid email service API key.

Get an API key from here.

Send an Email with Sendgrid in PHP
Get API Key

Once we assign the API key to an environment variable, we can proceed to the next step.

Note: Do not hardcode your API Keys and other credentials. Use Environment files instead.

Verify Sender Identity

We need to verify the sender’s identity to ensure customers maintain the best possible sender reputation. A sender identity represents a ‘From’ email address( the address the recipients see as the sender of your emails).

SendGrid requires customers to verify their Sender Identities by completing Domain Authentication. We can verify one or more Sender Identities using either Domain Authentication or Single Sender Verification methods.

As we will be performing a test, so we can skip the Domain Authentication and begin by completing Single Sender Verification. The Single sender verification is recommended for testing only, and for the best experience, please complete Domain Authentication before single-sender verification. Domain Authentication also requires you to upgrade from a free account.

Single Sender Verification

Single Sender Verification is a fast way to verify our Sender Identity when we don’t have access to the DNS settings of our domain. We use Single Sender Verification because it is a great way to start quickly when performing a test.

Here are the steps to follow to verify a single sender identity.

Adding a Sender

Click on Sender Authentication in the navigation bar setting. Then proceed with Single Sender Verification by selecting Get Started under Verify an Address.

Send an Email with Sendgrid in PHP
Adding Sender

We will be redirected to the Single Sender Verification page and click on the Create New Sender to load a form modal.

Send Emails with Sendgrid in PHP
Create Sender
Fill form
Filling the Form

Fill in all the fields in the form and then on create button.

Form Fields

  • From Name – A user-friendly name is displayed to the recipient.
  • From Email Address – This will show to the user as the email address that sent this email. SendGrid will send the verification email to the address we enter in this field. 
  • Reply To – If the user sends a reply, then the reply will go to this address.
  • Company Address, City, State, Zip Code, Country – The business address.
  • Nickname – This is a label for our sender identity to help you identify it more quickly. This label is not visible to your recipients.

After filling in the fields form, check the email address you entered and click the link to verify the Sender’s address.

After clicking on the link, you will see a page confirming the verification of your address. Congratulations We are now ready to send an email with SendGrid.

Send Emails with Sendgrid in PHP
Sender Address Verified

Install Composer 

Use the following command to check if the composer is already installed.

composer --version

If the composer is already installed, the terminal will print the output like this:

Install Composer
Composer Already Installed

If the composer is not already installed, visit to download and install the composer website. 

Kicking Off

Create a directory for this project.

mkdir send_mail

Navigate to the folder using this command.

cd send_mail

Create a .env file in your root project directory.

$ touch .env //Linux Shell
> New-Item .\env -ItemType File //Powershell

Paste your SendGrid API key in the .env as follows.

SEND_GRID_API_KEY = "<YOUR-API-KEY>"

Install SendGrid in PHP

It is more efficient to use the SendGrid helper library for PHP to interact with the Mail Send API. To install the SendGrid helper library, run the following Composer command. 

composer require sendgrid/sendgrid

With the SendGrid package in hand, let’s utilize it in PHP to send Emails.

Send an Email with SendGrid in PHP

We are now ready to send email using SendGrid in PHP. Let’s build the basic example from scratch.

Import Mail class from SendGrid package.

require 'vendor/autoload.php';

use \SendGrid\Mail\Mail;

Initialize a new Mail object.

$email = new Mail();

Set the sender’s email and name using setFrom().

$email->setFrom(
    'youreamil@gmail.com',
    'Sender'
);

Provide the email’s subject using setSubject().

$email->setSubject('Sending with Twilio SendGrid is Fun');

Set the receiver’s email and name using addTo().

$email->addTo(
    'youremail@gmail.com',
    'Receiver'
);

Add content to the email’s body using addContent().

$email->addContent(
    'text/html',
    '<strong>and fast with the PHP helper library.</strong>'
);

We need to initialize a SendGrid object to communicate with the underlying API. The SendGrid constructor function expects the SendGrid API key.

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

Now let’s call send() on the SendGrid object. We either get back a response or an error. The program logs out to the console and uses a try/catch block to cater to success and error possibilities.

try {
    $response = $sendgrid->send($email);
    printf("Response status: %d\n\n", $response->statusCode());
} catch (Exception $e) {
    echo 'Caught exception: '. $e->getMessage() ."\n";
}

Send Email Using SendGrid in PHP Code Examples

Let’s assemble the code blocks and form a complete example.

<?php

require 'vendor/autoload.php';
 
use \SendGrid\Mail\Mail;
 
$email = new Mail();
// To Replace the email address and name with your verified sender
$email->setFrom(
    'youreamil@gmail.com',
    'Sender'
);
$email->setSubject('Sending with Twilio SendGrid is Fun');
// To Replace the email address and name with your recipient
$email->addTo(
    'youremail@gmail.com',
    'Receiver'
);
$email->addContent(
    'text/html',
    '<strong>and fast with the PHP helper library.</strong>'
);
$sendgrid = new \SendGrid(getenv('SENDGRID_API_KEY'));
try {
    $response = $sendgrid->send($email);
    printf("Response status: %d\n\n", $response->statusCode());
 
    $headers = array_filter($response->headers());
    echo "Response Headers\n\n";
    foreach ($headers as $header) {
        echo '- ' . $header . "\n";
    }
} catch (Exception $e) {
    echo 'Caught exception: '. $e->getMessage() ."\n";
}

Send Bulk Emails with SendGrid

We can send bulk emails to an email list in PHP using Twilio SendGrid. We will use the foreach() loop to parse through an array of email addresses and then build a single array of recipients.

SendGrid allows us to personalize each email a recipient receives, and we can modify the content based on the individual email address.

Complete Example | Sends Bulk Emails with SendGrid

<?php
 
require 'vendor/autoload.php';
 
use SendGrid\Mail\Personalization;
use SendGrid\Mail\To;
 
// Load our `.env` variables
$dotenv = Dotenv\Dotenv::create(__DIR__);
$dotenv->load();
 
// Declares a new SendGrid Mail object
$email = new \SendGrid\Mail\Mail();
 
// Defines the primary email
$email->setFrom("your@email.com", "Abid");
$email->setSubject("Group Email to Twilio Subscribers");
$email->addTo("receiver@gmail.com", "First Recipient");
 
// Defines the additional email addresses
$email_addresses = [
    'youreamil@gmail.com',
];
 
foreach ( $email_addresses as $email_address ) {
 
    $personalization = new Personalization();
    $personalization->addTo( new To( $email_address ) );
 
    $email->addPersonalization( $personalization );
}
 
 
$email->addContent("text/plain", "We are Sending bulk emails is easy with SendGrid");
$email->addContent("text/html", "We are Sending bulk emails is easy with SendGrid");
 
$sendgrid = new \SendGrid(getenv('SENDGRID_API_KEY'));
 
try {
    $response = $sendgrid->send($email);
    print $response->statusCode() . "\n";
    print_r($response->headers());
    print $response->body() . "\n";
    echo "email sent!\n";
} catch (Exception $e) {
    echo 'Caught exception: '. $e->getMessage() ."\n";
}

Send an Email Attachment using SendGrid in PHP

SendGrid provides a simple and efficient way to send attachments with email in PHP.  You need to read a file using PHP and then add the file resource to addAttachment().

The following code sends an email attachment of a PDF file using SendGrid in PHP.

<?php
require 'vendor/autoload.php';
 
$dotenv = Dotenv\Dotenv::create(__DIR__);
$dotenv->load();
 
$email = new \SendGrid\Mail\Mail();
$email->setFrom("youremail@gmail.com", "Test User");
$email->setSubject("Send Email Attachments with Twilio SendGrid");
$email->addTo("youremail@gmail.com", "Example User");
$email->addContent(
   "text/html",
   "How easy can this be?"
);
 
$file_encoded = base64_encode(file_get_contents('test.pdf'));
$email->addAttachment(
   $file_encoded,
   "application/pdf",
   "test.pdf",
   "attachment"
);
 
$sendgrid = new \SendGrid(getenv('SENDGRID_API_KEY'));
 
try {
   $response = $sendgrid->send($email);
   print 'The Email sent successfuly' . "\n";
   print 'Status Code: ' . $response->statusCode() . "\n";
} catch (Exception $e) {
   echo 'Caught exception: '.  $e->getMessage(). "\n";
}

Frequently Asked Questions

Why do we use SendGrid to Send Emails in PHP?

SendGrid is a reliable and transactional email delivery service that provides a cloud-based email delivery service. It can handle all the heavy lifting in sending and receiving emails. We highly recommend you send email using SendGrid in PHP.

SendGrid-PHP library helps us with a quick SMTP setting to send emails through SendGrid using PHP. It allows us to integrate flexible APIs into our app easily. 

How many Emails can SendGrid Send per Hour?

SendGrid V3 API has a rate limit of up to 10,000 requests per second. You may need to upgrade your plan to use the max rate.

Is SendGrid good for email marketing

Yes, SendGrid is good for email marketing because it allows us quickly and easily engage with our audience. We can send emails to multiple people using SendGrid. 

Send Email Using SendGrid in PHP Examples

This article demonstrates how to send email using SendGrid in PHP. This article helps you set up a SendGrid account, authenticate using 2F authorization, verify your senders and set up your API key. After these essentials, the article demonstrates how to send an Email using the SendGrid package in PHP.

The article also explores how to send bulk email using SendGrid in PHP. You can run Email marketing campaigns with SendGrid, which supports 10,000 requests per second. You can also send attachments in your emails as the last example does.

I hope you’ve enjoyed the article. Stay tuned for more at FuelingPHP

Get deeper with PHP

We have many fun articles related to PHP. You can explore these to learn more about PHP.


© 2022 Confident.Systems