djekl
1/25/2017 - 12:55 PM

Simple postmark email send / batching.

Simple postmark email send / batching.

<?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);
    }
}
<?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,
        ];
    }
}

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.'),
    ]);
}