Skip to content

Instantly share code, notes, and snippets.

@ShawnMcCool
Last active February 21, 2017 12:18
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ShawnMcCool/7cdc2129e0c12d9e9198edaba8ba643d to your computer and use it in GitHub Desktop.
Save ShawnMcCool/7cdc2129e0c12d9e9198edaba8ba643d to your computer and use it in GitHub Desktop.
Simple postmark email send / batching.

Examples:

public function sendSingleExample() {
    (new SendMailViaAPI('<postmark-server-token>'))->single(
        new Mail('sender name', 'sender email', 'recipient email', 'hello from exampletown', '<strong>this is bold</strong> this is not.')
    );
}

public function sendBatchExample() {
    (new SendMailViaAPI('<postmark-server-token>'))->batch([
        new Mail('sender name', 'sender email', 'recipient email', 'hello from exampletown', '<strong>this is bold</strong> this is not.'),
        new Mail('sender name', 'sender email', 'different recipient email', 'hi other person', '<strong>this is bold</strong> this is not.'),
    ]);
}
<?php
class Mail {
private $fromName;
private $fromEmail;
private $toEmail;
private $subject;
private $html;
public function __construct($fromName, $fromEmail, $toEmail, $subject, $html) {
$this->fromName = $fromName;
$this->fromEmail = $fromEmail;
$this->toEmail = $toEmail;
$this->subject = $subject;
$this->html = $html;
}
public function serialize() {
return [
'From' => $this->fromName . '<' . $this->fromEmail . '>',
'To' => $this->toEmail,
'Subject' => $this->subject,
'HtmlBody' => $this->html,
];
}
}
<?php
class SendMailViaAPI {
private $postmarkServerToken;
public function __construct($postmarkServerToken) {
$this->postmarkServerToken = $postmarkServerToken;
}
// http://developer.postmarkapp.com/developer-send-api.html (send batch email)
// api accepts a maximum of 500 mail per batch
public function batch(array $batchedMail) {
$batches = array_chunk($batchedMail, 500);
foreach ($batches as $batch) {
$this->post('https://api.postmarkapp.com/email/batch', array_map(function (Mail $mail) {
return $mail->serialize();
}, $batch));
}
}
// http://developer.postmarkapp.com/developer-send-api.html (send a single email)
public function single(Mail $mail) {
$this->post('https://api.postmarkapp.com/email', $mail->serialize());
}
private function post($url, array $fields) {
$ch = curl_init();
// request
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Accept: application/json',
'Content-Type: application/json',
'X-Postmark-Server-Token: ' . $this->postmarkServerToken,
]);
// payload
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// execute
curl_exec($ch);
curl_close($ch);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment