File: /home/assibfaf/public_html/prox-modules/sendgridmailer/sendgridmailer.php
<?php
use Proxim\Application;
use Proxim\Configuration;
use Proxim\Module\Module;
use Proxim\Util\ArrayUtils;
use SendGrid\Mail\Attachment;
require_once dirname(__FILE__) . '/vendor/autoload.php';
class SendGridMailer extends Module
{
const SENDGRID_ENABLED = 'SENDGRID_ENABLED';
const SENDGRID_API_KEY = 'SENDGRID_API_KEY';
public function __construct()
{
$this->name = 'sendgridmailer';
$this->icon = 'fa fa-envelope';
$this->version = '1.0.0';
$this->prox_versions_compliancy = array('min' => '1.0.0', 'max' => Application::VERSION);
$this->author = 'Davison Pro';
$this->bootstrap = true;
parent::__construct();
$this->displayName = 'SendGrid';
$this->description = 'Send Email Newsletters, Password Resets, Promotional Emails, Shipping Notifications With Confidence';
}
public function install()
{
if (!parent::install()) {
return false;
}
$this->registerHook([
'actionEmailSendBefore',
'actionMailAlterMessageBeforeSend'
]);
}
public function hookActionMailAlterMessageBeforeSend($payload) {
if(!Configuration::get(self::SENDGRID_ENABLED)) {
return true;
}
$message = ArrayUtils::get($payload, 'message');
$fileAttachment = ArrayUtils::get($payload, 'fileAttachment');
$htmlMessage = ArrayUtils::get($payload, 'htmlMessage');
$email = new \SendGrid\Mail\Mail();
$from = $message->getFrom();
$to = $message->getTo();
if (is_array($from)) {
foreach ($from as $addr => $addrName) {
$addr = trim($addr);
$email->setFrom($addr, $addrName);
}
}
if (is_array($to)) {
foreach ($to as $addr => $addrName) {
$addr = trim($addr);
$email->addTo($addr, $addrName);
}
}
$email->setSubject( $message->getSubject() );
$email->addContent(
"text/html", $htmlMessage
);
if ($fileAttachment && !empty($fileAttachment)) {
// Multiple attachments?
if (!is_array(current($fileAttachment))) {
$fileAttachment = array($fileAttachment);
}
foreach ($fileAttachment as $attachment) {
if (isset($attachment['content']) && isset($attachment['name']) && isset($attachment['mime'])) {
$att = new Attachment();
$att->setContent( $attachment['content'] );
$att->setType( $attachment['mime'] );
$att->setFilename( $attachment['name'] );
$att->setDisposition("attachment");
$email->addAttachment( $att );
}
}
}
try {
$sendgrid = new SendGrid( Configuration::get(self::SENDGRID_API_KEY, PROX_ADMIN_SITE_ID) );
$res = $sendgrid->send($email);
} catch (Exception $e) {
}
return false;
}
}