Skip to content

TomAshe/sendgrid-php-ng

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

SendGrid-PHP

This is a version of SendGrid-PHP which uses Guzzle 6.x

Badge Bling: BuildStatus ScanStatus

This library allows you to quickly and easily send emails through SendGrid using PHP with the help of Guzzle 6.x. Guzzle is a very popular HTTP client for PHP used in many other PHP packages.

SendGrid has chosen to write their own PHP HTTP client. This module uses Guzzle instead. From the point that SendGrid choose to provide their own HTTP client library, this module has permanantly forked away from the official code and is mantained independently from the official libraries. This module uses Guzzle for the transport layer and so the code is differnt. Contributions to help maintain this libary is welcome!

Mainly, this API is maintained in support of the Drupal Sendgrid Integration Module that I also maintain. Drupal 8 ships with Guzzle 6.x in the core of the software and Guzzle 6.x supports the standardization of PSR messages. The official Sendgrid PHP API supports only the deprecated Guzzle 3.x as they are maintaining support for PHP 5.3.

To install this library it is best to use composer. I have published a package through Packagist for this library. Use the following in your composer.json:

"require": {
    "fastglass/sendgrid": ">=1.0.9"
  }

Example Code

If you would like to look at some example code for using this library, clone this repository.

Upgade to V3 API

Work is underway (in a development branch) to upgrade this module to the V3 API. Please help if you can!

PLEASE READ THIS

TLDR: If you upgrade and don't change your code appropriately, things WILL break.

One of the most notable changes is how addTo() behaves. We are now using our Web API parameters instead of the X-SMTPAPI header. What this means is that if you call addTo() multiple times for an email, ONE email will be sent with each email address visible to everyone. To utilize the original behavior of having an individual personalized email sent to each recipient you must now use addSmtpapiTo(). This will break substitutions if there is more than one To address added unless you update to use addSmtpapiTo().

Smtpapi addressing methods cannot be mixed with non Smtpapi addressing methods. Meaning you cannot currently use Cc and Bcc with addSmtpapiTo().

The send() method now raises a \SendGrid\Exception by default if the response code is not 200 and returns an instance of \SendGrid\Response.


Important: This library requires PHP 5.5 or higher.

$sendgrid = new SendGrid\Client('YOUR_SENDGRID_APIKEY');
$email = new SendGrid\Email();
$email
    ->addTo('[email protected]')
    ->setFrom('[email protected]')
    ->setSubject('Subject goes here')
    ->setText('Hello World!')
    ->setHtml('<strong>Hello World!</strong>');

$sendgrid->send($email);

// Or catch the error

try {
	$sendgrid->send($email);
} catch(\SendGrid\Exception $e) {
	echo $e->getCode();
	foreach($e->getErrors() as $er) {
		echo $er;
	}
}

Installation

Add SendGrid to your composer.json file. If you are not using Composer, you should be. It's an excellent way to manage dependencies in your PHP application.

{
  "require": {
    "fastglass/sendgrid": "~1.0"
  }
}

Then at the top of your PHP script require the autoloader:

require 'vendor/autoload.php';

Alternative: Install from zip

If you are not using Composer, simply download and install the latest packaged release of the library as a zip.

[⬇︎ Download Packaged Library ⬇︎]https://github.com/taz77/sendgrid-php-ng/archive/master.zip)

Then require the library from package:

require("path/to/sendgrid-php-ng/sendgrid-php.php");

Example App

There is a sendgrid-php-example app to help jumpstart your development.

Usage

To begin using this library, initialize the SendGrid object with a SendGrid API Key. API Key is the only preferred method allowed. To configure API keys, visit https://sendgrid.com/beta/settings/api_key.

$sendgrid = new SendGrid('YOUR_SENDGRID_APIKEY');

Create a new SendGrid Email object and add your message details.

$email = new SendGrid\Email();
$email
    ->addTo('[email protected]')
    ->addTo('[email protected]')
    ->setFrom('[email protected]')
    ->setSubject('Subject goes here')
    ->setText('Hello World!')
    ->setHtml('<strong>Hello World!</strong>')
;

