Giter Site home page Giter Site logo

sendgrid / sendgrid-php Goto Github PK

View Code? Open in Web Editor NEW
1.5K 255.0 623.0 4.15 MB

The Official Twilio SendGrid PHP API Library

Home Page: https://sendgrid.com

License: MIT License

PHP 99.67% Shell 0.06% Dockerfile 0.07% Makefile 0.20%
php sendgrid email transactional-emails

sendgrid-php's Introduction

SendGrid Logo

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

NEW:

  • 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.

If you need support using SendGrid, please check the Twilio SendGrid Support Help Center.

Please browse the rest of this README for further details.

We appreciate your continued support, thank you!

Table of Contents

Installation

Prerequisites

  • PHP version 7.3, 7.4, 8.0, or 8.1
  • 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:

<?php
// 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 <PATH TO> with the path to the sendgrid-php.php file
// require_once '<PATH TO>/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:

$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", "<strong>and easy to do anywhere, even with PHP</strong>"
);
$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)

$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)

$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.

Support

For product support, please check the Twilio SendGrid Support Help Center.

License

The MIT License (MIT)

sendgrid-php's People

Contributors

bertuss avatar caseyw avatar cjbuchmann avatar crweiner avatar davcpas1234 avatar dereckson avatar eddiezane avatar edwardrbaker avatar eshanholtz avatar geryjuhasz avatar hjmsw avatar iampoul avatar jennifermah avatar kampalex avatar kander-zz avatar lucasmezencio avatar motdotla avatar myzeprog avatar ninsuo avatar nquinlan avatar owenvoke avatar pangaunn avatar reisraff avatar semijoelon avatar ssiddhantsharma avatar theycallmeswift avatar thinkingserious avatar tiwarishubham635 avatar twilio-ci avatar twilio-dx avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sendgrid-php's Issues

Confusing error message with bad credentials

I changed my SendGrid password yesterday for an unrelated reason and when one of my crons ran this morning, I received the error message below. While it mentions the authenticator, it doesn't give any indication of what the actual error was.

(Paths removed but otherwise message untouched.)

Fatal error: Uncaught exception 'Swift_TransportException' with message 'Expected response code 250 but got code "", with message ""' in /[path]/vendor/sendgrid-php/lib/swift/classes/Swift/Transport/AbstractSmtpTransport.php:422
Stack trace:
#0 /[path]/vendor/sendgrid-php/lib/swift/classes/Swift/Transport/AbstractSmtpTransport.php(306): Swift_Transport_AbstractSmtpTransport->_assertResponseCode('', Array)
#1 /[path]/vendor/sendgrid-php/lib/swift/classes/Swift/Transport/EsmtpTransport.php(224): Swift_Transport_AbstractSmtpTransport->executeCommand('RSET??', Array, Array)
#2 /[path]/vendor/sendgrid-php/lib/swift/classes/Swift/Transport/Esmtp/Auth/LoginAuthenticator.php(50): Swift_Transport_EsmtpTransport->executeCommand('RSET??', Array)
#3 /[path]/vendor/sendgrid-php/lib/swift/classes/Swift/Transport/Esmtp/AuthHandler.php(170): Swift_Transport_Esmtp_Auth_LoginAuthenticator->authenticate in /[path]/vendor/sendgrid-php/lib/swift/classes/Swift/Transport/AbstractSmtpTransport.php on line 422

submodule issues on clone

When I cloned sendgrid-php into an existing repo
eg;

myrepo/scripts/

where the existing .git was at myrepo/.git, it cloned fine. However, when I tried to git add the sendgrid-php files into my repo it wouldn't add. Then when I tried to force it, git complained about a submodule for composer.json.

I was requested by Swift to post this bug but I'll try and replicate it (I used a workaround) and post the error messages in more detail

Needs better documentation on dependencies

Apparently, if you aren't using Composer, you are in a boatload of trouble. The documentation does not mention the still needed dependencies of Unirest and something else I can't get working called the SMTPAPI.

In line 23 of Sendgrid\Email, the program is looking \Smtpapi\Header.

Thing is, I do not want to use SMTP. I want to use the WEB API.

Can't set character set

AFAIK SendGrid defaults to using UTF-8, but would be nice to be able to specify a character set.

Request: API 3.0 support

Support for API 3.0 in this SDK would be much appreciated. Template Engine is the biggest factor for me, personally, but obviously all the new functionality coming into 3.0 would be a nice-to-have.

Thanks!

Add example for adding the SMTP API header

There is no example of adding the SMTP API header. @scottkawai found that whenever he used the addHeader method it seems like it was ignored.

The only way he got it working was:

$json = array (
        "to" => array (
            "New Person 1 <[email protected]>"
        )
    );
    $mail->setRecipientsInHeader(false);
    $mail->
        setHeaders($json);

Inbound Emails

Hi,

Does this library support parsing inbound emails? I could not find any examples or any note on this.

Unirest contans bugs

File: Unirest.php
#1) code

private static function getHeader($key, $val) {
$key = trim(strtolower($key));
if ($key == "user-agent" || $key == "expect") continue;
return $key . ": " . $val;
}

--> continue-statement to break an if-clause ????
#2) type hints

What is the stdObj-type ?????
Do you mean stdClass ?

to be found, e.g. here:

  • @return string|stdObj response string or stdObj if response is json-decodable
    */
    public static function patch($url, $headers = array(), $body = NULL, $username = NULL, $password = NULL)
    {
    return Unirest::request(HttpMethod::PATCH, $url, $body, $headers, $username, $password);
    }

Recommendations

I suppose there are better implementations of lightweight rest-clients to be found an github,e.g: https://github.com/guzzle/guzzle seems to be quite popular and is being maintained.

Question about sending bulk message

Hello

I have more than 30,000 emails I would like to send email to them, I will be using the below code to send the email:

    $sendgrid = new SendGrid('user', 'password');
    foreach ($emails as $email){
        $mail = new SendGrid\Mail();
        $mail->setFrom(EMAIL_FROM)->setFromName(EMAIL_NAME);
                $mail->addCategory('Test');
        $mail->setSubject('Subject')->
            setText(str_replace('%name%',$email['name'],$text))->
            setHtml(str_replace('%name%',$email['name'],$html));
        $mail->addTo($email['email'],$email['name']);
        $sendgrid->smtp->send($mail);
        unset($mail);
    }

What do you think about the code above?
Will this code open SMTP connection for every email SMTP request? or it will use one SMTP connection?
Will sendgrid-php handle all sendgrid limits (such as sending 100 email per SMTP connection)?

Fatal error on unit test?

When running test I'm getting Fatal error: Class 'Smtpapi\Header' not found in sendgrid-php/lib/SendGrid/Email.php on line 23. Anyone else getting this?

Steps:

composer update --dev
cd test
phpunit

Error: Missing destination email

Hi,
I've upgrated to the latest zip version of sendgrid, and I'm facing an issue saying the "to" field is empty, while instead it's is obviously not from the code.

Here is my code:

$mail = new SendGrid\Email();
$mail->
 addTo("[email protected]")->
 setFrom(array('[email protected]' => 'my email sender name');)->
 setSubject($emailsubject)->
 setHtml($emailcontent);

where $emailsubject and $emailcontent are set before this piece of code.
This is the var_dump before sending the email from the $mail object:

object(SendGrid\Email)#9 (12) {
  ["to"]=>
  NULL
  ["from"]=>
  array(1) {
    ["[email protected]"]=>
    string(19) "my email sender name"
  }
  ["from_name"]=>
  bool(false) 

........
(after the HTML content if the email...)
........

 ["smtpapi"]=>
  object(Smtpapi\Header)#10 (6) {
    ["to"]=>
    array(1) {
      [0]=>
      string(21) "[email protected]" 

So the "to" field" is set only In a sub-object, I don't know if this can be useful to you.

This is the $result of the request $sendgrid->send($mail); :

object(stdClass)#12 (2) {
  ["message"]=>
  string(5) "error"
  ["errors"]=>
  array(1) {
    [0]=>
    string(25) "Missing destination email"
  }
}

Going crazy with this, check you check if there is any issue?
Thanks

Bad credentials

Hello,

I've been using sendgrid and sent thousands of mails successfully with no issues up until now. I've pasted the message as-is from the error-log...

[Thu Jan 16 10:42:04.493110 2014] [:error] [pid 24983] [client 14.98.237.254:1725] PHP Fatal error:  Uncaught exception 'SendGrid\\AuthException' with message 'Bad username / password' in .../sendgrid-php/SendGrid/Smtp.php:170

Stack trace:
#0 /var/www/walk/classes/SendGridMailer.php(88): SendGrid\\Smtp->send(Object(SendGrid\\Mail))
#1 /var/www/walk/classes/UserManager.php(361): SendGridMailer->sendMail()
#2 /var/www/walk/classes/UserManager.php(280): UserManager->sendActivationEmail()
#3 /var/www/walk/model/model.signup.php(73): UserManager->createThisUser()
#4 /var/www/walk/pages/signup.php(4): include_once('/var/www/walk/m...')\n
#5 {main}\n  thrown in /var/www/walk/static-resources/class-includes/sendgrid-php/SendGrid/Smtp.php on line 170

There were no changes in the username/ password configurations and this error is inexplicable.

Actions taken:

  • I've searched for the reasons and I stumbled across this issue #12. It was of no help.
  • For some reason, I felt it was a cache error. So, I refreshed the apache server and things worked perfectly afterwards.

I believe that this error occurs because of corrupted/ overwritten cache (perhaps for the SMTP configuration).

Even though this error is a very rare, I would like to fix it.

Thanks,
dbx834

addTo($address) doesn't appear to set SendGrid\Email::$to

$to = "[email protected]";
$sendgrid = new SendGrid($sendgrid_username, $sendgrid_password, array("turn_off_ssl_verification" => true));
$email    = new SendGrid\Email();
$email->addTo($to)->
           setFrom($to)->
           setSubject('[sendgrid-php-example] Owl')->
           setText('Owl are you doing?')->
           setHtml('<strong>%how% are you doing?</strong>')->
           addSubstitution("%how%", array("Owl"))->
           addHeader('X-Sent-Using', 'SendGrid-API')->
           addHeader('X-Transport', 'web');
           //addAttachment('./gif.gif', 'owl.gif');

$response = $sendgrid->send($email);
var_dump($email);
var_dump($response); 

Output:
object(SendGrid\Email)#127 (12) { ["to"]=> NULL ["from"]=> string(11) "[email protected]" ["from_name"]=> bool(false) ["reply_to"]=> bool(false) ["cc_list"]=> NULL ["bcc_list"]=> NULL ["subject"]=> string(26) "[sendgrid-php-example] Owl" ["text"]=> string(18) "Owl are you doing?" ["html"]=> string(37) "%how% are you doing?" ["headers"]=> array(2) { ["X-Sent-Using"]=> string(12) "SendGrid-API" ["X-Transport"]=> string(3) "web" } ["smtpapi"]=> object(Smtpapi\Header)#131 (6) { ["to"]=> array(1) { [0]=> string(11) "[email protected]" } ["sub"]=> array(1) { ["%how%"]=> array(1) { [0]=> string(3) "Owl" } } ["unique_args"]=> array(0) { } ["category"]=> array(0) { } ["section"]=> array(0) { } ["filters"]=> array(0) { } } ["attachments"]=> NULL }
....
object(stdClass)#133 (2) { ["message"]=> string(5) "error" ["errors"]=> array(1) { [0]=> string(25) "Missing destination email" } }
....

Add Header does an append of Content-Transfer-Encoding, instead of Replace

While investigating this StackOverflow Post, I attempted to pass the Content-Transfer-Encoding header using both the CURL code provided on the docs website and the PHP Library in Github. These are the results.

What I found is that the header is added to the email, but does not replace the header that is created on ?the api server? by default. So, I'm not sure it is actually making the change or if it's in conflict and email programs are handling the header in their own way.

Code:


    $sendgrid = new SendGrid('user', 'pass');

    $mail = new SendGrid\Email();
    $mail ->addTo("[email protected]");
    $mail ->setFrom("[email protected]");
    $mail ->setSubject("TEST");

    $mail->addHeader('Content-Transfer-Encoding', '8bit');
    $mail->setHtml("&lt;h1&gt;Example&lt;/h1&gt;");

This will add the header that you're looking for, in addition to the default headers that are put into the email. The email headers end up like this via the PHP SendGrid-php/lib/SendGrid/Email.php

    dkim=pass [email protected]
    DKIM-Signature: v=1; a=rsa-sha1; c=relaxed; d=sendgrid.info; 
        h=content-type:mime-version:content-transfer-encoding:from:to:subject:content-transfer-encoding:x-feedback-id; 
        s=smtpapi; bh=1WW/c1AerBKZJHTBHMMd/W0PYo4=; b=HdEvkFqvTlGC4zeHIO
        D0bqZVg681r/CiS4tSoOhervfsgmWBdq5CEjsuyV10ZDIzE254RF5kLjPAlbdWE0
        7cuHga78uRoRrFO24x8aPeTnvoiB4lE6/0P7+3hiDQfqjlXEqL141bGdTwponBj1
        KD9n5YQaMoGLQryLSKDRKKsqM=
    Received: by filter-245.sjc1.sendgrid.net with SMTP id filter-245.20601.53B60E8B5
            2014-07-04 02:16:43.858111682 +0000 UTC
    Received: from MTM1ODk2OA (c-76-25-76-145.hsd1.co.comcast.net [76.25.76.145])
        by ismtpd-022.sjc1.sendgrid.net (SG) with HTTP id 146ff28d24f.1b27c.3cc5bd
        for <[email protected]>; Fri, 04 Jul 2014 02:16:43 +0000 (GMT)
    Content-Type: text/html; charset="utf-8"
    MIME-Version: 1.0
    Content-Transfer-Encoding: quoted-printable
    From: [email protected]
    To: [email protected]
    Subject: TEST
    Content-Transfer-Encoding: 8bit
    Message-ID: <[email protected]>
    Date: Fri, 04 Jul 2014 02:16:43 +0000 (UTC)
    X-SG-EID: Jzfy2lROYsig6oSHT1/xT2qkp+Z52+DmR5cWxSvPIJTONlldhWZ1A3c1UqOiYZNpz8+RxVxWMkNbcEiQjgKur9guPskKIGLfG+pTvCV/9q5ZDUPDVlteX2CsILx/Z41cqfIZdEE2k1bfeGx7QEevKpOnXAzRlsabxkputxYUJl0=
    X-Feedback-ID: 1358968:3E1XnPfeS0bo4KiasVIXA4c3P8p6prb7aL2N5peSNss=:3E1XnPfeS0bo4KiasVIXA4c3P8p6prb7aL2N5peSNss=:SG

If you attempt to use the api via the Curl example:

    Content-Transfer-Encoding: 8bit
    Message-ID: <[email protected]>
    Date: Fri, 04 Jul 2014 02:15:52 +0000 (UTC)
    X-SG-EID: Jzfy2lROYsig6oSHT1/xT2qkp+Z52+DmR5cWxSvPIJQkgKsJ+gbZx2X1LioJwmZs6GPhvJnqDdYjcZP0Czn+XvBTla3kN6Cm4x7F7Cnza+ln6P1nLdQ6vcivLxWFqNu6+Hpntx8Kb+WuVg1q6zKVQUbPDpuHB+eeX3C6W0nRsYE=
    X-Feedback-ID: 1358968:3E1XnPfeS0bo4KiasVIXA4c3P8p6prb7aL2N5peSNss=:3E1XnPfeS0bo4KiasVIXA4c3P8p6prb7aL2N5peSNss=:SG

    --===============5244786670933987949==
    Content-Type: text/plain; charset="utf-8"

    MIME-Version: 1.0
    Content-Transfer-Encoding: quoted-printable

    testing body=

    --===============5244786670933987949==
    Content-Type: text/html; charset="utf-8"
    MIME-Version: 1.0
    Content-Transfer-Encoding: quoted-printable

addTo() and addBcc() not working correctly when using addAttachment()

Hey there,

I've been trying to use the addTo() and addBcc() functions together with adding an attachment - > addAttachment("./file.php"), but I can't seem to get it to work.

Basically when I use

addTo('[email protected]')->
setBcc('[email protected]')->

in the mail object - it works perfect and the emails get delivered.

However, when I add the addAttachment("./file.php") function in the same object - the email goes out to only the addTo() address.

Thanks,
Andrei

sendgrid-php.php missing

sendgrid-php.php as stated to use the docs is missing in recent releases, also no vendor/autoload

Undefined variable $failures in Smtp.php:141

See title

  /* send
   * Send the Mail Message
   * @param Mail $mail - the SendGridMailMessage to be sent
   * @return true if mail was sendable (not necessarily sent)
   */
  public function send(Mail $mail)
  {
    $swift = $this->_getSwiftInstance($this->port);

    $message = $this->_mapToSwift($mail);

    $swift->send($message, $failures);

    return true;
  }

Bug fix for addTo() recipients with commas in their name

sendgrid/vendor/sendgrid/smtpapi/lib/Smtpapi/Header.php

If there is a comma in the value of $name, addTo() will not escape or quote it, leading to a faulty To: header.

I recommend changing line 16 to:

$this->to[] = ($name ? '"' . preg_replace('{"}', '&quot;', $name) . '" ' : $email);

Update Integration Docs for New Library

where is autoloader?
Please provide updated documentation. Had to go with Ccurl because it works and I don't have hours of time to figure out this new setup.

Checking cURL Error in Web API

Ran into this issue from an incorrectly configured SSL cert on my server. cURL was returning false, but the curl session is lost to run curl_error on. curl_error($curl_session) should be returned when the response comes back false from curl, instead of just nondescript false.

I can make this change if deemed necessary.

CC and BCC not working

CC and BCC fields aren't working. BCC is required for integration with a 3rd party service, so multiple TO fields aren't an option for me.

Test case:

mkdir sgtest && cd sgtest
composer init -s dev
composer require sendgrid/sendgrid 2.0.3
echo "<?php return ['username'=>'', 'password'=>'']; ?>" > cfg.php
# Add your username and password to cfg.php
curl https://gist.githubusercontent.com/lexicalbits/9669433/raw/61ee6a296734d4aaad708fdd7a482780e886e60a/gistfile1.php > run.php
php run.php

If you use the default emails in the test, you can verify the results here:
http://mailinator.com/inbox.jsp?to=sgtest_to
http://mailinator.com/inbox.jsp?to=sgtest_cc
http://mailinator.com/inbox.jsp?to=sgtest_bcc

The test gist: https://gist.github.com/lexicalbits/9669433

My setup:
Ubuntu Server 12.04 in KVM
PHP from https://launchpad.net/~ondrej/+archive/php5

php -v
PHP 5.5.4-1+debphp.org~precise+1 (cli) (built: Sep 27 2013 12:39:52) 
Copyright (c) 1997-2013 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2013 Zend Technologies
    with Zend OPcache v7.0.3-dev, Copyright (c) 1999-2013, by Zend Technologies
    with Xdebug v2.2.3, Copyright (c) 2002-2013, by Derick Rethans

unknown constant "__dir__"

File: lib/SendGrid.php

Do you mean DIR, but accidentially used "dir" ?

public function __get($api) {
$name = $api;

if($this->$name != null) {
  return $this->$name;
}

$api = $this->namespace . "\\" . ucwords($api);
$class_name = str_replace('\\', '/', "$api.php");
$file = __dir__ . DIRECTORY_SEPARATOR . $class_name;

if (!file_exists($file)) {
  throw new Exception("Api '$class_name' not found.");
}
require_once $file;

$this->$name = new $api($this->username, $this->password);
return $this->$name;

}
}

Recommendations

I'll suggest using a proper ide with full php code inspection features, e.g.: phpstorm. Everything that the ide displays in a "strange" color, can be fixed to prevent bugs at runtime.

Subject extra-spaces

Hi guys,
This might sound a little ridiculous so please bear with me for a moment.
A customer of ours reported that when using a non-ASCII character in the Subject of the email, extra-spaces are being added both in the front and at the back of the word containing that character (this happens only in Thunderbird and Outlook).
For example: "Kvitto för din betalning" will appear as "Kvitto för din betalning" in Thunderbird and Outlook.
The weird part is that this only happens when the addSubstitution() method is used, even though it does not have any visible connection with the setSubject() method.
So, when commenting out or removing addSubstitution(), the extra-spaces never appear.
I'm not sure what might cause this odd behavior. Any thoughts on it?

