This library allows you to quickly and easily use the Twilio SendGrid Web API v3 via PHP

Overview

SendGrid Logo

BuildStatus Packagist Downloads MIT licensed Twitter Follow GitHub contributors Open Source Helpers

NEW:

The default branch name for this repository has been changed to main as of 07/27/2020.

  • Send SMS messages with Twilio.

This library allows you to quickly and easily use the Twilio SendGrid Web API v3 via PHP.

Version 7.X.X of this library provides full support for all Twilio SendGrid Web API v3 endpoints, including the new v3 /mail/send.

We want this library to be community driven and Twilio SendGrid led. Your help is needed to realize this goal. To help make sure we are building the right things in the right order, we ask that you create issues and pull requests or simply upvote or comment on existing issues or pull requests.

Please browse the rest of this README for further details.

We appreciate your continued support, thank you!

Table of Contents

Installation

Prerequisites

  • PHP version 5.6, 7.0, 7.1, 7.2, 7.3, or 7.4
  • The Twilio SendGrid service, starting at the free level to send up to 40,000 emails for the first 30 days, then send 100 emails/day free forever or check out our pricing.
  • For SMS messages, you will need a free Twilio account.

Setup Environment Variables

Update the development environment with your SENDGRID_API_KEY, for example:

  1. Copy the sample env file to a new file named .env
cp .env.sample .env
  1. Edit the .env file to include your SENDGRID_API_KEY
  2. Source the .env file
source ./.env

Install Package

Add Twilio SendGrid to your composer.json file. If you are not using Composer, we highly recommend it. It's an excellent way to manage dependencies in your PHP application.

{
  "require": {
    "sendgrid/sendgrid": "~7"
  }
}

Alternative: Install package 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 ⬇︎

Previous versions of the library can be downloaded directly from GitHub.

Dependencies

Quick Start

Include the proper lines from below at the top of each example based on your installation method:


// Uncomment the next line if you're using a dependency loader (such as Composer) (recommended)
// require 'vendor/autoload.php';

// Uncomment the next line if you're not using a dependency loader (such as Composer), replacing 
    
      with the path to the sendgrid-php.php file
    
// require_once '
    
     /sendgrid-php.php';
    

Hello Email

The following is the minimum needed code to send an email. You may find more examples in our USE_CASES file:

setSubject("Sending with Twilio SendGrid is Fun"); $email->addTo("[email protected]", "Example User"); $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')); try { $response = $sendgrid->send($email); print $response->statusCode() . "\n"; print_r($response->headers()); print $response->body() . "\n"; } catch (Exception $e) { echo 'Caught exception: '. $e->getMessage() ."\n"; }">
$email = new \SendGrid\Mail\Mail();
$email->setFrom("[email protected]", "Example User");
$email->setSubject("Sending with Twilio SendGrid is Fun");
$email->addTo("[email protected]", "Example User");
$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'));
try {
    $response = $sendgrid->send($email);
    print $response->statusCode() . "\n";
    print_r($response->headers());
    print $response->body() . "\n";
} catch (Exception $e) {
    echo 'Caught exception: '. $e->getMessage() ."\n";
}

The SendGrid\Mail constructor creates a personalization object for you. Here is an example of how to add to it.

General v3 Web API Usage (With Fluent Interface)

headers()); print $response->body() . "\n"; } catch (Exception $e) { echo 'Caught exception: '. $e->getMessage(). "\n"; }">
$apiKey = getenv('SENDGRID_API_KEY');
$sg = new \SendGrid($apiKey);

try {
    $response = $sg->client->suppression()->bounces()->get();
    print $response->statusCode() . "\n";
    print_r($response->headers());
    print $response->body() . "\n";
} catch (Exception $e) {
    echo 'Caught exception: '.  $e->getMessage(). "\n";
}

General v3 Web API Usage (Without Fluent Interface)

get(); print $response->statusCode() . "\n"; print_r($response->headers()); print $response->body() . "\n"; } catch (Exception $e) { echo 'Caught exception: '. $e->getMessage(). "\n"; }">
$apiKey = getenv('SENDGRID_API_KEY');
$sg = new \SendGrid($apiKey);

try {
    $response = $sg->client->_("suppression/bounces")->get();
    print $response->statusCode() . "\n";
    print_r($response->headers());
    print $response->body() . "\n";
} catch (Exception $e) {
    echo 'Caught exception: '.  $e->getMessage(). "\n";
}

