Skip to content

Commit

Permalink
Made updates for SilverStripe 4.9.0
Browse files Browse the repository at this point in the history
These are quick updates to make this library compatible with SilverStripe 4.9.0
  • Loading branch information
Linkdup committed Oct 12, 2021
1 parent 841c329 commit fe5d287
Show file tree
Hide file tree
Showing 2 changed files with 139 additions and 55 deletions.
28 changes: 19 additions & 9 deletions src/MailgunHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace LeKoala\Mailgun;

use \Exception;
use Swift_Mailer;
use Mailgun\Mailgun;
use SilverStripe\Control\Director;
use SilverStripe\Core\Environment;
Expand Down Expand Up @@ -47,7 +48,9 @@ public static function getMailer()
*/
public static function isMailgunMailer()
{
return self::getMailer()->getSwiftMailer()->getTransport() instanceof MailgunSwiftTransport;
return self::getMailer()
->getSwiftMailer()
->getTransport() instanceof MailgunSwiftTransport;
}

/**
Expand All @@ -60,7 +63,9 @@ public static function getClient()
if (!self::$client) {
$key = self::config()->api_key;
if (empty($key)) {
throw new \Exception("api_key is not configured for " . __CLASS__);
throw new \Exception(
'api_key is not configured for ' . __CLASS__
);
}
$endpoint = self::DEFAULT_ENDPOINT;
if (self::config()->endpoint) {
Expand Down Expand Up @@ -102,7 +107,7 @@ public static function getDomain()
if ($domain = Environment::getEnv('MAILGUN_DOMAIN')) {
return $domain;
}
throw new Exception("MAILGUN_DOMAIN not set");
throw new Exception('MAILGUN_DOMAIN not set');
}

/**
Expand Down Expand Up @@ -164,15 +169,18 @@ public static function registerTransport()
$client = self::getClient();
$mailer = self::getMailer();
if (!$mailer instanceof SwiftMailer) {
throw new Exception("Mailer must be an instance of " . SwiftMailer::class . " instead of " . get_class($mailer));
throw new Exception(
'Mailer must be an instance of ' .
SwiftMailer::class .
' instead of ' .
get_class($mailer)
);
}
$transport = new MailgunSwiftTransport($client);
$newSwiftMailer = $mailer->getSwiftMailer()->newInstance($transport);
$mailer->setSwiftMailer($newSwiftMailer);
$mailer->setSwiftMailer(new Swift_Mailer($transport));
return $mailer;
}


/**
* Resolve default send from address
*
Expand All @@ -184,8 +192,10 @@ public static function registerTransport()
* @param bool $createDefault
* @return string
*/
public static function resolveDefaultFromEmail($from = null, $createDefault = true)
{
public static function resolveDefaultFromEmail(
$from = null,
$createDefault = true
) {
$original_from = $from;
if (!empty($from)) {
// If we have a sender, validate its email
Expand Down
166 changes: 120 additions & 46 deletions src/MailgunSwiftTransport.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace LeKoala\Mailgun;

use \Exception;
use \Swift_Mime_SimpleMessage;
use \Swift_MimePart;
use \Swift_Transport;
use \Swift_Attachment;
Expand All @@ -22,7 +23,6 @@
*/
class MailgunSwiftTransport implements Swift_Transport
{

/**
* @var Swift_Transport_SimpleMailInvoker
*/
Expand Down Expand Up @@ -85,23 +85,38 @@ public function stop()
$this->isStarted = false;
}

/**
* Not used
*/
public function ping()
{
return true;
}

/**
* @param Swift_Mime_Message $message
* @param null $failedRecipients
* @return int Number of messages sent
*/
public function send(Swift_Mime_Message $message, &$failedRecipients = null)
{
public function send(
Swift_Mime_SimpleMessage $message,
&$failedRecipients = null
) {
$this->resultApi = null;
if ($event = $this->eventDispatcher->createSendEvent($this, $message)) {
$this->eventDispatcher->dispatchEvent($event, 'beforeSendPerformed');
$this->eventDispatcher->dispatchEvent(
$event,
'beforeSendPerformed'
);
if ($event->bubbleCancelled()) {
return 0;
}
}

$sendCount = 0;
$disableSending = $message->getHeaders()->has('X-SendingDisabled') || MailgunHelper::config()->disable_sending;
$disableSending =
$message->getHeaders()->has('X-SendingDisabled') ||
MailgunHelper::config()->disable_sending;

$emailData = $this->buildMessage($message);

Expand All @@ -114,7 +129,9 @@ public function send(Swift_Mime_Message $message, &$failedRecipients = null)
];
$queued = true;
} else {
$resultResponse = $client->messages()->send(MailgunHelper::getDomain(), $emailData);
$resultResponse = $client
->messages()
->send(MailgunHelper::getDomain(), $emailData);
if ($resultResponse) {
$result = [
'message' => $resultResponse->getMessage(),
Expand Down Expand Up @@ -158,8 +175,10 @@ public function send(Swift_Mime_Message $message, &$failedRecipients = null)
* @param array $results Results from the api
* @return void
*/
protected function logMessageContent(Swift_Mime_Message $message, $results = [])
{
protected function logMessageContent(
Swift_Mime_Message $message,
$results = []
) {
$subject = $message->getSubject();
$body = $message->getBody();
$contentType = $this->getMessagePrimaryContentType($message);
Expand All @@ -173,10 +192,16 @@ protected function logMessageContent(Swift_Mime_Message $message, $results = [])
$logContent .= 'From : ' . print_r($message->getFrom(), true) . "\n";
$logContent .= 'Headers:' . "\n";
foreach ($message->getHeaders()->getAll() as $header) {
$logContent .= ' ' . $header->getFieldName() . ': ' . $header->getFieldBody() . "\n";
$logContent .=
' ' .
$header->getFieldName() .
': ' .
$header->getFieldBody() .
"\n";
}
if (!empty($message->getTo())) {
$logContent .= 'Recipients : ' . print_r($message->getTo(), true) . "\n";
$logContent .=
'Recipients : ' . print_r($message->getTo(), true) . "\n";
}
$logContent .= 'Results:' . "\n";
foreach ($results as $resultKey => $resultValue) {
Expand All @@ -197,16 +222,32 @@ protected function logMessageContent(Swift_Mime_Message $message, $results = [])
$logContent .= '<hr />';
foreach ($attachments as $attachment) {
if ($attachment instanceof Swift_Attachment) {
$attachmentDestination = $logFolder . '/' . $logName . '_' . $attachment->getFilename();
file_put_contents($attachmentDestination, $attachment->getBody());
$logContent .= 'File : <a href="' . $attachmentDestination . '">' . $attachment->getFilename() . '</a><br/>';
$attachmentDestination =
$logFolder .
'/' .
$logName .
'_' .
$attachment->getFilename();
file_put_contents(
$attachmentDestination,
$attachment->getBody()
);
$logContent .=
'File : <a href="' .
$attachmentDestination .
'">' .
$attachment->getFilename() .
'</a><br/>';
}
}
}

// Store it
$ext = ($contentType == 'text/html') ? 'html' : 'txt';
$r = file_put_contents($logFolder . '/' . $logName . '.' . $ext, $logContent);
$ext = $contentType == 'text/html' ? 'html' : 'txt';
$r = file_put_contents(
$logFolder . '/' . $logName . '.' . $ext,
$logContent
);

if (!$r && Director::isDev()) {
throw new Exception('Failed to store email in ' . $logFolder);
Expand All @@ -218,7 +259,9 @@ protected function logMessageContent(Swift_Mime_Message $message, $results = [])
*/
public function getLogger()
{
return Injector::inst()->get(LoggerInterface::class)->withName('Mailgun');
return Injector::inst()
->get(LoggerInterface::class)
->withName('Mailgun');
}

/**
Expand All @@ -234,10 +277,7 @@ public function registerPlugin(Swift_Events_EventListener $plugin)
*/
protected function getSupportedContentTypes()
{
return array(
'text/plain',
'text/html'
);
return ['text/plain', 'text/html'];
}

/**
Expand Down Expand Up @@ -291,24 +331,30 @@ public function buildMessage(Swift_Mime_Message $message)
$fromFirstName = current($fromAddresses);

if ($fromFirstName) {
$this->fromEmail = sprintf('%s <%s>', $fromFirstName, $fromFirstEmail);
$this->fromEmail = sprintf(
'%s <%s>',
$fromFirstName,
$fromFirstEmail
);
} else {
$this->fromEmail = $fromFirstEmail;
}

$toAddresses = $message->getTo();
$ccAddresses = $message->getCc() ? $message->getCc() : [];
$bccAddresses = $message->getBcc() ? $message->getBcc() : [];
$replyToAddresses = $message->getReplyTo() ? $message->getReplyTo() : [];

$recipients = array();
$cc = array();
$bcc = array();
$attachments = array();
$headers = array();
$tags = array();
$metadata = array();
$mergeVars = array();
$replyToAddresses = $message->getReplyTo()
? $message->getReplyTo()
: [];

$recipients = [];
$cc = [];
$bcc = [];
$attachments = [];
$headers = [];
$tags = [];
$metadata = [];
$mergeVars = [];
$inlineCss = null;

// Mandrill compatibility
Expand All @@ -321,16 +367,25 @@ public function buildMessage(Swift_Mime_Message $message)
}
if ($message->getHeaders()->has('X-MC-Metadata')) {
$metadataHeader = $message->getHeaders()->get('X-MC-Metadata');
$metadata = json_decode($metadataHeader->getValue(), JSON_OBJECT_AS_ARRAY);
$metadata = json_decode(
$metadataHeader->getValue(),
JSON_OBJECT_AS_ARRAY
);
$message->getHeaders()->remove('X-MC-Metadata');
}
if ($message->getHeaders()->has('X-MC-InlineCSS')) {
$inlineCss = $message->getHeaders()->get('X-MC-InlineCSS')->getValue();
$inlineCss = $message
->getHeaders()
->get('X-MC-InlineCSS')
->getValue();
$message->getHeaders()->remove('X-MC-InlineCSS');
}
if ($message->getHeaders()->has('X-MC-MergeVars')) {
$mergeVarsHeader = $message->getHeaders()->get('X-MC-MergeVars');
$mergeVarsFromMC = json_decode($mergeVarsHeader->getValue(), JSON_OBJECT_AS_ARRAY);
$mergeVarsFromMC = json_decode(
$mergeVarsHeader->getValue(),
JSON_OBJECT_AS_ARRAY
);
// We need to transform them to a mandrill friendly format rcpt => vars, to email : {...}
foreach ($mergeVarsFromMC as $row) {
$mergeVars[$row['rcpt']] = $row['vars'];
Expand All @@ -348,13 +403,23 @@ public function buildMessage(Swift_Mime_Message $message)
}
// @link https://documentation.mailgun.com/en/latest/user_manual.html#attaching-data-to-messages
if ($message->getHeaders()->has('X-Mailgun-Variables')) {
$metadataHeader = $message->getHeaders()->get('X-Mailgun-Variables');
$metadata = json_decode($metadataHeader->getValue(), JSON_OBJECT_AS_ARRAY);
$metadataHeader = $message
->getHeaders()
->get('X-Mailgun-Variables');
$metadata = json_decode(
$metadataHeader->getValue(),
JSON_OBJECT_AS_ARRAY
);
$message->getHeaders()->remove('X-Mailgun-Variables');
}
if ($message->getHeaders()->has('X-Mailgun-Recipient-Variables')) {
$recipientVariablesHeader = $message->getHeaders()->get('X-Mailgun-Recipient-Variables');
$mergeVars = json_decode($recipientVariablesHeader->getValue(), JSON_OBJECT_AS_ARRAY);
$recipientVariablesHeader = $message
->getHeaders()
->get('X-Mailgun-Recipient-Variables');
$mergeVars = json_decode(
$recipientVariablesHeader->getValue(),
JSON_OBJECT_AS_ARRAY
);
$message->getHeaders()->remove('X-Mailgun-Recipient-Variables');
}

Expand Down Expand Up @@ -410,12 +475,18 @@ public function buildMessage(Swift_Mime_Message $message)
// File attachment. You can post multiple attachment values.
// Important: You must use multipart/form-data encoding when sending attachments.
if ($child instanceof Swift_Attachment) {
$attachment = ['filename' => $child->getFilename(), 'fileContent' => $child->getBody()];
$attachment = [
'filename' => $child->getFilename(),
'fileContent' => $child->getBody(),
];
$attachments[] = $attachment;
} elseif ($child instanceof Swift_MimePart && $this->supportsContentType($child->getContentType())) {
if ($child->getContentType() == "text/html") {
} elseif (
$child instanceof Swift_MimePart &&
$this->supportsContentType($child->getContentType())
) {
if ($child->getContentType() == 'text/html') {
$bodyHtml = $child->getBody();
} elseif ($child->getContentType() == "text/plain") {
} elseif ($child->getContentType() == 'text/plain') {
$bodyText = $child->getBody();
}
}
Expand All @@ -433,12 +504,15 @@ public function buildMessage(Swift_Mime_Message $message)

// Custom unsubscribe list
if ($message->getHeaders()->has('List-Unsubscribe')) {
$headers['List-Unsubscribe'] = $message->getHeaders()->get('List-Unsubscribe')->getValue();
$headers['List-Unsubscribe'] = $message
->getHeaders()
->get('List-Unsubscribe')
->getValue();
}

// Mailgun params format does not work well in yml, so we map them
$rawParams = MailgunHelper::config()->default_params;
$defaultParams = [];
$defaultParams = [];
foreach ($rawParams as $rawParamKey => $rawParamValue) {
switch ($rawParamKey) {
case 'inline':
Expand All @@ -460,13 +534,13 @@ public function buildMessage(Swift_Mime_Message $message)
}

// Build base transmission
$mailgunMessage = array(
$mailgunMessage = [
'to' => implode(',', $recipients),
'from' => $this->fromEmail,
'subject' => $message->getSubject(),
'html' => $bodyHtml,
'text' => $bodyText,
);
];
if ($reply_to) {
$mailgunMessage['h:Reply-To'] = $reply_to;
}
Expand Down

0 comments on commit fe5d287

Please sign in to comment.