Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add SendGrid API support #399

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions config/application.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,8 @@
'MailerSMTPHosts' => null, // When MailerUseSMTP is true: A string host or array of hosts (e.g., 'host1' or array('host1', 'backuphost')).
'MailerSMTPUsername' => null, // When MailerUseSMTP is true: Authorized username for SMTP server.
'MailerSMTPPassword' => null, // When MailerUseSMTP is true: Authorized password for SMTP server (for above user).
'SendGridAPIKey' => null, // SendGrid API Key for sending mail. (https://sendgrid.com/docs/Classroom/Send/How_Emails_Are_Sent/api_keys.html)
// If this API Key is set, it will be used instead of the SMTP settings.
'ServerStatusCache' => 2, // Store a cached server status and refresh every X minutes. Default: 2 minutes (value is measured in minutes).
'ServerStatusTimeout' => 2, // For each server, spend X amount of seconds to determine whether it's up or not.
'SessionKey' => 'fluxSessionData', // Shouldn't be changed, just specifies the session key to be used for session data.
Expand Down
72 changes: 72 additions & 0 deletions lib/Flux/MailerSendGrid.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
<?php

require 'sendgrid/sendgrid-php.php';

require_once 'Flux/LogFile.php';

class Flux_Mailer_SendGrid {
protected $pm;
public static $errLog;
protected static $log;

public function __construct()
{
if (!self::$errLog) {
self::$errLog = new Flux_LogFile(FLUX_DATA_DIR.'/logs/errors/mail/'.date('Ymd').'.log');
}
if (!self::$log) {
self::$log = new Flux_LogFile(FLUX_DATA_DIR.'/logs/mail/'.date('Ymd').'.log');
}

$this->pm = $pm = new \SendGrid\Mail\Mail();
$this->errLog = self::$errLog;
$this->log = self::$log;

}

public function send($recipient, $subject, $template, array $templateVars = array())
{
if (array_key_exists('_ignoreTemplate', $templateVars) && $templateVars['_ignoreTemplate']) {
$content = $template;
} else {
$templatePath = FLUX_DATA_DIR."/templates/$template.php";
if (!file_exists($templatePath)) {
return false;
}

$find = array();
$repl = array();

foreach ($templateVars as $key => $value) {
$find[] = '{'.$key.'}';
$repl[] = $value;
}

ob_start();
include $templatePath;
$content = ob_get_clean();

if (!empty($find) && !empty($repl)) {
$content = str_replace($find, $repl, $content);
}
}
$this->pm->setFrom(Flux::config('MailerFromAddress'), Flux::config('MailerFromName'));
$this->pm->AddTo($recipient, $recipient);
$this->pm->SetSubject($subject);
$this->pm->AddContent("text/html", $content);

$sendgrid = new \SendGrid(Flux::config('SendGridAPIKey'));

try {
$response = $sendgrid->send($this->pm);
self::$log->puts("sent e-mail -- Recipient: $recipient, Subject: $subject");
return $response->statusCode() . "\n";
//print_r($response->headers());
//print $response->body() . "\n";
} catch (Exception $e) {
self::$errLog->puts("{$this->pm->ErrorInfo} (while attempting -- Recipient: $recipient, Subject: $subject)");
return 'Caught exception: '. $e->getMessage() ."\n";
}
}
}
?>
9 changes: 7 additions & 2 deletions lib/Flux/PaymentNotifyRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -323,15 +323,20 @@ public function process()
$this->logPayPal('Transaction invalid, aborting.');

