Skip to contentSkip to navigationSkip to topbar
Rate this page:
On this page

Email API Quickstart for PHP


In this quickstart, you'll learn how to send your first email using PHP(link takes you to an external page) and the Twilio SendGrid Mail Send API.


Prerequisites

prerequisites page anchor

Be sure to perform the following prerequisites to complete this tutorial. You can skip ahead if you've already completed these tasks.

  1. Sign up for a SendGrid account.
  2. Enable Two-factor authentication.
  3. Create and store a SendGrid API key.
  4. Complete Domain Authentication.
  5. Install PHP.
  6. Install Composer.

Skip the prerequisites

Sign up for a SendGrid account

sign-up-for-a-sendgrid-account page anchor

When you sign up for a free SendGrid account(link takes you to an external page), you'll be able to send 100 emails per day forever. For more account options, see our pricing page(link takes you to an external page).

Enable Two-factor authentication

enable-two-factor-authentication page anchor

Twilio SendGrid requires customers to enable Two-factor authentication (2FA). You can enable 2FA with SMS or by using the Authy(link takes you to an external page) app. See the 2FA section of our authentication documentation for instructions.

Create and store a SendGrid API key

create-and-store-a-sendgrid-api-key page anchor

Unlike a username and password — credentials that allow access to your full account — an API key is authorized to perform a limited scope of actions. If your API key is compromised, you can also cycle it (delete and create another) without changing your other account credentials.

Visit our API Key documentation for instructions on creating an API key and storing an API key in an environment variable. To complete this tutorial, you can create a Restricted Access API key with Mail Send > Full Access permissions only, which will allow you to send email and schedule emails to be sent later. You can edit the permissions assigned to an API key later to work with additional services.

Once your API key is assigned to an environment variable — this quickstart uses SENDGRID_API_KEY — you can proceed to the next step.


_10
export SENDGRID_API_KEY=<Your API Key>

Verify your Sender Identity

verify-your-sender-identity page anchor

To ensure our customers maintain the best possible sender reputations and to uphold legitimate sending behavior, we require customers to verify their Sender Identities by completing Domain Authentication. A Sender Identity represents your 'From' email address—the address your recipients see as the sender of your emails.

(information)

Info

To get started quickly, you may be able to skip Domain Authentication and begin by completing Single Sender Verification. Single Sender Verification is recommended for testing only. Some email providers have DMARC policies that restrict email from being delivered using their domains. For the best experience, please complete Domain Authentication. Domain Authentication is also required to upgrade from a free account.

Before installing PHP, you can see if you already have a version on your machine.

(information)

Info

The Twilio SendGrid PHP helper library requires PHP version 5.6, 7.0, 7.1, 7.2, 7.3, or 7.4. However, we strongly encourage you to use the latest, stable version, 7.4.

PHP version check

php-version-check page anchor

Check if you already have a version installed on your machine by opening your terminal (also known as a command line or console) and typing the following command.


_10
php -v

If you have PHP installed, the terminal will print something like the following output.


_10
PHP 8.0.3 (cli) (built: Mar 4 2021 20:42:56) ( NTS )
_10
Copyright (c) The PHP Group
_10
Zend Engine v4.0.3, Copyright (c) Zend Technologies
_10
with Zend OPcache v8.0.3, Copyright (c), by Zend Technologies

(information)

Info

You may already have a version of PHP included by your operating system. For example, macOS includes a version of PHP; however, you will often want to build your applications with a different version. You can install and manage different versions of PHP on macOS using Homebrew(link takes you to an external page).

If you do not already have a version of PHP installed, visit the PHP website(link takes you to an external page) to download and install a version appropriate for your operating system. Alternatively, use your operating system's package manager (such as APT, Yum, Pacman, Ports, or Homebrew) to install the latest supported version of PHP.

See the Composer installation documentation(link takes you to an external page) for download and installation instructions. We recommend installing Composer globally, so that you don't have to install each time you create a new project.

To check if you already have it installed, run the following command.


_10
composer --version


Starting the project

starting-project page anchor

With the prerequisites completed, create a project folder for this app by running the following command.


_10
mkdir send_mail

Next, navigate into the send_mail directory to complete the rest of the tutorial.


_10
cd send_mail

While you could use an HTTP helper library such as Guzzle or cURL to interact with the Mail Send API, it is far more efficient to use the SendGrid helper library for PHP(link takes you to an external page) instead.

To install the SendGrid helper library, run the following Composer command. It will create a composer.json file at the root of your project, and install the SendGrid helper library for PHP, along with its dependencies in a new directory named vendor.


_10
composer require sendgrid/sendgrid

As the command runs, the terminal will print output something like the following example.