Gmail stripping the content from within parentheses

Hey Swift, me again :)

It looks like if you have your "From" name set to something like:

setFromName('Something whatever (DEV)');

Gmail strips the (DEV) part entirely, and only displays the 'From name' as 'Something whatever'.

I've tested sending with the same "From name" using other Libraries and Email Clients, through SendGrid, and they all seem to display it correctly.

Let me know if you need more details.

Thanks!
Andrei

issue with lib/SendGrid/Email.php and unirest "Array to string conversion"

'Array to string conversion' notice from line 134 of Unirest.php due to the body of the request being supplied a nested array for the POST array $body:

curl_setopt ($ch, CURLOPT_POSTFIELDS, $body); // line 134 Unirest.php

The Email::toWebFormat() creates the POST payload, and fails to join $web['to'] and $web['bcc'] to a csv string. The email does not get sent.

Add this around line 448 in lib/SendGrid/Email.php

// fix for Array to string conversion in Unirest
$web['to'] = implode(",",$web['to']);
if ($this->getBccs()) $web['bcc'] = implode(",",$web['bcc']);

update Wiki to mention try, catch

Might want to consider updating the following section of the Wiki to mention the use of try, catch to catch swiftmailer errors us newbies:

"Send it using the API of your choice

try

   {
    $sendgrid->smtp->send($mail);
   }

catch (Exception $e)
    {
   //add error handling as appropriate (e.g., post the error to a log file), or just print the error
    print('error:' . $e->getMessage());
    }

"

See also:

http://stackoverflow.com/questions/1245201/fatal-error-uncaught-exception-using-php-swiftmailer

Great work by the way!

addUniqueArg

De library used $this->smtpapi->addUniqueArgs($key, $value);
instead of
$this->smtpapi->addUniqueArg($key, $value)

SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

When we try to run the following command on our local Apache 2.2 server, we get the following error message:

$sendgrid->web->send($mail);

Fatal error: Uncaught exception 'Exception' with message 'SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed' in C:\Apache2.2\htdocs\mysite\site\CRONTAB\libraries\Unirest\Unirest\Unirest.php:166 Stack trace: #0 C:\Apache2.2\htdocs\mysite\site\CRONTAB\libraries\Unirest\Unirest\Unirest.php(61): Unirest::request('POST', 'https://api.sen...';, Array, Array, NULL, NULL) #1

sendgridConnect::TIMEOUT is too short

The default 20-second timeout is too short for some operations to complete, such as newsletter_get_list_emails() on a list with > 15k addresses.

I'd suggest lengthening the timeout, or making it configurable on a per-request basis.

Your requirements could not be resolved to an installable set of packages.

https://github.com/sendgrid/sendgrid-php/blob/v1.1.4/composer.json
line 8-11
mashape/unirest-php needs to be an uppercase M
since composer is seeing everything strict now
as mentioned in this github issue of composer: composer/composer#2690

This is the error our users are receiving when attempting to install SendGrid PHP with the new version of composer : Your requirements could not be resolved to an installable set of packages.

Web api issue

Hi.

I may have found a problem with the web api.

When I send with "$sendgrid->smtp->send($mail);" everything is fine. However, when I send by the web api "$sendgrid->web->send($mail);", I get the following error:

Fatal error: Call to undefined function SendGrid\curl_init() in C:\MY_FILES\sendgrid\SendGrid\Web.php on line 127
Call Stack

Time Memory Function Location

1 0.0013 382136 {main}( ) ..\tailored_email_test.php:0
2 0.0442 585048 SendGrid\Web->send( ) ..\tailored_email_test.php:86

SMTP API *sometimes* generating invalid SMTP API headers

The Sendgrid PHP SMTP API will sometimes generate SMTP API headers that get rejected by SendGrid.

The headers include unique arguments, substitutions, and email addresses added with the addTo() function.

Using the same data set, sometimes the API will generate headers that SendGrid accepts, and sometimes not.

I have the PHP and SMTP API JSON headers, along with my PHP code. Please email me for them as they contain sensitive information. [email protected]

Display name

I've been trying to add a display name, and it looks like this is not included in the source code. I'm not sure if there is a good workaround or not, but if not, this would be a key feature.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.