Skip to content

Commit

Permalink
Fixes and tests
Browse files Browse the repository at this point in the history
  • Loading branch information
zanderwar committed Feb 1, 2018
1 parent ef7ba83 commit e503f63
Show file tree
Hide file tree
Showing 5 changed files with 129 additions and 15 deletions.
40 changes: 40 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
[![Build Status](https://travis-ci.org/vulcandigital/silverstripe-sendgrid.svg?branch=master)](https://travis-ci.org/vulcandigital/silverstripe-sendgrid)

## silverstripe-sendgrid
A module to assist developers in sending template emails via SendGrid

## Requirements
* silverstripe/framework: ^4.0

## Installation
```bash
composer require vulcandigital/silverstripe-sendgrid *
```

## Configuration
**mysite/_config/sendgrid.yml:**
```yml
Vulcan\SendGrid\SendGrid:
api_key: 'REPLACE-WITH-YOUR-API-KEY'
```
## Usage
```php
$sendGrid = \Vulcan\SendGrid\SendGrid::create();
$sendGrid->setSubject("We have a sale for your!");
$sendGrid->setFrom('[email protected]');
$sendGrid->setFromName('My Site');
$sendGrid->setReplyTo('[email protected]');
$sendGrid->addRecipient('[email protected]', 'Reece Alexander', [
':salutation' => 'Mr',
':button_link' => 'https://example.com/verify/aASdGdjnklashewjk12321hjkasd213'
]);
$sendGrid->setBody("<p>We thought you'd like this awesome t-shirt!</p>");
$sendGrid->setTemplateId('your-template-id');
$sendGrid->send();
```

You can add as many recipients as you want.

## License
[BSD-3-Clause](LICENSE.md) - [Vulcan Digital Ltd](https://vulcandigital.co.nz)
6 changes: 4 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,13 @@
"sendgrid/sendgrid": "~6.0"
},
"require-dev": {
"phpunit/PHPUnit": "^5.7"
"phpunit/PHPUnit": "^5.7",
"squizlabs/php_codesniffer": "3.*"
},
"autoload": {
"psr-4": {
"Vulcan\\SendGrid\\": "src/"
"Vulcan\\SendGrid\\": "src/",
"Vulcan\\SendGrid\\Tests\\": "tests/"
}
},
"minimum-stability": "dev"
Expand Down
4 changes: 3 additions & 1 deletion src/Exceptions/SendGridException.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,6 @@

namespace Vulcan\SendGrid\Exceptions;

class SendGridException extends \Exception {}
class SendGridException extends \Exception
{
}
85 changes: 76 additions & 9 deletions src/SendGrid.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@

use SendGrid\Personalization;
use SendGrid\Response;
use SilverStripe\Assets\File;
use SilverStripe\Control\Controller;
use SilverStripe\Control\Director;
use SilverStripe\Core\Config\Configurable;
use SilverStripe\Core\Injector\Injectable;
use SilverStripe\ORM\ArrayLib;
Expand All @@ -16,7 +19,7 @@
* Class SendGrid
* @package Vulcan\SendGrid
*
* @author Reece Alexander <[email protected]>
* @author Reece Alexander <[email protected]>
*/
class SendGrid
{
Expand Down Expand Up @@ -67,12 +70,18 @@ class SendGrid
*/
protected $body;

/**
* @var ArrayList
*/
protected $attachments;

/**
* SendGrid constructor.
*/
public function __construct()
{
$this->to = ArrayList::create();
$this->attachments = ArrayList::create();
$this->sendGrid = new \SendGrid($this->getApiKey());
}

Expand Down Expand Up @@ -101,21 +110,32 @@ public function send()
} else {
$personalization = new \SendGrid\Personalization();
$to = new \SendGrid\Email($recipient->Name, $recipient->Email);
$personalization->addBcc($to);
$personalization->addTo($to);
$personalization->setSubject($this->getSubject());
}

foreach ($recipient->Personalizations as $map) {
$personalization->addSubstitution($map['Key'], $map['Value']);
}

$mail->addPersonalization($personalization);
if ($i !== 0) {
$mail->addPersonalization($personalization);
}

$i++;
}

foreach ($this->getAttachments() as $attachment) {
$mail->addAttachment([
'content' => $attachment->Content,
'type' => $attachment->Type,
'filename' => $attachment->Filename
]);
}

$mail->setTemplateId($this->getTemplateId());

/** @var Response $response */
$response = $this->sendGrid->client->mail()->send()->post($mail);

// 2xx responses indicate success
Expand All @@ -125,6 +145,43 @@ public function send()
$definition = $this->getErrorDefinition($response->statusCode());
throw new SendGridException(sprintf('[Response: %s - %s] %s', $definition->Code, $definition->Message, $definition->Reason));
}

return true;
}

/**
* @param File $file The file object to attach to the email.
* @param null|string $filename The name of the file, must include extension. Will default to current filename
* @param bool $forcePublish If the provided file is unpublished, setting this to true will publish it forcibly, immediately
*
* @return $this
*/
public function addAttachment(File $file, $filename = null, $forcePublish = false)
{
if (!$file->isPublished()) {
if (!$forcePublish) {
throw new \InvalidArgumentException("That file [$file->Filename] is not published, and won't be visible to the recipient, please publish the image first or toggle the forcePublish parameter");
}

$file->publishSingle();
}

$path = Controller::join_links(Director::baseFolder(), $file->Link());

if (!file_exists($path)) {
throw new \InvalidArgumentException("That attachments represents a file that does not exist [$path]");
}

$contents = base64_encode(file_get_contents($path));

$this->attachments->push([
'Content' => $contents,
'Type' => $file->getMimeType(),
'Filename' => ($filename) ? $filename : basename($file->Filename),
'Size' => $file->getAbsoluteSize()
]);

return $this;
}

/**
Expand All @@ -135,7 +192,7 @@ public function send()
*/
public function validate()
{
if (!$this->getFromName()) {
if (!$this->getFrom()) {
throw new \InvalidArgumentException('You must set the from address');
}

Expand Down Expand Up @@ -195,11 +252,11 @@ public function addRecipient($to, $name = null, $personalizations = null)
];
}

$this->to->add([
$this->to->push(ArrayData::create([
'Email' => $to,
'Name' => $name,
'Personalizations' => $personalizations
]);
'Personalizations' => $data
]));

return $this;
}
Expand Down Expand Up @@ -304,7 +361,9 @@ public function getBody()
public function setBody($body)
{
if ($body instanceof DBHTMLText) {
$this->body = $body->getValue();
$this->body = $body->RAW();

return $this;
}

$this->body = $body;
Expand Down Expand Up @@ -388,4 +447,12 @@ public function getErrorDefinition($code)

return $record;
}
}

/**
* @return ArrayList
*/
public function getAttachments()
{
return $this->attachments;
}
}
9 changes: 6 additions & 3 deletions tests/SendGridTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,15 @@ public function tearDown()
SendGrid::config()->set('api_key', $this->originalKey);
}

public function testSendGrid()
public function testBody()
{
$dbHtmlText = DBHTMLText::create("<p>Hello World</p>");
$dbHtmlText = DBHTMLText::create()->setValue("<p>Hello World</p>");
$this->sendGrid->setBody($dbHtmlText);
$this->assertEquals("<p>Hello World</p>", $this->sendGrid->getBody(), 'When setBody is passed a DBHTMLText object, it should automatically convert that object to string');
}

public function testRecipients()
{
$this->sendGrid->addRecipient('[email protected]', 'Reece Alexander', [':salutation' => 'Mr']);

/** @var ArrayData $recipient */
Expand All @@ -62,4 +65,4 @@ public function testSendGrid()
$this->assertTrue(true);
}
}
}
}

0 comments on commit e503f63

Please sign in to comment.