if(!in_array($received_from, $allowed_hosts) && Flux::config('PaypalHackNotify')){
require_once 'Flux/Mailer.php';
if(Flux::config('SendGridAPIKey')){
require_once 'Flux/MailerSendGrid.php';
$mail = new Flux_Mailer_SendGrid();
} else {
require_once 'Flux/Mailer.php';
$mail = new Flux_Mailer();
}

$customArray = @unserialize(base64_decode((string)$this->ipnVariables->get('custom')));
$customArray = $customArray && is_array($customArray) ? $customArray : array();
$customData = new Flux_Config($customArray);
$accountID = $customData->get('account_id');
$serverName = $customData->get('server_name');

$mail = new Flux_Mailer();

$tmpl = "<p>Paypal hack detected!</p>";
$tmpl .= "<p>Account: ".$accountID."</p>";
Expand Down
8 changes: 8 additions & 0 deletions lib/sendgrid-php/.editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
root = true

[*.php]
indent_style = space
indent_size = 4
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
1 change: 1 addition & 0 deletions lib/sendgrid-php/.env.sample
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export SENDGRID_API_KEY=''
647 changes: 647 additions & 0 deletions lib/sendgrid-php/CHANGELOG.md

Large diffs are not rendered by default.

73 changes: 73 additions & 0 deletions lib/sendgrid-php/CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
# Contributor Covenant Code of Conduct

## Our Pledge

In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.

## Our Standards

Examples of behavior that contributes to creating a positive environment
include:

- Using welcoming and inclusive language
- Being respectful of differing viewpoints and experiences
- Gracefully accepting constructive criticism
- Focusing on what is best for the community
- Showing empathy towards other community members

Examples of unacceptable behavior by participants include:

- The use of sexualized language or imagery and unwelcome sexual attention or
advances
- Trolling, insulting/derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information, such as a physical or electronic
address, without explicit permission
- Other conduct which could reasonably be considered inappropriate in a
professional setting

## Our Responsibilities

Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.

Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.

## Scope

This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at [email protected]. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.

Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html

[homepage]: https://www.contributor-covenant.org
160 changes: 160 additions & 0 deletions lib/sendgrid-php/CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
Hello! Thank you for choosing to help contribute to one of the Twilio SendGrid open source libraries. There are many ways you can contribute and help is always welcome. We simply ask that you follow the following contribution policies.

All third party contributors acknowledge that any contributions they provide will be made under the same open source license that the open source project is provided under.

- [Improvements to the Codebase](#improvements-to-the-codebase)
- [Development Environment](#development-environment)
- [Install and Run Locally](#install-and-run-locally)
- [Prerequisites](#prerequisites)
- [Initial setup:](#initial-setup)
- [Environment Variables](#environment-variables)
- [Execute:](#execute)
- [Understanding the Code Base](#understanding-the-codebase)
- [Testing](#testing)
- [Style Guidelines & Naming Conventions](#style-guidelines--naming-conventions)
- [Creating a Pull Request](#creating-a-pull-request)
- [Code Reviews](#code-reviews)

There are a few ways to contribute, which we'll enumerate below:

## Improvements to the Codebase

We welcome direct contributions to the sendgrid-php code base. Thank you!

Please note that we utilize the [Gitflow Workflow](https://www.atlassian.com/git/tutorials/comparing-workflows/gitflow-workflow) for Git to help keep project development organized and consistent.

### Development Environment ###

#### Install and Run Locally ####

##### Prerequisites #####

- PHP version 7.3, 7.4, 8.0, or 8.1

##### Initial setup: #####

```bash
git clone https://github.com/sendgrid/sendgrid-php.git
cd sendgrid-php
composer install
```

### Environment Variables

First, get your free Twilio SendGrid account [here](https://sendgrid.com/free?source=sendgrid-php).

Next, update your environment with your [SENDGRID_API_KEY](https://app.sendgrid.com/settings/api_keys).

```bash
echo "export SENDGRID_API_KEY='YOUR_API_KEY'" > sendgrid.env
echo "sendgrid.env" >> .gitignore
source ./sendgrid.env
```

##### Execute: #####

See the [examples folder](examples) or [README](README.md) to get started quickly.

We prefer the use of the Composer autoloader by loading `vendor/autoload.php`.

The examples will load `sendgrid-php.php` which is in the project root. This file verifies the existence of the Composer autoloader and warns you if dependencies are missing.

## Understanding the Codebase

**/examples**

Working examples that demonstrate usage.

```bash
php examples/example.php
```

**/test/unit**

Unit tests for the HTTP client.

**/test/integration**

Unit tests for the HTTP client.

**/lib**

The interface to the Twilio SendGrid API. The subfolders are helpers.

## Testing

All PRs require passing tests before the PR will be reviewed. All test files are in the [`/test/unit`](test/unit) directory. For the purposes of contributing to this repo, please update or add relevant test files [here](test) with tests as you modify the code.

The integration tests require a Twilio SendGrid mock API in order to execute. We've simplified setting this up using Docker to run the tests. You will just need [Docker Desktop](https://docs.docker.com/get-docker/) and `make`.

Once these are available, simply execute the Docker test target to run all tests: `make test-docker`. This command can also be used to open an interactive shell into the container where this library is installed. To start a *bash* shell for example, use this command: `command=bash make test-docker`.

## Style Guidelines & Naming Conventions

Generally, we follow the style guidelines as suggested by the official language. However, we ask that you conform to the styles that already exist in the library. If you wish to deviate, please explain your reasoning.

- [PSR2 Coding Standards](http://www.php-fig.org/psr/psr-2/)

Please run your code through:

- [PHP Code Sniffer](https://github.com/squizlabs/PHP_CodeSniffer)

## Creating a Pull Request

1. [Fork](https://help.github.com/fork-a-repo/) the project, clone your fork,
and configure the remotes:

```bash
# Clone your fork of the repo into the current directory
git clone https://github.com/sendgrid/sendgrid-php

# Navigate to the newly cloned directory
cd sendgrid-php

# Assign the original repo to a remote called "upstream"
git remote add upstream https://github.com/sendgrid/sendgrid-php
```

2. If you cloned a while ago, get the latest changes from upstream:

```bash
git checkout <dev-branch>
git pull upstream <dev-branch>
```

3. Create a new topic branch off the `development` branch to
contain your feature, change, or fix:

```bash
git checkout development
git checkout -b <topic-branch-name>
```

4. Commit your changes in logical chunks. Please adhere to these [git commit
message guidelines](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html)
or your code is unlikely to be merged into the main project. Use Git's
[interactive rebase](https://help.github.com/articles/interactive-rebase)
feature to tidy up your commits before making them public.

4a. Create tests.

4b. Create or update the example code that demonstrates the functionality of this change to the code.

5. Locally merge (or rebase) the upstream `development` branch into your topic branch:

```bash
git pull [--rebase] upstream development
```

6. Push your topic branch up to your fork:

```bash
git push origin <topic-branch-name>
```

7. [Open a Pull Request](https://help.github.com/articles/using-pull-requests/)
with a clear title and description against the `development` branch. All tests must be passing before we will review the PR.

## Code Reviews

If you can, please look at open PRs and review them. Give feedback and help us merge these PRs much faster! If you don't know how, GitHub has some [great information on how to review a Pull Request](https://help.github.com/articles/about-pull-request-reviews/).
16 changes: 16 additions & 0 deletions lib/sendgrid-php/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
ARG version=latest
FROM php:$version

RUN apt-get update \
&& apt-get install -y zip

RUN curl -s https://getcomposer.org/installer | php \
&& mv composer.phar /usr/local/bin/composer

COPY prism/prism/nginx/cert.crt /usr/local/share/ca-certificates/cert.crt
RUN update-ca-certificates

WORKDIR /app
COPY . .

RUN make install
Loading
Loading