Skip to contentSkip to navigationSkip to topbar
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.

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.

php -v

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

1
PHP 8.0.3 (cli) (built: Mar 4 2021 20:42:56) ( NTS )
2
Copyright (c) The PHP Group
3
Zend Engine v4.0.3, Copyright (c) Zend Technologies
4
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, Pac-Man, 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.

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.

mkdir send_mail

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

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.

composer require sendgrid/sendgrid

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

1
Using version ^7.9 for sendgrid/sendgrid
2
./composer.json has been created
3
Running composer update sendgrid/sendgrid
4
Loading composer repositories with package information
5
Updating dependencies
6
Lock file operations: 3 installs, 0 updates, 0 removals
7
- Locking sendgrid/php-http-client (3.14.0)
8
- Locking sendgrid/sendgrid (7.9.2)
9
- Locking starkbank/ecdsa (0.0.4)
10
Writing lock file
11
Installing dependencies from lock file (including require-dev)
12
Package operations: 3 installs, 0 updates, 0 removals
13
- Downloading sendgrid/php-http-client (3.14.0)
14
- Installing starkbank/ecdsa (0.0.4): Extracting archive
15
- Installing sendgrid/php-http-client (3.14.0): Extracting archive
16
- Installing sendgrid/sendgrid (7.9.2): Extracting archive
17
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.

1
<?php
2
3
declare(strict_types=1);
4
5
require 'vendor/autoload.php';
6
7
use \SendGrid\Mail\Mail;
8
9
$email = new Mail();
10
// Replace the email address and name with your verified sender
11
$email->setFrom(
12
'sender@example.com',
13
'Example Sender'
14
);
15
$email->setSubject('Sending with Twilio SendGrid is Fun');
16
// Replace the email address and name with your recipient
17
$email->addTo(
18
'recipient@example.com',
19
'Example Recipient'
20
);
21
$email->addContent(
22
'text/html',
23
'<strong>and fast with the PHP helper library.</strong>'
24
);
25
$sendgrid = new \SendGrid(getenv('SENDGRID_API_KEY'));
26
try {
27
$response = $sendgrid->send($email);
28
printf("Response status: %d\n\n", $response->statusCode());
29
30
$headers = array_filter($response->headers());
31
echo "Response Headers\n\n";
32
foreach ($headers as $header) {
33
echo '- ' . $header . "\n";
34
}
35
} catch (Exception $e) {
36
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.

require 'vendor/autoload.php'

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

$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.

1
// Replace with your verified sender
2
$email->setFrom(
3
'sender@example.com',
4
'Example Sender'
5
);
6
$email->setSubject(
7
'Sending with Twilio SendGrid is Fun'
8
);
9
// Replace with your recipient
10
$email->addTo(
11
'recipient@example.com',
12
'Example Recipient'
13
);
14
$email->addContent(
15
'text/html',
16
'<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.

$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.

$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.

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.

1
try {
2
$response = $sendgrid->send($email);
3
print $response->statusCode() . "\n";
4
print_r($response->headers());
5
} catch (Exception $e) {
6
echo 'Caught exception: '. $e->getMessage() ."\n";
7
}

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.

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.