Use Cases

Examples of common API use cases, such as how to send an email with a transactional template.

Usage

Announcements

v7 has been released! Please see the release notes for details.

All updates to this library are documented in our CHANGELOG and releases.

How to Contribute

We encourage contribution to our libraries (you might even score some nifty swag), please see our CONTRIBUTING guide for details.

Quick links:

Troubleshooting

Please see our troubleshooting guide for common library issues.

About

sendgrid-php is maintained and funded by Twilio SendGrid, Inc. The names and logos for sendgrid-php are trademarks of Twilio SendGrid, Inc.

If you need help installing or using the library, please check the Twilio SendGrid Support Help Center.

If you've instead found a bug in the library or would like new features added, go ahead and open issues or pull requests against this repo!

License

The MIT License (MIT)

Comments
  • added support to extend curl options

    added support to extend curl options

    This PR add a curlOptions option to merge custom parameters to curl, and add the ability to set a proxy and/or a timeout.

    Should be merged after: https://github.com/sendgrid/php-http-client/pull/11

    type: community enhancement status: work in progress 
    opened by ninsuo 21
  • Refactor Code

    Refactor Code

    I believe that most of the functions I removed were redundant. Causing an overly complicated code. Not only for writing this API but for using it. Most people (probably all) will write PHP code connected to some sort of RDBMS. Which means they will pull back objects or an array. In this case I am using array as arrays are preferred in most API I have seen. There are a lot of "new Collection" functions that shouldn't exist. Also there was a lot of random syntax errors and things that don't make sense in regards to posting ("important-key", "important value) but then in the collection it was (["important key" => "important value"]) I think it was just overlooked. However I believe this is the best way to go. This reduces programming time to make the API as well as a friendly environment for integration.

    status: code review request difficulty: easy 
    opened by jopanel 16
  • Attachments now automatically get base64 encoded if they are not already

    Attachments now automatically get base64 encoded if they are not already

    Fixes

    Fixes #611

    Checklist

    • [x] I have made a material change to the repo (functionality, testing, spelling, grammar)
    • [x] I have read the [Contribution Guide] and my PR follows them.
    • [x] I updated my branch with the master branch.
    • [x] I have added tests that prove my fix is effective or that my feature works
    • [x] I have added necessary documentation about the functionality in the appropriate .md file
    • [x] I have added in line documentation to the code I modified

    Short description of what this PR does:

    • When an attachement is added it first checks whether or not it has already been base64 encoded, if not it encodes its.
    type: community enhancement status: code review request difficulty: medium 
    opened by martijnmelchers 12
  • New version of Sengrid-PHP for Guzzle 6.x support

    New version of Sengrid-PHP for Guzzle 6.x support

    I have been working on a fork of the SendGrid-PHP library to support Guzzle 6.x. This fork only supports PHP 5.5+ and eventually PHP 7.0 as testing with the RC's for PHP 7.0 has started. The decesion to do this was also for my support of the Drupal Sendgrid module. Drupal 8.0 includes Guzzle 6.x making integration really easy for the Drupal CMF for 8.x and beyond. It also supports Drupal 7.x by using the another contrib module that provides Composer.

    I made a grave mistake by commiting to master branch in my fork. I should have created a branch! But what is done is done. I updated all the classes and methods and have run Travis CI using my own account and the existing PHPUnit test adapted to exclude PHP 5.3 and 5.4.

    I would love for Sendgrid to consider this contribution as a new version of Sendgrid-PHP. This would allow you to continue support for PHP 5.3 by creating a new version of the Sendgrid library.

    This pull request isn't meant to be the final version. I know there are other changes that need to be made. This pull request could essentially be looked at as a request to make a new branch in SendGrid-PHP library - a 4.x.x branch.

    Lastly, along with the testing. I am using this on a production website via custom composer.json's: https://www.swingsurgeon.com

    Thoughts?

    opened by taz77 11
  • feat: enhanced type exception handling

    feat: enhanced type exception handling

    Closes #754 Closes https://github.com/sendgrid/sendgrid-php/issues/987

    Checklist

    • [x] I have made a material change to the repo (functionality, testing, spelling, grammar)
    • [x] I have read the [Contribution Guide] and my PR follows them.
    • [x] I updated my branch with the master branch.
    • [x] I have added tests that prove my fix is effective or that my feature works
    • [ ] I have added necessary documentation about the functionality in the appropriate .md file
    • [x] I have added in line documentation to the code I modified

    Short description of what this PR does:

    • New Assert class for strict type validation (100% code coverage with tests)
    • Refactoring using params type assertion
    status: code review request difficulty: hard type: twilio enhancement 
    opened by misantron 10
  • Allow for Dynamic Templates Implementation

    Allow for Dynamic Templates Implementation

    Fixes #648

    Checklist

    • [X] I have made a material change to the repo (functionality, testing, spelling, grammar)
    • [X] I have read the [Contribution Guide] and my PR follows them.
    • [X] I updated my branch with the master branch.
    • [X] I have added tests that prove my fix is effective or that my feature works
    • [ ] I have added necessary documentation about the functionality in the appropriate .md file
    • [X] I have added in line documentation to the code I modified

    Short description of what this PR does:

    • Adds dynamic template support by adding a new helper object, new methods into the mail and personalization classes.
    type: community enhancement status: work in progress difficulty: medium 
    opened by mwillbanks 10
  • Add ability to impersonate subuser

    Add ability to impersonate subuser

    Sendgrid API has a feature allowing parent accounts to impersonate subusers by including an HTTP header "On-Behalf-Of" in each API request. This commit enables setting the value for impersonation when creating the Sendgrid API Client instance, through the $options argument.

    Fixes #551

    status: code review request difficulty: medium type: twilio enhancement 
    opened by stianpr 9
  • PHPDoc & code improvements

    PHPDoc & code improvements

    Fixes

    Fixes #619

    Checklist

    • [x] I have made a material change to the repo (functionality, testing, spelling, grammar)
    • [x] I have read the [Contribution Guide] and my PR follows them.
    • [x] I updated my branch with the master branch.
    • [x] I have added tests that prove my fix is effective or that my feature works
    • [x] I have added necessary documentation about the functionality in the appropriate .md file
    • [x] I have added in line documentation to the code I modified

    Short description of what this PR does:

    • Improved PHPdoc warnings
    • Improve code style & self assignments
    type: community enhancement status: code review request difficulty: easy 
    opened by martijnmelchers 8
  • Added ability to provide Email address in new formats

    Added ability to provide Email address in new formats

    Closes #497

    Short description of what this PR does:

    • Added ability to provide Email address in new formats
    • It is now possible to provide Email addresses in the following formats: [email protected] example example < [email protected] >
    status: duplicate 
    opened by lribi 8
  • PSR1 and PSR2 Conversion

    PSR1 and PSR2 Conversion

    Reference issue #317.

    Tried to run tests on current master copy in addition to this PR version, kept getting errors referencing Class SendGrid and Class SendGrid\Client not found. I'm going to assume it's related to this #91

    type: community enhancement status: work in progress 
    opened by Braunson 8
  • feat: register autoload function if not using composer

    feat: register autoload function if not using composer

    fixes #638

    based on the documentation, the library should work without using composer, but doesn't. this PR registers an autoload function based on the directory structure of the library.

    status: wontfix 
    opened by EvaLok 7
  • fix: preserve substitutions from To in Personalization

    fix: preserve substitutions from To in Personalization

    If there are substitutions in the To object preserve them by transfering them to the Personalization object.

    Currently this does not work (we loose all substitutions from the To):

    $personalization0 = new Personalization();
    $personalization0->addTo(new To(
            "[email protected]",
            "Example User2",
            [
                '-name-' => 'Example User 2'   // <--this is lost and not sent to sendgrid API
            ],
            "Example User2 -name-"
    ));
    $email->addPersonalization($personalization0);
    

    We can either add the substitution during addTo method (as current PR is proposing) or parse all Tos during getSubstitutions method and add them to the substitution property. I propose the first way because it is similar to what we have in https://github.com/sendgrid/sendgrid-php/blob/main/lib/mail/Mail.php#L205

    We have to also think about implementations that worked around this issue (like myself) and not break them, so the following must still be working :

    $personalization0 = new Personalization();
    personalization->addSubstitution(new Substitution('-name-', 'Example User 1')); // <- we want this preserved even if added first
    $personalization0->addTo(new To(
            "[email protected]",
            "Example User2",
            [
                '-name-' => 'Example User 2' // <- we want this to not be applied in this case as addSubstitution takes precedence
            ],
            "Example User2 -name-"
    ));
    
    $email->addPersonalization($personalization0);
    

    OR we don't but we risk to break some implementations. Are there means of communicating the change in this case ?

    Checklist

    • [x] I acknowledge that all my contributions will be made under the project's license
    • [x] I have made a material change to the repo (functionality, testing, spelling, grammar)
    • [x] I have read the Contribution Guidelines and my PR follows them
    • [x] I have titled the PR appropriately
    • [x] I have updated my branch with the main branch
    • [x] I have added tests that prove my fix is effective or that my feature works
    • [x] I have added the necessary documentation about the functionality in the appropriate .md file N/A
    • [x] I have added inline documentation to the code I modified
    opened by toleabivol 0
  • docs: fix USE_CASES typo and params

    docs: fix USE_CASES typo and params

    fix Send Multiple Emails with Personalizations doc

    Checklist

    • [x] I acknowledge that all my contributions will be made under the project's license
    • [x] I have made a material change to the repo (functionality, testing, spelling, grammar)
    • [ ] I have read the Contribution Guidelines and my PR follows them
    • [x] I have titled the PR appropriately
    • [x] I have updated my branch with the main branch
    • [ ] I have added tests that prove my fix is effective or that my feature works
    • [ ] I have added the necessary documentation about the functionality in the appropriate .md file
    • [ ] I have added inline documentation to the code I modified

    If you have questions, please file a support ticket.

    opened by toleabivol 0
  • feat: add reply to list support

    feat: add reply to list support

    Fixes

    This PR add reply_to_list support to the library.

    Checklist

    • [x] I acknowledge that all my contributions will be made under the project's license
    • [x] I have made a material change to the repo (functionality, testing, spelling, grammar)
    • [x] I have read the Contribution Guidelines and my PR follows them
    • [x] I have titled the PR appropriately
    • [x] I have updated my branch with the main branch
    • [n/a] I have added tests that prove my fix is effective or that my feature works
    • [ n/a] I have added the necessary documentation about the functionality in the appropriate .md file
    • [x ] I have added inline documentation to the code I modified

    If you have questions, please file a support ticket.

    opened by MxFlorin 1
  • Changed Assert::email validation by egulias email RFCValidation

    Changed Assert::email validation by egulias email RFCValidation

    Changed Assert::email validation by eguilias email RFCValidation which is used in Laravel for example

    Fixes

    A short description of what this PR does.

    Checklist

    • [x] I acknowledge that all my contributions will be made under the project's license
    • [x] I have made a material change to the repo (functionality, testing, spelling, grammar)
    • [x] I have read the Contribution Guidelines and my PR follows them
    • [x] I have titled the PR appropriately
    • [x] I have updated my branch with the main branch
    • [x] I have added tests that prove my fix is effective or that my feature works
    • [x] I have added the necessary documentation about the functionality in the appropriate .md file
    • [x] I have added inline documentation to the code I modified

    If you have questions, please file a support ticket, or create a GitHub Issue in this repository.

    opened by jsolam 0
  • fix: Mitigate for duplicate email recipients

    fix: Mitigate for duplicate email recipients

    Ensure the uniqueness of email addresses when adding recipients in all emailTypes. Mitigation for error: "Each email address in the personalization block should be unique between to, cc, and bcc"

    opened by aingelc12ell 0
  • Api key

    Api key

    Fixes

    A short description of what this PR does.

    Checklist

    • [x] I acknowledge that all my contributions will be made under the project's license
    • [ ] I have made a material change to the repo (functionality, testing, spelling, grammar)
    • [ ] I have read the Contribution Guidelines and my PR follows them
    • [ ] I have titled the PR appropriately
    • [ ] I have updated my branch with the main branch
    • [ ] I have added tests that prove my fix is effective or that my feature works
    • [ ] I have added the necessary documentation about the functionality in the appropriate .md file
    • [ ] I have added inline documentation to the code I modified

    If you have questions, please file a support ticket, or create a GitHub Issue in this repository.

    status: code review request 
    opened by mmiermans 0
Releases(8.0.1)
Owner
Twilio SendGrid
Official open source libraries - send emails and integrate with our APIs fast.
Twilio SendGrid
SendGrid's PHP HTTP Client for calling APIs

Quickly and easily access any RESTful or RESTful-like API. If you are looking for the SendGrid API client library, please see this repo. Announcements

Twilio SendGrid 119 Nov 25, 2022
A library written in PHP to interact with Coinbase Pro via API.

A library written in PHP to interact with Coinbase Pro via API.

Blake Hamilton 4 Mar 31, 2022
This library is for integration with Salesforce via REST API.

xsolve-pl/salesforce-client Introduction This library is for integration with Salesforce via REST API. Licence This library is under the MIT license.

Boldare / XSolve Sp. z o.o. 31 Oct 13, 2022
🤖 Telegram Bot API PHP SDK. Lets you build Telegram Bots easily! Supports Laravel out of the box.

Telegram Bot API - PHP SDK Telegram Bot PHP SDK lets you develop Telegram Bots in PHP easily! Supports Laravel out of the box. Telegram Bot API is an

Irfaq Syed 2.5k Dec 6, 2022
⚡️ Web3 PHP is a supercharged PHP API client that allows you to interact with a generic Ethereum RPC.

Web3 PHP is a supercharged PHP API client that allows you to interact with a generic Ethereum RPC. This project is a work-in-progress. Code and docume

Web3 PHP 662 Dec 3, 2022
oursms.app client library that allows you to send SMS

Oursms laravel client https://oursms.app client library that allows you to send SMS Installation Install oursms client with composer composer requir

Khalid Mohammad 11 Aug 27, 2022
PHP package for the Limg.app website - allowing to upload images via the API of the website.

Limg PHP Client Package. Installation You can install the package via composer: composer require havenstd06/limg-php-client Usage use Havenstd06\Limg\

Thomas 3 Jul 27, 2021
HTTP Requestor: Package for a client request that supports you to make an external service request easily and with fast usage.

HttpRequestor from Patienceman HTTP Requestor: Package for a client request that supports you to make an external service request easily and with fast

Manirabona Patience 2 Aug 26, 2022
PHP library to use IOTA REST API to help node management and tangle queries

iota.php About PHP library to use IOTA REST API to help node management and tangle queries. Please be aware that this library is in an early developme

IOTA Community 44 Aug 17, 2022
Wise-php - This library is written to accommodate the wise API's use in php projects With Wise

Wise-php - This library is written to accommodate the wise API's use in php projects With Wise you can automate payments, connect your business tools, and create ways to manage your finances. You can also power your cross-border and domestic payouts.

Albert Xhani 15 Nov 17, 2022
Simple papara payment api that you can use without the need for an activation key

PaparaQrApi Papara QR Api Simple papara payment api that you can use without the need for an activation key. Explore the docs » View Demo About The Pr

Azad 5 Oct 23, 2022
PHP library with ready-to-use Yunbi API implementation.

yunbi-client-php A simple PHP client for Crypto Trade Site Yunbi.com Quick example <?php require_once('lib/yunbi-client.php'); try { $client = new

null 6 Dec 2, 2019
PHP JSON-RPC 2.0 Server/Client Implementation with Automatic Client Class Generation via SMD

PHP JSON-RPC 2.0 Server/Client Implementation with Automatic Client Class Generation via SMD

Sergey Bykov 63 Feb 14, 2022
ProcessTranslatePage – A Processwire module to translate all page fields via Fluency

ProcessTranslatePage – A Processwire module to translate all page fields via Fluency ProcessTranslatePage is an extension for the Processwire module F

Robert Weiss 5 Aug 29, 2022
A links dashboard which can be integrated via HTML into various other systems.

quickdash Newest QuickDash version. Combines the API and Client repositories. Requirements PHP version 7.4 - https://www.php.net/ Composer - https://g

Hugo Soares 0 Aug 11, 2022
Notifies via Telegram when an aircraft passes over a certain area.

adsbTelegramNotifier Notifies via Telegram when an aircraft passes over a certain area. The script gets the data from an existing readsb or dump1090 i

RundesBalli 4 Nov 24, 2022
PHP 5.3+ library which helps you to interact with the DigitalOcean API

DigitalOcean The version 2 of the API will be available soon ! Please visit DigitalOceanV2 and contribute :) This PHP 5.3+ library helps you to intera

Antoine Kirk 156 Jul 30, 2022
Laravel 8.x package wrapper library for Metatrader 5 Web API

Laravel 8.x package wrapper library for Metatrader 5 Web API

Ali A. Dhillon 10 Nov 13, 2022
A PHP package for handling client requests, sending response, database CRUD operations, among others, easily

Zam Zam helps to receive and process client request(s), return response to client with appropriate header and database CRUD operation for a more robus

SirMekus 3 Aug 26, 2022