Send it.

$sendgrid->send($email);

Exceptions

A SendGrid\Exception is raised by default if the response is not 200 OK.

To disable exceptions, pass in the raise_exceptions => false option when creating a SendGrid\Client.

$client = new SendGrid('SENDGRID_APIKEY', array('raise_exceptions' => false));

Options

Options may be passed to the library when initializing the SendGrid object:

$options = array(
    'turn_off_ssl_verification' => false,
    'protocol' => 'https',
    'host' => 'api.sendgrid.com',
    'endpoint' => '/api/mail.send.json',
    'port' => null,
    'url' => null,
    'raise_exceptions' => false
);
$sendgrid = new SendGrid('YOUR_SENDGRID_APIKEY', $options);

Changing URL

You may change the URL sendgrid-php uses to send email by supplying various parameters to options, all parameters are optional:

$sendgrid = new SendGrid\Client(
    'YOUR_SENDGRID_APIKEY',
    array(
        'protocol' => 'http',
        'host' => 'sendgrid.org',
        'endpoint' => '/send',
        'port' => '80'
    )
);

A full URL may also be provided:

$sendgrid = new SendGrid\Client(
    'YOUR_SENDGRID_APIKEY',
    array( 'url' => 'http://sendgrid.org:80/send')
);

Ignoring SSL certificate verification

You can optionally ignore verification of SSL certificate when using the Web API.

$sendgrid = new SendGrid\Client(
    'YOUR_SENDGRID_APIKEY',
    array("turn_off_ssl_verification" => true)
);

Response

An instance of \SendGrid\Response is returned from the send() method.

$email = new SendGrid\Email();
$email
    ->addTo('[email protected]')
    ->setFrom('[email protected]')
    ->setSubject('Subject goes here')
    ->setText('Hello World!');
$res = sendgrid->send($email);

var_dump($res);

// Output
object(SendGrid\Response)#31 (4) {
  ["code"]=>
  int(200)
  ["headers"]=>
  object(GuzzleHttp\Message\Header\HeaderCollection)#48 (1) {
    ["headers":protected]=>
    array(6) {
	...
      ["content-type"]=>
      object(GuzzleHttp\Message\Header)#41 (3) {
        ["values":protected]=>
        array(1) {
          [0]=>
          string(16) "application/json"
        }
        ["header":protected]=>
        string(12) "Content-Type"
        ["glue":protected]=>
        string(1) ","
      }
   ...
    }
  }
  ["raw_body"]=>
  string(21) "{"message":"success"}"
  ["body"]=>
  array(1) {
    ["message"]=>
    string(7) "success"
  }
}

getCode

Returns the status code of the response.

getHeaders

Returns the headers of the response as a array. Keys are the response identifiers such as "Authorization"

getRawBody

Returns the unparsed JSON response from SendGrid.

getBody

Returns the parsed JSON from SendGrid.

Exception

A \SendGrid\Exception is raised if the response code is not 200. Catching it is optional but highly recommended.

try {
    $sendgrid->send($email);
} catch(\SendGrid\Exception $e) {
    echo $e->getCode() . "\n";
    foreach($e->getErrors() as $er) {
        echo $er;
    }
}

// Output
400
Permission denied, wrong credentials

SMTPAPI

This library makes use of sendgrid/smtpapi-php for all things related to the X-SMTPAPI Header.


Library Methods

addTo

You can add one or multiple TO addresses using addTo along with an optional TO name. Note: If using TO names, each address needs a name.

$email = new SendGrid\Email();
$email
    ->addTo('[email protected]')
    ->addTo('[email protected]')
;
$sendgrid->send($email);

// With names
$email = new SendGrid\Email();
$email
	->addTo('[email protected]', 'Frank Foo')
	->addTo('[email protected]', 'Joe Bar')
;
$sendgrid->send($email);

// As an array
$email = new SendGrid\Email();
$email
    ->addTo(array('[email protected]', 'bar@example'), array('Frank Foo', 'Brian Bar'))
;
$sendgrid->send($email);

addSmtpapiTo

Add a TO address to the smtpapi header along with an optional name.

$email = new SendGrid\Email();
$email
    ->addSmtpapiTo('[email protected]')
    ->addSmtpapiTo('[email protected]', 'Mike Bar')
;
$sendgrid->send($email);

setTos

If you prefer, you can add multiple TO addresses as an array using the setTos method. This will unset any previous addTos you appended.

$email = new SendGrid\Email();
$emails = array("[email protected]", "[email protected]", "[email protected]");
$email->setTos($emails);
$sendgrid->send($email);

setSmtpapiTos

$email = new SendGrid\Email();
$emails = array("[email protected]", "Brian Bar <[email protected]>", "[email protected]");
$email->setSmtpapiTos($emails);
$sendgrid->send($email);

setFrom

$email = new SendGrid\Email();
$email->setFrom('[email protected]');
$sendgrid->send($email);

setFromName

$email = new SendGrid\Email();
$email
    ->setFrom('[email protected]')
    ->setFromName('Foo Bar')
;
$sendgrid->send($email);

setReplyTo

$email = new SendGrid\Email();
$email
    ->addTo('[email protected]')
    ->setReplyTo('[email protected]')
    ->setFromName('John Doe')
   ...
;

Cc

addCc

$email = new SendGrid\Email();
$email->addCc('[email protected]');
$sendgrid->send($email);

setCc

$email = new SendGrid\Email();
$email->setCc('[email protected]');
$sendgrid->send($email);

setCcs

$email = new SendGrid\Email();
$emails = array("[email protected]", "[email protected]", "[email protected]");
$email->setCcs($emails);
$sendgrid->send($email);

removeCc

$email->removeCc('[email protected]');

Bcc

Use multiple addSmtpapiTos as a superior alternative to setBcc.

$email = new SendGrid\Email();
$email
    ->addSmtpapiTo('[email protected]')
    ->addSmtpapiTo('[email protected]')
    ->addSmtpapiTo('[email protected]')
   ...
;

But if you do still have a need for Bcc you can do the following:

addBcc

$email = new SendGrid\Email();
$email->addTo('[email protected]');
$email->addBcc('[email protected]');
$sendgrid->send($email);

setBcc

$email = new SendGrid\Email();
$email->setBcc('[email protected]');
$sendgrid->send($email);

setBccs

$email = new SendGrid\Email();
$emails = array("[email protected]", "[email protected]", "[email protected]");
$email->setBccs($emails);
$sendgrid->send($email);

removeBcc

$email->removeBcc('[email protected]');

Important Gotcha: Using multiple addSmtpapiTos is recommended over bcc whenever possible. Each user will receive their own personalized email with that setup, and only see their own email.

Standard setBcc will hide who the email is addressed to. If you use multiple addSmtpapiTo's, each user will receive a personalized email showing only their email. This is more friendly and more personal.

setSubject

$email = new SendGrid\Email();
$email->setSubject('This is a subject');
$sendgrid->send($email);

setText

$email = new SendGrid\Email();
$email->setText('This is some text');
$sendgrid->send($email);

setHtml

$email = new SendGrid\Email();
$email->setHtml('<h1>This is an html email</h1>');
$sendgrid->send($email);

setDate

$email = new SendGrid\Email();
$email->setDate('Wed, 17 Dec 2014 19:21:16 +0000');
$sendgrid->send($email);

setSendAt

$email = new SendGrid\Email();
$email->setSendAt(1409348513);
$sendgrid->send($email);

setSendEachAt

$email = new SendGrid\Email();
$email->setSendEachAt(array(1409348513, 1409348514, 1409348515));
$sendgrid->send($email);

addSendEachAt

$email = new SendGrid\Email();
$email
    ->addSendEachAt(1409348513)
    ->addSendEachAt(1409348514)
    ->addSendEachAt(1409348515)
;
$sendgrid->send($email);

Categories

Categories are used to group email statistics provided by SendGrid.

To use a category, simply set the category name. Note: there is a maximum of 10 categories per email.

addCategory

$email = new SendGrid\Email();
$email
    ->addTo('[email protected]')
    ...
    ->addCategory("Category 1")
    ->addCategory("Category 2")
;

setCategory

$email = new SendGrid\Email();
$email
    ->addTo('[email protected]')
    ...
    ->setCategory("Category 1")
;

setCategories

$email = new SendGrid\Email();
$categories = array("Category 1", "Category 2", "Category 3");
$email->setCategories($categories);

removeCategory

$email = new SendGrid\Email();
$email
    ->addTo('[email protected]')
    ...
    ->removeCategory("Category 1")
;

Attachments

Attachments are currently file based only, with future plans for an in memory implementation as well.

File attachments are limited to 7 MB per file.

addAttachment

$email = new SendGrid\Email();
$email
    ->addTo('[email protected]')
    ...
    ->addAttachment("../path/to/file.txt")
;

setAttachment

$email = new SendGrid\Email();
$email
    ->addTo('[email protected]')
    ...
    ->setAttachment("../path/to/file.txt")
;

setAttachments

$email = new SendGrid\Email();
$attachments = array("../path/to/file1.txt", "../path/to/file2.txt");
$email
    ->addTo('[email protected]')
    ...
    ->setAttachments($attachments)
;

removeAttachment

$email = new SendGrid\Email();
$email
    ->addTo('[email protected]')
    ...
    ->addAttachment("../path/to/file.txt")
    ->removeAttachment("../path/to/file.txt")
;

You can tag files for use as inline HTML content. It will mark the file for inline disposition using the specified "cid".

$email = new SendGrid\Email();
$email
    ->addTo('[email protected]')
    ->setHtml('<div>Our logo:<img src="cid:file-cid"></div>')
    ->addAttachment("../path/to/file.png", "super_file.png", "file-cid")
;

Substitutions

Substitutions can be used to customize multi-recipient emails, and tailor them for the user.

Unless you are only sending to one recipient, please make sure to use addSmtpapiTo().

addSubstitution

$email = new SendGrid\Email();
$email
    ->addSmtpapiTo('[email protected]')
    ->addSmtpapiTo('[email protected]')
    ->addSmtpapiTo('[email protected]')
       ...
    ->setHtml("Hey %name%, we've seen that you've been gone for a while")
    ->addSubstitution('%name%', array('John', 'Harry', 'Bob'))
;

Substitutions can also be used to customize multi-recipient subjects.

$email = new SendGrid\Email();
$email
    ->addSmtpapiTo(array('[email protected]', '[email protected]', '[email protected]'))
    ->setSubject('%subject%')
    ->addSubstitution(
        '%subject%',
        array('Subject to John', 'Subject to Harry', 'Subject to Bob')
    )
    ...
;

setSubstitutions

$email = new SendGrid\Email();
$email
    ->addSmtpapiTo(array('[email protected]', '[email protected]', '[email protected]'))
    ->setSubject('%subject%')
    ->setSubstitutions(array(
        '%name%' => array('John', 'Harry', 'Bob'),
        '%subject%' => array('Subject to John', 'Subject to Harry', 'Subject to Bob')
    ))
    ...
;

Sections

Sections can be used to further customize messages for the end users. A section is only useful in conjunction with a substitution value.

addSection

$email = new SendGrid\Email();
$email
    ->addSmtpapiTo('[email protected]')
    ->addSmtpapiTo("[email protected]")
    ->addSmtpapiTo("[email protected]")
    ...
    ->setHtml("Hey %name%, you work at %place%")
    ->addSubstitution("%name%", array("John", "Harry", "Bob"))
    ->addSubstitution("%place%", array("%office%", "%office%", "%home%"))
    ->addSection("%office%", "an office")
    ->addSection("%home%", "your house")
;

setSections

$email = new SendGrid\Email();
$email
    ->addSmtpapiTo('[email protected]')
    ->addSmtpapiTo("[email protected]")
    ->addSmtpapiTo("[email protected]")
    ...
    ->setHtml("Hey %name%, you work at %place%")
    ->addSubstitution("%name%", array("John", "Harry", "Bob"))
    ->addSubstitution("%place%", array("%office%", "%office%", "%home%"))
    ->setSections(array("%office%" => "an office", "%home%" => "your house"))
