Skip to content

Instantly share code, notes, and snippets.

@wilr
Last active August 3, 2020 03:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wilr/d32a0e83af3489538603f1b2f18dc73a to your computer and use it in GitHub Desktop.
Save wilr/d32a0e83af3489538603f1b2f18dc73a to your computer and use it in GitHub Desktop.
Postmark Mailing in Silverstripe 4.5

Sending Emails via Postmark in Silverstripe 4

Silverstripe 4 uses an older version of Swift Mailer (v5) not v6 so you'll find the latest Postmark SDK won't work out of the box. You'll receive something like the following when you come to do $email->send()

ERROR [Notice]: Object of class GuzzleHttp\Psr7\Response could not be converted to int
Line 45 in framework/src/Control/Email/SwiftMailer.php

Not to fear! With a bit of configuration and a wrapper class we can get this to work. Apply the email.yml config to your project and but the PostmarkMailTransport.php class in your project code.

composer require wildbit/swiftmailer-postmark ^2
---
Name: projectemailconfig
After:
- '#emailconfig'
---
SilverStripe\Core\Injector\Injector:
Swift_Transport:
class: PostmarkMailTransport
constructor:
0: '{{ your postmark key }}'
<?php
use Psr\Log\LoggerInterface;
use SilverStripe\Control\Email\Email;
use SilverStripe\Control\Director;
use SilverStripe\Core\Environment;
use SilverStripe\Core\Injector\Injector;
class PostmarkMailTransport extends \Postmark\Transport
{
public function send(Swift_Mime_Message $message, &$failedRecipients = null)
{
if (!$message->getFrom()) {
$message->setFrom(Email::config()->send_all_emails_from);
}
if (defined('SS_SEND_ALL_EMAILS_TO')) {
// override sender
$message->setTo(SS_SEND_ALL_EMAILS_TO);
} elseif ($t = Environment::getEnv('SS_SEND_ALL_EMAILS_TO')) {
// send
$message->setTo($t);
} elseif (Director::isDev() || Director::isTest()) {
// prevent emailing to everyone
$message->setTo(Email::config()->admin_email);
}
$result = parent::send($message, $failedRecipients);
if ($result->getStatusCode() == 200) {
return 1;
} else {
$err = sprintf(
'Could not send Postmark Email: Error status %s - %s %s',
$result->getStatusCode(),
$result->getReasonPhrase(),
$result->getBody()->getContents()
);
Injector::inst()->get(LoggerInterface::class)->warning($err);
if (Director::isDev()) {
throw new Exception($err);
}
return 0;
}
return $result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment