Skip to content

Commit

Permalink
Merge pull request #3 from byng-systems/upgrade-to-sendgrid-5
Browse files Browse the repository at this point in the history
Upgrade sendgrid/sendgrid to 5, remove Unirest, update base code
  • Loading branch information
seeruk authored Jan 11, 2017
2 parents 557f833 + 94f31ac commit 019e647
Show file tree
Hide file tree
Showing 6 changed files with 167 additions and 101 deletions.
1 change: 0 additions & 1 deletion DependencyInjection/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ public function getConfigTreeBuilder()
$rootNode
->addDefaultsIfNotSet()
->children()
->scalarNode('api_user')->isRequired()->cannotBeEmpty()->end()
->scalarNode('api_key')->isRequired()->cannotBeEmpty()->end()
->scalarNode('logging')->defaultValue('%kernel.debug%')->end()
->end();
Expand Down
4 changes: 2 additions & 2 deletions DependencyInjection/SavchSendgridExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ public function load(array $configs, ContainerBuilder $container)

$configuration = new Configuration();
$config = $processor->processConfiguration($configuration, $configs);
foreach (array('api_key', 'api_user', 'logging') as $attribute) {

foreach (array('api_key', 'logging') as $attribute) {
$container->setParameter('savch_sendgrid.'.$attribute, $config[$attribute]);
}
}
Expand Down
10 changes: 3 additions & 7 deletions Resources/config/services.yml
Original file line number Diff line number Diff line change
@@ -1,16 +1,12 @@
services:
SendGrid.SendGridService:
sendgrid.sendgridservice:
class: SendGrid
arguments:
username: "%savch_sendgrid.api_user%"
password: "%savch_sendgrid.api_key%"

SendGrid.SendGridMailerService:
sendgrid.sendgridmailerservice:
class: Savch\SendgridBundle\Service\SendGridTemplatingMailerService
arguments:
sendGrid: "@SendGrid.SendGridService"
sendGrid: "@sendgrid.sendgridservice"
templating: "@templating"
throwExceptionsOnFail: true
credentials:
username: "%savch_sendgrid.api_user%"
password: "%savch_sendgrid.api_key%"
113 changes: 71 additions & 42 deletions Service/SendGridTemplatingMailerService.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,12 @@
namespace Savch\SendgridBundle\Service;

use SendGrid;
use SendGrid\Attachment;
use SendGrid\Content;
use SendGrid\Email;
use StdClass;
use SendGrid\Mail;
use SendGrid\Personalization;
use SendGrid\Response;
use Savch\SendgridBundle\Exception\MailNotSentException;
use Savch\SendgridBundle\Model\TemplatedEmailBody;
use Symfony\Bundle\TwigBundle\TwigEngine;
Expand Down Expand Up @@ -47,23 +51,16 @@ class SendGridTemplatingMailerService
*/
protected $throwExceptionsOnFail;

/**
* @var array
*/
private $credentials;

/**
*
* @param SendGrid $sendGrid
* @param TwigEngine $templating
* @param boolean $throwExceptionsOnFail
* @param array $credentials
*/
public function __construct(SendGrid $sendGrid, TwigEngine $templating, $throwExceptionsOnFail = true, $credentials = array())
public function __construct(SendGrid $sendGrid, TwigEngine $templating, $throwExceptionsOnFail = true)
{
$this->sendGrid = $sendGrid;
$this->templating = $templating;
$this->credentials = $credentials;

$this->setThrowExceptionsOnFail($throwExceptionsOnFail);
}
Expand All @@ -78,8 +75,7 @@ public function getTemplating()
}

/**
*
* @return type
* @return SendGrid
*/
protected function getSendGrid()
{
Expand All @@ -106,7 +102,7 @@ public function setThrowExceptionsOnFail($throwExceptionsOnFail)

public function sendHtmlEmail(array $from, array $to, $subject, $bodyHtml, array $additionalHeaders = array(), array $attachments = null)
{
//
// Build base email
$email = static::buildBaseEmail($from, $to, $subject, $additionalHeaders, $attachments);

// If the given body is a TemplatedEmailBody object, populate and reassign the string value to itself
Expand All @@ -117,25 +113,34 @@ public function sendHtmlEmail(array $from, array $to, $subject, $bodyHtml, array
)->getContent();
}

$email->setHtml($bodyHtml);
$content = new Content("text/html", $bodyHtml);
$email->addContent($content);

return $this->processResponse($this->sendGrid->web->send($email));
return $this->processResponse($this->sendGrid->client->mail()->send()->post($email));
}

/**
* @param Response $response
*
* @param type $response
*
* @return boolean
* @return bool
* @throws MailNotSentException
*/
protected function processResponse(StdClass $response, $throwExceptionOnFail = true) {
$result = (isset($response->message) && $response->message == "success");
protected function processResponse(Response $response) {
$result = (empty($response->body()) && ($response->statusCode() === 200 || $response->statusCode() === 202));

if ($result === false && $this->throwExceptionsOnFail === true) {

$body = json_decode($response->body(), true);

$hasErrors = !is_null($response->headers())
&& $response->body()
&& array_key_exists('errors', $body)
&& is_array($body['errors']);

throw new MailNotSentException(
(
isset($response->errors) && is_array($response->errors)
? implode(";", $response->errors)
$hasErrors
? implode("", $response->headers()) . implode(" ", $body['errors'][0])
: "No error information given"
)
);
Expand All @@ -144,40 +149,67 @@ protected function processResponse(StdClass $response, $throwExceptionOnFail = t
return $result;
}

/**
* @param array $from
* @param array $to
* @param $subject
* @param array $additionalHeaders
* @param array|null $attachments
*
* @return Mail
*/
protected static function buildBaseEmail(array $from, array $to, $subject, array $additionalHeaders = array(), array $attachments = null)
{
$email = new Email();

$fromAddress = current(array_keys($from));
$fromName = current($from);

$email->setFrom($fromAddress)
->setFromName($fromName)
->setSubject($subject);
$fromObj = new Email($fromName, $fromAddress);

$email = new Mail();
$email->setFrom($fromObj);
$email->setSubject($subject);

$personalization = new Personalization();

// Set to headers
foreach ($to as $toAddress => $toName) {
$email->addTo($toAddress, $toName);
$toObj = new Email($toName, $toAddress);
$personalization->addTo($toObj);
}

// Set CC header if a value is given
if (isset($additionalHeaders["cc"]) && is_array(($cc = $additionalHeaders["cc"]))) {
$email->setCcs($cc);
if (isset($additionalHeaders["cc"]) && is_array(($ccs = $additionalHeaders["cc"]))) {
foreach ($ccs as $ccAddress => $ccName) {
$ccObj = new Email($ccName, $ccAddress);
$personalization->addCc($ccObj);
}
}

// Set BCC header if a valud is given
if (isset($additionalHeaders["bcc"]) && is_array(($bcc = $additionalHeaders["bcc"]))) {
$email->setBccs($bcc);
if (isset($additionalHeaders["bcc"]) && is_array(($bccs = $additionalHeaders["bcc"]))) {
foreach ($bccs as $bccAddress => $bccName) {
$bccObj = new Email($bccName, $bccAddress);
$personalization->addBcc($bccObj);
}
}

if (isset($additionalHeaders["reply-to"])) {
$email->setReplyTo($additionalHeaders["reply-to"]);
}

if (isset($attachments)) {
$email->setAttachments($attachments);

foreach ($attachments as $attachmentPath) {
$attachment = new Attachment();
$attachment->setContent(base64_encode(file_get_contents($attachmentPath)));
$attachment->setFilename(basename($attachmentPath));
$attachment->setDisposition("attachment");
$email->addAttachment($attachment);
}
}

$email->addPersonalization($personalization);

return $email;
}

Expand All @@ -186,20 +218,17 @@ protected static function buildBaseEmail(array $from, array $to, $subject, array
*
* @param string $email
*
* @return \Unirest\HttpResponse
* @return SendGrid\Response
*/
public function unsubscribeEmail($email)
{
$url = "https://api.sendgrid.com/api/unsubscribes.add.json";

$form = array();
$form['api_user'] = $this->credentials['username'];
$form['api_key'] = $this->credentials['password'];
$form['email'] = $email;

$response = \Unirest::post($url, array(), $form);
$request = [
"recipient_emails" => [
$email
]
];

return $response;
return $this->sendGrid->client->asm()->suppressions()->global()->post($request);
}

}
3 changes: 1 addition & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,7 @@
"keywords": ["sendgrid", "mail", "email", "web service", "smtp"],
"require": {
"symfony/templating": ">=2.4.1",
"mashape/unirest-php": "dev-master",
"sendgrid/sendgrid": "~1.1.7"
"sendgrid/sendgrid": "~5.1"
},
"target-dir": "Savch/SendgridBundle",
"autoload": {
Expand Down
Loading

0 comments on commit 019e647

Please sign in to comment.