;

Unique Arguments

Unique Arguments are used for tracking purposes

addUniqueArg / addUniqueArgument

$email = new SendGrid\Email();
$email
    ->addTo('[email protected]')
    ...
    ->addUniqueArg("Customer", "Someone")
    ->addUniqueArg("location", "Somewhere")
;

setUniqueArgs / setUniqueArguments

$email = new SendGrid\Email();
$email
    ->addTo('[email protected]')
    ...
    ->setUniqueArgs(array('cow' => 'chicken'))
;

Filter Settings

Filter Settings are used to enable and disable apps, and to pass parameters to those apps.

addFilter / addFilterSetting

$email = new SendGrid\Email();
$email
    ->addTo('[email protected]')
    ...
    addFilter("gravatar", "enable", 1)
    ->addFilter("footer", "enable", 1)
    ->addFilter("footer", "text/plain", "Here is a plain text footer")
    ->addFilter(
        "footer",
        "text/html",
        "<p style='color:red;'>Here is an HTML footer</p>"
    )
;

setFilters / setFilterSettings

$email = new SendGrid\Email();
$email
    ->addTo('[email protected]')
    ...
    setFilters(array("gravatar" => array("settings" => array("enable" => 1))))
;

Templates

You can easily use SendGrid's template engine by applying filters.

setTemplateId

$email = new SendGrid\Email();
$email
    ->addTo('[email protected]')
    ->setFrom('[email protected]')
    ->setFromName('Support')
    ->setSubject('Subject goes here')
    // set html or text to an empty space (see http://git.io/hCNy)
    ->setHtml(' ') // <-- triggers the html version of the template
    // AND / OR
    ->setText(' ') // <-- triggers the plaintext version of the template
    ->setTemplateId($templateId);

This is simply a convenience method for:

$email = new SendGrid\Email();
$email
    ->addFilter('templates', 'enabled', 1)
    ->addFilter('templates', 'template_id', $templateId)
;

Advanced Suppression Manager

ASM is used to handle suppression groups.

setAsmGroupId

$email = new SendGrid\Email();
$email->setAsmGroupId('my_group_id');

Headers

You can add standard email message headers as necessary.

addHeader

$email = new SendGrid\Email();
$email
    ->addTo('[email protected]')
    ...
    ->addHeader('X-Sent-Using', 'SendGrid-API')
    ->addHeader('X-Transport', 'web')
;

setHeaders

$email = new SendGrid\Email();
$email
    ->addTo('[email protected]')
    ...
    ->setHeaders(array('X-Sent-Using' => 'SendGrid-API', 'X-Transport' => 'web'))
;

removeHeader

$email = new SendGrid\Email();
$email
    ->addTo('[email protected]')
    ...
    ->addHeader('X-Sent-Using', 'SendGrid-API')
    ->addHeader('X-Transport', 'web')
;
$email->removeHeader('X-Transport');

Sending to 1,000s of emails in one batch

Sometimes you might want to send 1,000s of emails in one request. You can do that. It is recommended you break each batch up in 1,000 increments. So if you need to send to 5,000 emails, then you'd break this into a loop of 1,000 emails at a time.

$sendgrid = new SendGrid('YOUR_SENDGRID_APIKEY');
$email = new SendGrid\Email();

$recipients = array(
    "[email protected]",
    "[email protected]",
    "[email protected]"
);
$names = array("Alpha", "Beta", "Zeta");

$email
    ->setFrom("[email protected]")
    ->setSubject('[sendgrid-php-batch-email]')
    ->setSmtpapiTos($recipients)
    ->addSubstitution("%name%", $names)
    ->setText("Hey %name%, we have an email for you")
    ->setHtml("<h1>Hey %name%, we have an email for you</h1>")
;

$result = $sendgrid->send($email);

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Added some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

Running Tests

The existing tests in the test directory can be run using PHPUnit with the following command:

composer update --dev
./vendor/bin/phpunit ./tests

or if you already have PHPUnit installed globally.

cd test
phpunit

About

Sendgrid PHP API Next Generation

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages

  • PHP 100.0%