# Send Transactional Emails in PHP with Twilio SendGrid
* * *
**Tags**
[ PHP ](https://www.twilio.com/en-us/blog/tag.tech-stack%253Aphp) [ Developer insights ](https://www.twilio.com/en-us/blog/tag.topic%253Adeveloper-insights)
**Products**
[ Twilio SendGrid Email API logo Email API ](https://www.twilio.com/en-us/products/email-api)
* * *
[ Start for free  ](https://www.twilio.com/try-twilio)
Time to read: 4 minutes
  * [ Facebook logo ](https://www.facebook.com/sharer/sharer.php?u=https://www.twilio.com/en-us/blog/developers/tutorials/product/send-transactional-emails-php-twilio-sendgrid "Share via Facebook")
  * [ Twitter Logo Follow us on Twitter ](https://twitter.com/intent/tweet?url=https://www.twilio.com/en-us/blog/developers/tutorials/product/send-transactional-emails-php-twilio-sendgrid "Share via X")
  * [ LinkedIn logo ](https://www.linkedin.com/sharing/share-offsite/?url=https://www.twilio.com/en-us/blog/developers/tutorials/product/send-transactional-emails-php-twilio-sendgrid "Share via LinkedIn")
  *   * [ ](https://www.twilio.com/blog.feed.xml "Twilio RSS")


October 30, 2019 
**Written by**
[ Marcus Battle ](https://www.twilio.com/en-us/blog/authors/author.mbattle)
Twilion 
* * *
[Send Transactional Emails in PHP with Twilio SendGrid](https://www.twilio.com/en-us/blog/developers/tutorials/product/send-transactional-emails-php-twilio-sendgrid#Send-Transactional-Emails-in-PHP-with-Twilio-SendGrid)
![Transactional Emails in PHP with Twilio SendGrid](https://www.twilio.com/content/dam/twilio-com/global/en/blog/legacy/2019/send-transactional-emails-php-twilio-sendgrid/axg4gbFqn8X2EbyHFhQVV6Usx-6HIIT_QlH3Ae5WB5gL11SDxHDk7bDLBjeGNiChecAqoAn4NqZ6o-.png)
Your inbox is undoubtedly full of transactional emails. While they prevent you from getting to [inbox zero](https://whatis.techtarget.com/definition/inbox-zero), without them, you’d have a less informative Internet experience.
[Transactional emails](https://sendgrid.com/docs/for-developers/sending-email/getting-started-with-transactional-emails/?utm_referrer=https%3A%2F%2Fwww.twilio.com%2Fen-us%2Fblog%2Fdevelopers%2Ftutorials%2Fproduct%2Fsend-transactional-emails-php-twilio-sendgrid) are those sent from within an application when a certain event is triggered. In the case of an e-commerce store, you would send a transactional email when the user has completed their account signup and when they successfully complete their purchase.
Historically, sending an email in PHP has been one of the simplest tasks to complete. With only the [mail()](https://www.php.net/manual/en/function.mail.php) function, you need only to insert a call to the [mail()](https://www.php.net/manual/en/function.mail.php) function within any part of your workflow to send a transactional email.
It’s simplicity, though, has also been its downfall. If you are unfamiliar with the `mail()` function, know that PHP developers have a love-hate relationship with it because, while it’s easy to implement, it has its challenges with bulk messaging and deliverability through SPAM filters. This is largely why transactional email products such as [Twilio SendGrid](https://www.twilio.com/sendgrid) exist, to ensure that emails arrive successfully, every time.
This tutorial will teach you how to use Twilio SendGrid to send transactional emails in PHP.
## [Tools Needed to Complete This Tutorial](https://www.twilio.com/en-us/blog/developers/tutorials/product/send-transactional-emails-php-twilio-sendgrid#Tools-Needed-to-Complete-This-Tutorial)
Because you’re building this logic in one PHP file, there aren’t too many prerequisites for this tutorial. Make sure you have the following dependencies installed:
  * A [Twilio SendGrid Account](https://signup.sendgrid.com/)
  * [Composer](https://getcomposer.org/) globally installed


## [Create a New Project Folder and Files](https://www.twilio.com/en-us/blog/developers/tutorials/product/send-transactional-emails-php-twilio-sendgrid#Create-a-New-Project-Folder-and-Files)
In your console window, run the following commands to generate a project folder and source file:
Copy code
```
$ mkdir php-sendgrid && cd php-sendgrid
$ touch email.php
```

## [Set Up the Composer Project](https://www.twilio.com/en-us/blog/developers/tutorials/product/send-transactional-emails-php-twilio-sendgrid#Set-Up-the-Composer-Project)
Composer is a tool for dependency management in PHP. It allows you to easily declare which libraries your project needs. In your console window, create a new `composer.json` file by running the following command:
Copy code
```
$ touch composer.json
```

Open the newly created file in your IDE by running `open composer.json` and add the following declaration:
Copy code
```
{
    "require": {}
}
```

Run `composer install` to generate the vendor directory.
## [Install Dotenv](https://www.twilio.com/en-us/blog/developers/tutorials/product/send-transactional-emails-php-twilio-sendgrid#Install-Dotenv)
Next, you’ll need a way to securely store your Twilio SendGrid API Key. The [phpdotenv package](https://github.com/vlucas/phpdotenv) by [Vance Lucas](http://www.vancelucas.com/) will create a mechanism to load environment variables from a `.env` file to `getenv()`, `$_ENV` and `$_SERVER`. Let’s install it by running the following command:
Copy code
```
$ composer require vlucas/phpdotenv && touch .env
```

Let’s create a placeholder for our API key by adding the following variable to our file:
Copy code
```
SENDGRID_API_KEY=""
```

## [Sign Up for a Twilio SendGrid API Key](https://www.twilio.com/en-us/blog/developers/tutorials/product/send-transactional-emails-php-twilio-sendgrid#Sign-Up-for-a-Twilio-SendGrid-API-Key)
As mentioned before, we will use Twilio SendGrid to supply our transactional emails. After you create your [SendGrid](https://sendgrid.com/?utm_referrer=https%3A%2F%2Fwww.twilio.com%2Fen-us%2Fblog%2Fdevelopers%2Ftutorials%2Fproduct%2Fsend-transactional-emails-php-twilio-sendgrid) account, [navigate to your dashboard](https://app.sendgrid.com/settings/api_keys) in order to generate an API key.
![Create Twilio SendGrid API key](https://www.twilio.com/content/dam/twilio-com/global/en/blog/legacy/2019/send-transactional-emails-php-twilio-sendgrid/oXt-ApUutRQnqpl0IBl8ynn3Ib3WBxRoRx5xsA3Q6EvWUZhPQesp6u2Fw9TJjGPwIJz_TB-poxX9MC.png)
Give the API Key a name such as “PHP Emails” and select “Full Access” for the API Key permissions.
Click on “Create & View” and copy the newly created key to the `SENDGRID_API_KEY` variable in your `.env` file.
**NOTE:**_You will not be able to retrieve the API key after you leave this page. Be sure to copy and paste it somewhere safe for retrieval at a later time, if desired._
## [Install the Twilio SendGrid PHP SDK](https://www.twilio.com/en-us/blog/developers/tutorials/product/send-transactional-emails-php-twilio-sendgrid#Install-the-Twilio-SendGrid-PHP-SDK)
Now that the Twilio SendGrid API key has been generated, you’ll need to install the SendGrid PHP SDK in order to access the SendGrid API. Run the following command:
Copy code
```
$ composer require sendgrid/sendgrid
```

## [Create the Code to Send a Transactional Email](https://www.twilio.com/en-us/blog/developers/tutorials/product/send-transactional-emails-php-twilio-sendgrid#Create-the-Code-to-Send-a-Transactional-Email)
You’re ready to create the code to send your transactional email! Add the following code to the `email.php` file:
Copy code
```
<?php

require 'vendor/autoload.php';

// Load our `.env` variables
$dotenv = Dotenv\Dotenv::create(__DIR__);
$dotenv->load();

// Declare a new SendGrid Mail object
$email = new \SendGrid\Mail\Mail();

// Set the email parameters
$email->setFrom("mbattle@twilio.com", "Marcus Battle");
$email->setSubject("Sending with SendGrid is Fun");

$email->addTo("marcus@marcusbattle.com", "Marcus Battle");
$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'));

// Send the email
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";
}
```

## [Testing](https://www.twilio.com/en-us/blog/developers/tutorials/product/send-transactional-emails-php-twilio-sendgrid#Testing)
From the console window, run the following command: `php email.php`
![Example SendGrid email](https://www.twilio.com/content/dam/twilio-com/global/en/blog/legacy/2019/send-transactional-emails-php-twilio-sendgrid/Oj3pxpZ8_8bc_6kOT1Lr-U1Z96XKz30GcTOHZ0DeLnOXqgEyf2nRlQVbBkfdfA1P9fd7M6krN0CBqs.png)
**NOTE:**_Based on your domain settings, i_ _t is possible that your email was blocked by Google’s_ _DMARC_ _policy. If you notice that the email was successfully sent, but put on_ _the blocked list_ _, change the email “from” address to_ _an acceptable domain_ _._
## [Conclusion](https://www.twilio.com/en-us/blog/developers/tutorials/product/send-transactional-emails-php-twilio-sendgrid#Conclusion)
It’s amazing that with less than thirty lines of code, you have transactional emails working in a stand-alone PHP script. This logic could be used to provide transactional emails in any existing PHP application.
We could even extend this further by providing transactional SMS at the same time an email is sent.
_Marcus Battle is the PHP Developer of Technical Content at Twilio. He is committed to prompting and rallying PHP developers across the world to build the future of communications. He can be reached on Twitter at_ _[@themarcusbattle](https://twitter.com/themarcusbattle)_ _and via_ _email_ _._
##  Related Posts 
  * [ ![](https://www.twilio.com/content/dam/twilio-com/global/en/blog/developers/developers-imagery-by-post/p-s/send-bulk-sms-with-php-and-twilio/send-bulk-sms-with-php-and-twilio.png/_jcr_content/renditions/compressed-800.webp) Send Bulk SMS With PHP and Twilio Matthew Setter  ](https://www.twilio.com/en-us/blog/developers/tutorials/send-bulk-sms-with-php-and-twilio)
  * [ ![](https://www.twilio.com/content/dam/twilio-com/global/en/blog/developers/developers-imagery-by-post/a-c/build-a-twilio---zoho-crm-voice-integration/build-twilio-zoho-crm-voice-vntegration.png/_jcr_content/renditions/compressed-800.webp) Build a Twilio + Zoho CRM Voice Integration Matthew Setter  ](https://www.twilio.com/en-us/blog/developers/tutorials/integrations/build-twilio-zoho-crm-voice-integration)
  * [ ![](https://www.twilio.com/content/dam/twilio-com/global/en/blog/importer-images/a-c/agent-to-human-protocol-with-openclaw/media1/_jcr_content/renditions/compressed-800.webp) How to Use the Agent-to-Human Communication (A2H) Protocol with OpenClaw Ryan Ferguson  Rikki Singh  ](https://www.twilio.com/en-us/blog/developers/tutorials/building-blocks/agent-to-human-protocol-with-openclaw)


##  Related Resources 
[ From APIs to SDKs to sample apps API reference documentation, SDKs, helper libraries, quickstarts, and tutorials for your language and platform. An icon of a right arrow ](https://www.twilio.com/docs) [ The latest ebooks, industry reports, and webinars Learn from customer engagement experts to improve your own communication. An icon of a right arrow ](https://www.twilio.com/en-us/resource-center) [ Twilio's developer community hub Best practices, code samples, and inspiration to build communications and digital engagement experiences. An icon of a right arrow ](https://www.twilio.com/en-us/developers)
