PHPackages                             awanesia/sendgrid-4.0.4 - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Mail &amp; Notifications](/categories/mail)
4. /
5. awanesia/sendgrid-4.0.4

ActiveLibrary[Mail &amp; Notifications](/categories/mail)

awanesia/sendgrid-4.0.4
=======================

This library allows you to quickly and easily send emails through SendGrid using PHP.

4.0.5(5y ago)0178MITPHPPHP &gt;=5.3CI failing

Since Jun 4Pushed 5y ago1 watchersCompare

[ Source](https://github.com/awanesia/sendgrid-4.0.4)[ Packagist](https://packagist.org/packages/awanesia/sendgrid-4.0.4)[ Docs](http://github.com/awanesia)[ RSS](/packages/awanesia-sendgrid-404/feed)WikiDiscussions master Synced 2d ago

READMEChangelog (2)Dependencies (5)Versions (3)Used By (0)

Edit Version

SendGrid-PHP
============

[](#sendgrid-php)

This library allows you to quickly and easily send emails through SendGrid using PHP.

WARNING: This module was recently upgraded from [2.2.x](https://github.com/sendgrid/sendgrid-php/tree/v2.2.1) to 3.X. There were API breaking changes for various method names. See [usage](https://github.com/sendgrid/sendgrid-php#usage) for up to date method names.

PLEASE READ THIS
----------------

[](#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.3 or higher.

[![BuildStatus](https://camo.githubusercontent.com/651d24f16a408ed3e0a3203008095dd3ad4f04cd18e722216415b3b6eb21a50e/68747470733a2f2f7472617669732d63692e6f72672f73656e64677269642f73656e64677269642d7068702e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/sendgrid/sendgrid-php)[![Latest Stable Version](https://camo.githubusercontent.com/7d123fc1c8c21948ddd4042c8a2bb5212c7efb655d99b4fce5bb197bdd59488f/68747470733a2f2f706f7365722e707567782e6f72672f73656e64677269642f73656e64677269642f76657273696f6e2e737667)](https://packagist.org/packages/sendgrid/sendgrid)

```
$sendgrid = new SendGrid('YOUR_SENDGRID_APIKEY');
$email = new SendGrid\Email();
$email
    ->addTo('foo@bar.com')
    ->setFrom('me@bar.com')
    ->setSubject('Subject goes here')
    ->setText('Hello World!')
    ->setHtml('Hello World!')
;

$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;
	}
}
```

Announcements
-------------

[](#announcements)

For users of our [Web API v3 endpoints](https://sendgrid.com/docs/API_Reference/Web_API_v3/API_Keys/index.html), we have begun integrating v3 endpoints into this library. We are also updating and enhancing the core library code.

In no particular order, we have implemented a [few of the v3](#webapiv3) endpoints already and would appreciate your feedback.

Thank you for your continued support!

Installation
------------

[](#installation)

Add SendGrid to your `composer.json` file. If you are not using [Composer](http://getcomposer.org), you should be. It's an excellent way to manage dependencies in your PHP application.

```
{
  "require": {
    "sendgrid/sendgrid": "~4.0"
  }
}
```

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

```
require 'vendor/autoload.php';
```

#### Alternative: Install from zip

[](#alternative-install-from-zip)

If you are not using Composer, simply download and install the **[latest packaged release of the library as a zip](https://sendgrid-open-source.s3.amazonaws.com/sendgrid-php/sendgrid-php.zip)**.

[**⬇︎ Download Packaged Library ⬇︎**](https://sendgrid-open-source.s3.amazonaws.com/sendgrid-php/sendgrid-php.zip)

Then require the library from package:

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

Previous versions of the library can be found in the [version index](https://sendgrid-open-source.s3.amazonaws.com/index.html).

Example App
-----------

[](#example-app)

There is a [sendgrid-php-example app](https://github.com/sendgrid/sendgrid-php-example) to help jumpstart your development.

Usage
-----

[](#usage)

To begin using this library, initialize the SendGrid object with your SendGrid [API Key](https://sendgrid.com/docs/Classroom/Send/api_keys.html). To configure API keys, visit [https://app.sendgrid.com/settings/api\_keys](https://app.sendgrid.com/settings/api_keys).

```
$sendgrid = new SendGrid('YOUR_SENDGRID_APIKEY');
```

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

```
$email = new SendGrid\Email();
$email
    ->addTo('foo@bar.com')
    //->addTo('bar@foo.com') //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.
    ->setFrom('me@bar.com')
    ->setSubject('Subject goes here')
    ->setText('Hello World!')
    ->setHtml('Hello World!')
;
```

Send it.

```
$sendgrid->send($email);
```

NOTE: The total message size is limited to 20,480,000 bytes, or approximately 19.5MB. This includes all the headers, body, and attachments. [Reference](https://sendgrid.com/docs/Classroom/Build/attachments.html)

### Exceptions

[](#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('YOUR_SENDGRID_APIKEY', array('raise_exceptions' => false));
```

### Options

[](#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

[](#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(
    'YOUR_SENDGRID_APIKEY',
    array(
        'protocol' => 'http',
        'host' => 'sendgrid.org',
        'endpoint' => '/send',
        'port' => '80'
    )
);
```

A full URL may also be provided:

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

#### Ignoring SSL certificate verification

[](#ignoring-ssl-certificate-verification)

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

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

#### Response

[](#response)

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

```
$email = new SendGrid\Email();
$email
    ->addTo('foo@bar.com')
    ->setFrom('me@bar.com')
    ->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(Guzzle\Http\Message\Header\HeaderCollection)#48 (1) {
    ["headers":protected]=>
    array(6) {
	...
      ["content-type"]=>
      object(Guzzle\Http\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

[](#getcode)

Returns the status code of the response.

```
$res = $sendgrid->send($email);
echo $res->getCode()
```

#### getHeaders

[](#getheaders)

Returns the headers of the response as a [Guzzle\\Http\\Message\\Header\\HeaderCollection object](https://docs.aws.amazon.com/aws-sdk-php/v2/api/class-Guzzle.Http.Message.Header.HeaderCollection.html).

```
$res = $sendgrid->send($email);
$guzzle = $res->getHeaders();
echo var_dump($guzzle);
```

#### getRawBody

[](#getrawbody)

Returns the unparsed JSON response from SendGrid.

```
$res = $sendgrid->send($email);
echo $res->getRawBody()
```

#### getBody

[](#getbody)

Returns the parsed JSON from SendGrid.

```
$res = $sendgrid->send($email);
echo var_dump($res->getBody());
```

### Exception

[](#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
```

### WEB API v3

[](#web-api-v3)

[APIKeys](https://sendgrid.com/docs/API_Reference/Web_API_v3/API_Keys/index.html)

List all API Keys belonging to the authenticated user. \[GET\]

```
require 'vendor/autoload.php';
Dotenv::load(__DIR__);
$sendgrid_apikey = getenv('SG_KEY');
$sendgrid = new Client($sendgrid_apikey);
$response = $sendgrid->api_keys->get();
print("Status Code: " . $response->getStatusCode() . "\n");
print("Body: " . $response->getBody() . "\n");
```

Generate a new API Key for the authenticated user. \[POST\]

```
Dotenv::load(__DIR__);
$sendgrid_apikey = getenv('SG_KEY');
$sendgrid = new Client($sendgrid_apikey);
$api_key = "My API Key";
$scopes = array("mail.send", "alerts.create", "alerts.read"); // optional
$response = $sendgrid->api_keys->post($api_key, $scopes);
print("Status Code: " . $response->getStatusCode() . "\n");
print("Body: " . $response->getBody() . "\n");
```

Update the name of an existing API Key \[PATCH\]

```
require 'vendor/autoload.php';
Dotenv::load(__DIR__);
$sendgrid_apikey = getenv('SG_KEY');
$sendgrid = new Client($sendgrid_apikey);
$api_key_id = "Q5xdErWiSO6b8fYUgtYY8g";
$response = $sendgrid->api_keys->patch($api_key_id, "Updated API Key Name");
print("Status Code: " . $response->getStatusCode() . "\n");
print("Body: " . $response->getBody() . "\n");
```

Update the name &amp; scopes of an API Key \[PUT\]

```
require 'vendor/autoload.php';
Dotenv::load(__DIR__);
$sendgrid_apikey = getenv('SG_KEY');
$sendgrid = new Client($sendgrid_apikey);
$api_key_id = "Q5xdErWiSO6b8fYUgtYY8g";
$name = "Updated API Key Name";
$scopes = array("user.profile.read", "user.profile.update");
$response = $sendgrid->api_keys->put($api_key_id, $name, $scopes);
print("Status Code: " . $response->getStatusCode() . "\n");
print("Body: " . $response->getBody() . "\n");
```php

Revoke an existing API Key [DELETE]

```php
require 'vendor/autoload.php';
Dotenv::load(__DIR__);
$sendgrid_apikey = getenv('SG_KEY');
$sendgrid = new Client($sendgrid_apikey);
$api_key_id = "Q5xdErWiSO6b8fYUgtYY8g";
$response = $sendgrid->api_keys->delete($api_key_id);
print("Status Code: " . $response->getStatusCode() . "\n");
print("Body: " . $response->getBody() . "\n");

[ASMGroups](https://sendgrid.com/docs/API_Reference/Web_API_v3/Suppression_Management/groups.html)

Retrieve all suppression groups associated with the user.

```php
require 'vendor/autoload.php';
Dotenv::load(__DIR__);
$sendgrid_apikey = getenv('SG_KEY');
$sendgrid = new Client($sendgrid_apikey);
$response = $sendgrid->asm_groups->get();
print("Status Code: " . $response->getStatusCode() . "\n");
print("Body: " . $response->getBody() . "\n");
```

[ASMSuppressions](https://sendgrid.com/docs/API_Reference/Web_API_v3/Suppression_Management/suppressions.html)

Get suppressed addresses for a given group.

```
require 'vendor/autoload.php';
Dotenv::load(__DIR__);
$sendgrid_apikey = getenv('SG_KEY');
$sendgrid = new Client($sendgrid_apikey);
$group_id = 70;
$response = $sendgrid->asm_suppressions->get($group_id);
print("Status Code: " . $response->getStatusCode() . "\n");
print("Body: " . $response->getBody() . "\n");
```

Add recipient addresses to the suppressions list for a given group.

```
$group_id = 70;
$email = 'elmer.thomas+test1@gmail.com';
$response = $sendgrid->asm_suppressions->post($group_id, $email);
print("Status Code: " . $response->getStatusCode() . "\n");
print("Body: " . $response->getBody() . "\n");

$email = array('elmer.thomas+test5@gmail.com', 'elmer.thomas+test6@gmail.com');
$response = $sendgrid->asm_suppressions->post($group_id, $email);
print("Status Code: " . $response->getStatusCode() . "\n");
print("Body: " . $response->getBody() . "\n");
```

Delete a recipient email from the suppressions list for a group.

```
$group_id = 70;
$email = 'elmer.thomas+test1@gmail.com';
$response = $sendgrid->asm_suppressions->delete($group_id, $email);
print("Status Code: " . $response->getStatusCode() . "\n");
print("Body: " . $response->getBody() . "\n");
```

### SMTPAPI

[](#smtpapi)

This library makes use of [sendgrid/smtpapi-php](https://github.com/sendgrid/smtpapi-php/) for all things related to the [X-SMTPAPI Header](https://sendgrid.com/docs/API_Reference/SMTP_API/index.html).

---

### Library Methods

[](#library-methods)

#### addTo

[](#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('foo@bar.com')
    ->addTo('another@another.com')
;
$sendgrid->send($email);

// With names
$email = new SendGrid\Email();
$email
	->addTo('foo@bar.com', 'Frank Foo')
	->addTo('another@another.com', 'Joe Bar')
;
$sendgrid->send($email);

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

#### addSmtpapiTo

[](#addsmtpapito)

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

```
$email = new SendGrid\Email();
$email
    ->addSmtpapiTo('foo@bar.com')
    ->addSmtpapiTo('another@another.com', 'Mike Bar')
;
$sendgrid->send($email);
```

#### setTos

[](#settos)

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

```
$email = new SendGrid\Email();
$emails = array("foo@bar.com", "another@another.com", "other@other.com");
$email->setTos($emails);
$sendgrid->send($email);
```

#### setSmtpapiTos

[](#setsmtpapitos)

```
$email = new SendGrid\Email();
$emails = array("foo@bar.com", "Brian Bar ", "other@example.com");
$email->setSmtpapiTos($emails);
$sendgrid->send($email);
```

#### setFrom

[](#setfrom)

```
$email = new SendGrid\Email();
$email->setFrom('foo@bar.com');
$sendgrid->send($email);
```

#### setFromName

[](#setfromname)

```
$email = new SendGrid\Email();
$email
    ->setFrom('foo@bar.com')
    ->setFromName('Foo Bar')
;
$sendgrid->send($email);
```

#### setReplyTo

[](#setreplyto)

```
$email = new SendGrid\Email();
$email
    ->addTo('foo@bar.com')
    ->setReplyTo('someone.else@example.com')
    ->setFromName('John Doe')
   ...
;
```

### Cc

[](#cc)

#### addCc

[](#addcc)

```
$email = new SendGrid\Email();
$email->addCc('foo@bar.com');
$sendgrid->send($email);
```

#### setCc

[](#setcc)

```
$email = new SendGrid\Email();
$email->setCc('foo@bar.com');
$sendgrid->send($email);
```

#### setCcs

[](#setccs)

```
$email = new SendGrid\Email();
$emails = array("foo@bar.com", "another@another.com", "other@other.com");
$email->setCcs($emails);
$sendgrid->send($email);
```

#### removeCc

[](#removecc)

```
$email->removeCc('foo@bar.com');
```

### Bcc

[](#bcc)

Use multiple `addSmtpapiTo`s as a superior alternative to `setBcc`.

```
$email = new SendGrid\Email();
$email
    ->addSmtpapiTo('foo@bar.com')
    ->addSmtpapiTo('someotheraddress@bar.com')
    ->addSmtpapiTo('another@another.com')
   ...
;
```

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

#### addBcc

[](#addbcc)

```
$email = new SendGrid\Email();
$email->addTo('bar@example.com');
$email->addBcc('foo@bar.com');
$sendgrid->send($email);
```

#### setBcc

[](#setbcc)

```
$email = new SendGrid\Email();
$email->setBcc('foo@bar.com');
$sendgrid->send($email);
```

#### setBccs

[](#setbccs)

```
$email = new SendGrid\Email();
$emails = array("foo@bar.com", "another@another.com", "other@other.com");
$email->setBccs($emails);
$sendgrid->send($email);
```

#### removeBcc

[](#removebcc)

```
$email->removeBcc('foo@bar.com');
```

**Important Gotcha**: Using multiple `addSmtpapiTo`s 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

[](#setsubject)

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

#### setText

[](#settext)

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

#### setHtml

[](#sethtml)

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

#### setDate

[](#setdate)

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

#### setSendAt

[](#setsendat)

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

#### setSendEachAt

[](#setsendeachat)

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

#### addSendEachAt

[](#addsendeachat)

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

### Categories

[](#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

[](#addcategory)

```
$email = new SendGrid\Email();
$email
    ->addTo('foo@bar.com')
    ...
    ->addCategory("Category 1")
    ->addCategory("Category 2")
;
```

#### setCategory

[](#setcategory)

```
$email = new SendGrid\Email();
$email
    ->addTo('foo@bar.com')
    ...
    ->setCategory("Category 1")
;
```

#### setCategories

[](#setcategories)

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

#### removeCategory

[](#removecategory)

```
$email = new SendGrid\Email();
$email
    ->addTo('foo@bar.com')
    ...
    ->removeCategory("Category 1")
;
```

### Attachments

[](#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

[](#addattachment)

```
$email = new SendGrid\Email();
$email
    ->addTo('foo@bar.com')
    ...
    ->addAttachment("../path/to/file.txt")
;
```

#### setAttachment

[](#setattachment)

```
$email = new SendGrid\Email();
$email
    ->addTo('foo@bar.com')
    ...
    ->setAttachment("../path/to/file.txt")
;
```

#### setAttachments

[](#setattachments)

```
$email = new SendGrid\Email();
$attachments = array("../path/to/file1.txt", "../path/to/file2.txt");
$email
    ->addTo('foo@bar.com')
    ...
    ->setAttachments($attachments)
;
```

#### removeAttachment

[](#removeattachment)

```
$email = new SendGrid\Email();
$email
    ->addTo('foo@bar.com')
    ...
    ->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('foo@bar.com')
    ->setHtml('Our logo:')
    ->addAttachment("../path/to/file.png", "super_file.png", "file-cid")
;
```

### Substitutions

[](#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

[](#addsubstitution)

```
$email = new SendGrid\Email();
$email
    ->addSmtpapiTo('john@somewhere.com')
    ->addSmtpapiTo('harry@somewhere.com')
    ->addSmtpapiTo('Bob@somewhere.com')
       ...
    ->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('john@somewhere.com', 'harry@somewhere.com', 'bob@somewhere.com'))
    ->setSubject('%subject%')
    ->addSubstitution(
        '%subject%',
        array('Subject to John', 'Subject to Harry', 'Subject to Bob')
    )
    ...
;
```

#### setSubstitutions

[](#setsubstitutions)

```
$email = new SendGrid\Email();
$email
    ->addSmtpapiTo(array('john@somewhere.com', 'harry@somewhere.com', 'bob@somewhere.com'))
    ->setSubject('%subject%')
    ->setSubstitutions(array(
        '%name%' => array('John', 'Harry', 'Bob'),
        '%subject%' => array('Subject to John', 'Subject to Harry', 'Subject to Bob')
    ))
    ...
;
```

### Sections

[](#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

[](#addsection)

```
$email = new SendGrid\Email();
$email
    ->addSmtpapiTo('john@somewhere.com')
    ->addSmtpapiTo("harry@somewhere.com")
    ->addSmtpapiTo("Bob@somewhere.com")
    ...
    ->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

[](#setsections)

```
$email = new SendGrid\Email();
$email
    ->addSmtpapiTo('john@somewhere.com')
    ->addSmtpapiTo("harry@somewhere.com")
    ->addSmtpapiTo("Bob@somewhere.com")
    ...
    ->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)

[Unique Arguments](https://sendgrid.com/docs/API_Reference/SMTP_API/unique_arguments.html) are used for tracking purposes.

NOTE: While you can attach an unlimited number of unique arguments to your email, there is an upper bound of 10,000 bytes. Before passing an email into the `send` function, you should do the following:

```
if (mb_strlen($myEmail->smtpapi->jsonString(), 'UTF-8') > 10000) {
    // throw Exception
}

```

#### addUniqueArg / addUniqueArgument

[](#adduniquearg--adduniqueargument)

```
$email = new SendGrid\Email();
$email
    ->addTo('foo@bar.com')
    ...
    ->addUniqueArg("Customer", "Someone")
    ->addUniqueArg("location", "Somewhere")
;
```

#### setUniqueArgs / setUniqueArguments

[](#setuniqueargs--setuniquearguments)

```
$email = new SendGrid\Email();
$email
    ->addTo('foo@bar.com')
    ...
    ->setUniqueArgs(array('cow' => 'chicken'))
;
```

### Filter Settings

[](#filter-settings)

[Filter Settings](https://sendgrid.com/docs/API_Reference/SMTP_API/apps.html) are used to enable and disable apps, and to pass parameters to those apps.

#### addFilter / addFilterSetting

[](#addfilter--addfiltersetting)

```
$email = new SendGrid\Email();
$email
    ->addTo('foo@bar.com')
    ...
    addFilter("gravatar", "enable", 1)
    ->addFilter("footer", "enable", 1)
    ->addFilter("footer", "text/plain", "Here is a plain text footer")
    ->addFilter(
        "footer",
        "text/html",
        "Here is an HTML footer"
    )
;
```

#### setFilters / setFilterSettings

[](#setfilters--setfiltersettings)

```
$email = new SendGrid\Email();
$email
    ->addTo('foo@bar.com')
    ...
    setFilters(array("gravatar" => array("settings" => array("enable" => 1))))
;
```

### Templates

[](#templates)

You can easily use SendGrid's [template engine](https://sendgrid.com/docs/User_Guide/Apps/template_engine.html) by applying filters.

#### setTemplateId

[](#settemplateid)

```
$email = new SendGrid\Email();
$email
    ->addTo('someone@example.com')
    ->setFrom('support@example.com')
    ->setFromName('Support')
    ->setSubject('Subject goes here')
    // set html or text to an empty space (see http://git.io/hCNy)
    ->setHtml(' ') // setText(' ') // 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

[](#advanced-suppression-manager)

[ASM](https://sendgrid.com/docs/User_Guide/advanced_suppression_manager.html) is used to handle suppression groups.

#### setAsmGroupId

[](#setasmgroupid)

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

### Headers

[](#headers)

You can add standard email message headers as necessary.

#### addHeader

[](#addheader)

```
$email = new SendGrid\Email();
$email
    ->addTo('foo@bar.com')
    ...
    ->addHeader('X-Sent-Using', 'SendGrid-API')
    ->addHeader('X-Transport', 'web')
;
```

#### setHeaders

[](#setheaders)

```
$email = new SendGrid\Email();
$email
    ->addTo('foo@bar.com')
    ...
    ->setHeaders(array('X-Sent-Using' => 'SendGrid-API', 'X-Transport' => 'web'))
;
```

#### removeHeader

[](#removeheader)

```
$email = new SendGrid\Email();
$email
    ->addTo('foo@bar.com')
    ...
    ->addHeader('X-Sent-Using', 'SendGrid-API')
    ->addHeader('X-Transport', 'web')
;
$email->removeHeader('X-Transport');
```

### Sending to 1,000s of emails in one batch

[](#sending-to-1000s-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(
    "alpha@mailinator.com",
    "beta@mailinator.com",
    "zeta@mailinator.com"
);
$names = array("Alpha", "Beta", "Zeta");

$email
    ->setFrom("from@mailinator.com")
    ->setSubject('[sendgrid-php-batch-email]')
    ->setSmtpapiTos($recipients)
    ->addSubstitution("%name%", $names)
    ->setText("Hey %name%, we have an email for you")
    ->setHtml("Hey %name%, we have an email for you")
;

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

Contributing
------------

[](#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
-------------

[](#running-tests)

The existing tests in the `test` directory can be run using [PHPUnit](https://github.com/sebastianbergmann/phpunit/) with the following command:

```
composer update --dev
./vendor/bin/phpunit --bootstrap test/unit/bootstrap.php --filter test* test/unit
```

or if you already have PHPUnit installed globally.

```bash
phpunit --bootstrap test/unit/bootstrap.php --filter test* test/unit
```

## Releasing

To release a new version of this library, update the version in all locations, tag the version, and then push the tag up. Packagist.org takes care of the rest.

1. Confirm tests pass
2. Bump the version in composer.json, lib/Client.php, lib/SendGrid.php, test/unit/SendGridTest.php
3. Update CHANGELOG.md
4. Confirm tests pass
5. Commit Version bump vX.X.X
6. Push changes to GitHub
7. Release tag on GitHub vX.X.X
8. Packagist.org takes care of the rest

#### Testing uploading to Amazon S3

If you want to test uploading the zipped file to Amazon S3 (SendGrid employees only), do the following.

```
export S3_SIGNATURE="secret_signature"
export S3_POLICY="secret_policy"
export S3_BUCKET="sendgrid-open-source"
export S3_ACCESS_KEY="secret_access_key"
./scripts/s3upload.sh
```
```

###  Health Score

24

—

LowBetter than 32% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity10

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity51

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

2

Last Release

2168d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/048cc111efe46337adbff471833e938d0bdc43900ac8330acb039bdfc1a2130a?d=identicon)[awanesia](/maintainers/awanesia)

---

Top Contributors

[![Loetfi](https://avatars.githubusercontent.com/u/19318186?v=4)](https://github.com/Loetfi "Loetfi (6 commits)")

---

Tags

emailsendgridsendgrid 4.0.4

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/awanesia-sendgrid-404/health.svg)

```
[![Health](https://phpackages.com/badges/awanesia-sendgrid-404/health.svg)](https://phpackages.com/packages/awanesia-sendgrid-404)
```

###  Alternatives

[sendgrid/sendgrid

This library allows you to quickly and easily send emails through Twilio SendGrid using PHP.

1.5k47.5M164](/packages/sendgrid-sendgrid)[egulias/email-validator

A library for validating emails against several RFCs

11.6k691.3M307](/packages/egulias-email-validator)[sendgrid/smtpapi

Build SendGrid X-SMTPAPI headers in PHP.

696.5M2](/packages/sendgrid-smtpapi)[pelago/emogrifier

Converts CSS styles into inline style attributes in your HTML code

94944.1M110](/packages/pelago-emogrifier)[zbateson/mail-mime-parser

MIME email message parser

53949.2M79](/packages/zbateson-mail-mime-parser)[fastglass/sendgrid

This library allows you to send emails through SendGrid using PHP and Guzzle 6.x.

213.7M](/packages/fastglass-sendgrid)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