_18
Using version ^7.9 for sendgrid/sendgrid
_18
./composer.json has been created
_18
Running composer update sendgrid/sendgrid
_18
Loading composer repositories with package information
_18
Updating dependencies
_18
Lock file operations: 3 installs, 0 updates, 0 removals
_18
- Locking sendgrid/php-http-client (3.14.0)
_18
- Locking sendgrid/sendgrid (7.9.2)
_18
- Locking starkbank/ecdsa (0.0.4)
_18
Writing lock file
_18
Installing dependencies from lock file (including require-dev)
_18
Package operations: 3 installs, 0 updates, 0 removals
_18
- Downloading sendgrid/php-http-client (3.14.0)
_18
- Installing starkbank/ecdsa (0.0.4): Extracting archive
_18
- Installing sendgrid/php-http-client (3.14.0): Extracting archive
_18
- Installing sendgrid/sendgrid (7.9.2): Extracting archive
_18
1 package suggestions were added by new dependencies, use `composer suggest` to see details.
_18
Generating autoload files


You're now ready to write some code to send your first email. Start by creating a new PHP file named send_mail.php in the root of your project directory.

The following PHP block contains all the code needed in your send_mail.php file to successfully deliver a message with the Twilio SendGrid Mail Send API. You can copy this code to the send_mail.php file, modify the values passed to the setFrom and addTo methods, and run the code to see what happens. We'll break down each piece of this code in the following sections.


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

Your API call must have the following components. The helper library abstracts this away, reducing the code you must write.

  • A host (the host for Web API v3 requests is always https://api.sendgrid.com/v3/ )
  • An API key passed in an Authorization Header
  • A request (when submitting data to a resource via POST or PUT , you must submit your request body in JSON format)

The code starts by loading Composer's autoloader(link takes you to an external page), which makes all of the required classes available to our code.


_10
require 'vendor/autoload.php'

It then initializes a new variable, $email, as an instance of the library's Mail class.


_10
$email = new Mail();

The code then sets the message's sender, subject, recipient, and content using the setFrom, setSubject, addTo, and addContent methods. The values passed to these methods are formatted and sent to the API in a Personalizations object when using the v3 Mail Send API.

The setSubject method accepts a string. The setFrom and addTo methods accept an email address and an optional sender name as strings. Be sure to assign addTo an address with an inbox that you can access.

The addContent method takes the message's type, which can be either text/plain or text/html, and a string value, which is the content you wish to send in the message body.


_17
// Replace with your verified sender
_17
$email->setFrom(
_17
'sender@example.com',
_17
'Example Sender'
_17
);
_17
$email->setSubject(
_17
'Sending with Twilio SendGrid is Fun'
_17
);
_17
// Replace with your recipient
_17
$email->addTo(
_17
'recipient@example.com',
_17
'Example Recipient'
_17
);
_17
$email->addContent(
_17
'text/html',
_17
'<strong>and fast with the PHP helper library.</strong>'
_17
);

With the message object initialized, a new variable, $sendgrid, is initialized, which provides the ability to send the message. This variable is a SendGrid object. The SendGrid class accepts two arguments: your API key and an options array. You need to pass in your API key only, which the code does using PHP's getenv method(link takes you to an external page). The helper library will handle setting the host, constructing your personalizations object, and formatting the message for you.


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

Lastly, the code calls the $sendgrid send method, to which you pass your $email. This method makes a request to the Mail Send API to deliver the email message, assigning the response to a variable, aptly, named $response.


_10
$response = $sendgrid->send($email);

With all the code in place, run the send_mail.php file in your terminal to send the email using the command below.


_10
php send_mail.php

You can also wrap your API call in a try block to print the status code and headers of the response or log exceptions in the try block's corresponding catch block.


_10
try {
_10
$response = $sendgrid->send($email);
_10
print $response->statusCode() . "\n";
_10
print_r($response->headers());
_10
} catch (Exception $e) {
_10
echo 'Caught exception: '. $e->getMessage() ."\n";
_10
}

If a 202 status code(link takes you to an external page) is printed to the console, your message was sent successfully. Check the inbox of the addTo address, and you will see your demo message. If you don't see the email, check your spam folder.

If you receive an error message, you can reference our response message documentation for clues about what may have gone wrong.

All responses are returned in JSON format. We specify this by sending the Content-Type header. The Web API v3 provides a selection of response codes, content-type headers, and pagination options to help you interpret the responses to your API requests.

(information)

Info

Get additional onboarding support. Save time, increase the quality of your sending, and feel confident you are set up for long-term success with our Email API Onboarding guide.


This is just the beginning of what you can do with our APIs. To learn more, check the resources below.


Rate this page: