Send Email Attachments Using Twilio SendGrid and PHP

November 26, 2019
Written by
Felistas Ngumi
Contributor
Opinions expressed by Twilio contributors are their own

PHP Email Attachments with SendGrid

Companies with a clear commitment to efficient communication rely heavily on email as a communication tool. At some point, this dependency requires sending email attachments to customers for transactions such as receiving their invoice after an online purchase, sending of travel itinerary and many more. These attachments can be images, videos, or even documents. Twilio SendGrind API provides a simple and efficient way of doing this. In this tutorial, I will take you through how to send email attachments with SendGrid and PHP.

Prerequisites

Ensure you have the following installed in your local development environment:

  1. PHP version 7.0 or higher
  2. Composer

Also, head over to SendGrid and create a free account.

Getting Started

In your preferred terminal, run the following commands to set up the project:

$ mkdir demo && cd demo
$ touch email.php
$ composer require sendgrid/sendgrid vlucas/phpdotenv

The above commands created a folder called demo which you will use to store all of your project files. We have also installed two packages that will be useful when building this project. The vlucas/phpdotenv package is responsible for loading environment variables into your application and the sendgrid/sendgrid package gives access to the SendGrid API inside the PHP application.

Obtaining Your SendGrid API Key

You’ll need a SendGrid API key in order to send your emails. After creating an account with SendGrid, navigate to the API Keys section under Settings to create one. Be sure to select the Full Access option like shown below:  

SendGrid API Key console

NOTE: You should never use sensitive credentials directly in your code e.g API Keys. Always store them in a .env file.

Run the following command in your terminal to create the .env file.

$ touch .env

Next, add the following key to your file and copy the API Key you just generated.

SENDGRID_API_KEY= your_sendgrid_api_key

Send Email Attachments

In your preferred code editor, add the following lines of code in the email.php file.

<?php
require 'vendor/autoload.php';

$dotenv = Dotenv\Dotenv::create(__DIR__);
$dotenv->load();

$email = new \SendGrid\Mail\Mail();
$email->setFrom("test@example.com", "Test User");
$email->setSubject("Send Email Attachments with Twilio SendGrid");
$email->addTo("felistaswaceera@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 'Email sent successfuly' . "\n";
   print 'Status Code: ' . $response->statusCode() . "\n";
} catch (Exception $e) {
   echo 'Caught exception: '.  $e->getMessage(). "\n";
}

Note: Be sure to replace the recipient address to yours.

The above code loads the set environment variables, then instantiates a new SendGrid Mail class that we use to call methods such as setFrom to construct the final email object sent to the recipient.

Testing

Add a pdf file in the root directory of this project. Replace test.pdf in the code with the name of the file you have added.

In your terminal, run php email.php. You should see a new email in your inbox!

Success email

Jim Carey dancing

Conclusion

In this tutorial, we have learned how to send email attachments using Twilio SendGrid and PHP.  I would love to hear from you! Let's chat on Twitter or send me an email. Happy hacking!