In this quickstart, you'll learn how to send your first email using PHP and the Twilio SendGrid Mail Send API.
Be sure to perform the following prerequisites to complete this tutorial. You can skip ahead if you've already completed these tasks.
When you sign up for a free SendGrid account, you'll be able to send 100 emails per day forever. For more account options, see our pricing page.
Twilio SendGrid requires customers to enable Two-factor authentication (2FA). You can enable 2FA with SMS or by using the Authy app. See the 2FA section of our authentication documentation for instructions.
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>
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.
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.
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.
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.
1PHP 8.0.3 (cli) (built: Mar 4 2021 20:42:56) ( NTS )2Copyright (c) The PHP Group3Zend Engine v4.0.3, Copyright (c) Zend Technologies4with Zend OPcache v8.0.3, Copyright (c), by Zend Technologies
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.
If you do not already have a version of PHP installed, visit the PHP website 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 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
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 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.
1Using version ^7.9 for sendgrid/sendgrid2./composer.json has been created3Running composer update sendgrid/sendgrid4Loading composer repositories with package information5Updating dependencies6Lock file operations: 3 installs, 0 updates, 0 removals7- Locking sendgrid/php-http-client (3.14.0)8- Locking sendgrid/sendgrid (7.9.2)9- Locking starkbank/ecdsa (0.0.4)10Writing lock file11Installing dependencies from lock file (including require-dev)12Package operations: 3 installs, 0 updates, 0 removals13- Downloading sendgrid/php-http-client (3.14.0)14- Installing starkbank/ecdsa (0.0.4): Extracting archive15- Installing sendgrid/php-http-client (3.14.0): Extracting archive16- Installing sendgrid/sendgrid (7.9.2): Extracting archive171 package suggestions were added by new dependencies, use `composer suggest` to see details.18Generating 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<?php23declare(strict_types=1);45require 'vendor/autoload.php';67use \SendGrid\Mail\Mail;89$email = new Mail();10// Replace the email address and name with your verified sender11$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 recipient17$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'));26try {27$response = $sendgrid->send($email);28printf("Response status: %d\n\n", $response->statusCode());2930$headers = array_filter($response->headers());31echo "Response Headers\n\n";32foreach ($headers as $header) {33echo '- ' . $header . "\n";34}35} catch (Exception $e) {36echo '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.
https://api.sendgrid.com/v3/
)POST
or PUT
, you must submit your request body in JSON format)The code starts by loading Composer's autoloader, 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 sender2$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 recipient10$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. 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.
1try {2$response = $sendgrid->send($email);3print $response->statusCode() . "\n";4print_r($response->headers());5} catch (Exception $e) {6echo 'Caught exception: '. $e->getMessage() ."\n";7}
If a 202
status code 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.
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.