forked from Znarkus/postmark-php
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Postmark.php
executable file
·642 lines (558 loc) · 17 KB
/
Postmark.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
<?php
/**
* Postmark PHP class
*
* Copyright 2011, Markus Hedlund, Mimmin AB, www.mimmin.com
* Licensed under the MIT License.
* Redistributions of files must retain the above copyright notice.
*
* @author Markus Hedlund ([email protected]) at mimmin (www.mimmin.com)
* @copyright Copyright 2009 - 2011, Markus Hedlund, Mimmin AB, www.mimmin.com
* @version 0.4.5
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*
* Usage:
* Mail_Postmark::compose()
* ->addTo('[email protected]', 'Name')
* ->subject('Subject')
* ->messagePlain('Plaintext message')
* ->tag('Test tag')
* ->send();
*
* or:
*
* $email = new Mail_Postmark();
* $email->addTo('[email protected]', 'Name')
* ->subject('Subject')
* ->messagePlain('Plaintext message')
* ->tag('Test tag')
* ->send();
*/
class Mail_Postmark
{
const DEBUG_OFF = 0;
const DEBUG_VERBOSE = 1;
const DEBUG_RETURN = 2;
const TESTING_API_KEY = 'POSTMARK_API_TEST';
const MAX_ATTACHMENT_SIZE = 10485760; // 10 MB
const RECIPIENT_TYPE_TO = 'to';
const RECIPIENT_TYPE_CC = 'cc';
const RECIPIENT_TYPE_BCC = 'bcc';
static $_mimeTypes = array('ai' => 'application/postscript', 'avi' => 'video/x-msvideo', 'doc' => 'application/msword', 'eps' => 'application/postscript', 'gif' => 'image/gif', 'htm' => 'text/html', 'html' => 'text/html', 'jpeg' => 'image/jpeg', 'jpg' => 'image/jpeg', 'mov' => 'video/quicktime', 'mp3' => 'audio/mpeg', 'mpg' => 'video/mpeg', 'pdf' => 'application/pdf', 'ppt' => 'application/vnd.ms-powerpoint', 'ps' => 'application/postscript', 'rtf' => 'application/rtf', 'tif' => 'image/tiff', 'tiff' => 'image/tiff', 'txt' => 'text/plain', 'xls' => 'application/vnd.ms-excel', 'csv' => 'text/comma-separated-values', 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'flv' => 'video/x-flv', 'ics' => 'text/calendar', 'log' => 'text/plain', 'png' => 'image/png', 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'psd' => 'image/photoshop', 'rm' => 'application/vnd.rn-realmedia', 'swf' => 'application/x-shockwave-flash', 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'xml' => 'text/xml');
private $_apiKey;
private $_from;
private $_to = array();
private $_cc = array();
private $_bcc = array();
private $_replyTo;
private $_subject;
private $_tag;
private $_messagePlain;
private $_messageHtml;
private $_headers = array();
private $_attachments = array();
private $_debugMode = self::DEBUG_OFF;
/**
* Initialize
*/
public function __construct()
{
if (class_exists('Mail_Postmark_Adapter', false)) {
require_once('Adapter_Interface.php');
$reflection = new ReflectionClass('Mail_Postmark_Adapter');
if (!$reflection->implementsInterface('Mail_Postmark_Adapter_Interface')) {
trigger_error('Mail_Postmark_Adapter must implement interface Mail_Postmark_Adapter_Interface', E_USER_ERROR);
}
$this->_apiKey = Mail_Postmark_Adapter::getApiKey();
Mail_Postmark_Adapter::setupDefaults($this);
} else {
if (!defined('POSTMARKAPP_API_KEY')) {
trigger_error('Postmark API key is not set', E_USER_ERROR);
}
$this->_apiKey = POSTMARKAPP_API_KEY;
if (defined('POSTMARKAPP_MAIL_FROM_ADDRESS')) {
$this->from(
POSTMARKAPP_MAIL_FROM_ADDRESS,
defined('POSTMARKAPP_MAIL_FROM_NAME') ? POSTMARKAPP_MAIL_FROM_NAME : null
);
}
}
$this->messageHtml(null)->messagePlain(null);
}
/**
* Add a physical file as an attachment
* Options:
* - filenameAlias, use a different filename for the attachment
*
* @param string $filename Location of the file
* @param array $options An optional array with options
* @throws InvalidArgumentException If file doesn't exist
* @throws OverflowException If maximum attachment size has been reached
* @return Mail_Postmark
*/
public function &addAttachment($filename, $options = array())
{
if (!is_file($filename)) {
throw new InvalidArgumentException("File \"{$filename}\" does not exist");
}
$this->addCustomAttachment(
isset($options['filenameAlias']) ? $options['filenameAlias'] : basename($filename),
file_get_contents($filename),
$this->_getMimeType($filename)
);
return $this;
}
/**
* Add a BCC address
*
* @param string $address E-mail address used in BCC
* @param string $name Optional. Name used in BCC
* @throws InvalidArgumentException On invalid address
* @throws OverflowException If there are too many email recipients
* @return Mail_Postmark
*/
public function &addBcc($address, $name = null)
{
$this->_addRecipient(self::RECIPIENT_TYPE_BCC, $address, $name);
return $this;
}
/**
* Add a CC address
*
* @param string $address E-mail address used in CC
* @param string $name Optional. Name used in CC
* @throws InvalidArgumentException On invalid address
* @throws OverflowException If there are too many email recipients
* @return Mail_Postmark
*/
public function &addCc($address, $name = null)
{
$this->_addRecipient(self::RECIPIENT_TYPE_CC, $address, $name);
return $this;
}
/**
* Add an attachment.
*
* @param string $filename What to call the file
* @param string $content Raw file data
* @param string $mimeType The mime type of the file
* @throws OverflowException If maximum attachment size has been reached
* @return Mail_Postmark
*/
public function &addCustomAttachment($filename, $content, $mimeType)
{
$length = strlen($content);
$lengthSum = 0;
foreach ($this->_attachments as $file) {
$lengthSum += $file['length'];
}
if ($lengthSum + $length > self::MAX_ATTACHMENT_SIZE) {
throw new OverflowException("Maximum attachment size reached");
}
$this->_attachments[$filename] = array(
'content' => base64_encode($content),
'mimeType' => $mimeType,
'length' => $length
);
return $this;
}
/**
* Add a custom header
*
* @param string $name Custom header name
* @param string $value Custom header value
* @return Mail_Postmark
*/
public function &addHeader($name, $value)
{
$this->_headers[$name] = $value;
return $this;
}
/**
* Add a receiver
*
* @param string $address E-mail address used in To
* @param string $name Optional. Name used in To
* @throws InvalidArgumentException On invalid address
* @throws OverflowException If there are too many email recipients
* @return Mail_Postmark
*/
public function &addTo($address, $name = null)
{
$this->_addRecipient(self::RECIPIENT_TYPE_TO, $address, $name);
return $this;
}
/**
* New e-mail
*
* @return Mail_Postmark
*/
public static function compose()
{
return new self();
}
/**
* Turns debug output on
*
* @param int $mode One of the debug constants
* @return Mail_Postmark
*/
public function &debug($mode = self::DEBUG_VERBOSE)
{
$this->_debugMode = $mode;
return $this;
}
/**
* Specify sender. Overwrites default From. Note that the address
* must first be added in the Postmark app admin interface
*
* @param string $address E-mail address used in From
* @param string $name Optional. Name used in From
* @throws InvalidArgumentException On invalid address
* @return Mail_Postmark
*/
public function &from($address, $name = null)
{
if (!$this->_validateAddress($address)) {
throw new InvalidArgumentException("From address \"{$address}\" is invalid");
}
$this->_from = array('address' => $address, 'name' => $name);
return $this;
}
/**
* Specify sender name. Overwrites default From name, but doesn't change address.
*
* @param string $name Name used in From
* @return Mail_Postmark
*/
public function &fromName($name)
{
$this->_from['name'] = $name;
return $this;
}
/**
* Add HTML message. Can be used in conjunction with messagePlain()
*
* @param string $message E-mail message
* @return Mail_Postmark
*/
public function &messageHtml($message)
{
$this->_messageHtml = $message;
return $this;
}
/**
* Add plaintext message. Can be used in conjunction with messageHtml()
* @param string $message E-mail message
* @return Mail_Postmark
*/
public function &messagePlain($message)
{
$this->_messagePlain = $message;
return $this;
}
/**
* Specify reply-to
*
* @param string $address E-mail address used in To
* @param string $name Optional. Name used in To
* @throws InvalidArgumentException On invalid address
* @return Mail_Postmark
*/
public function &replyTo($address, $name = null)
{
if (!$this->_validateAddress($address)) {
throw new InvalidArgumentException("Reply To address \"{$address}\" is invalid");
}
$this->_replyTo = array('address' => $address, 'name' => $name);
return $this;
}
/**
* Sends the e-mail. Prints debug output if debug mode is turned on
*
* Options:
* returnMessageId
*
* @throws Exception If HTTP code 422, Exception with API error code and Postmark message, otherwise HTTP code.
* @throws BadMethodCallException If From address, To address or Subject is missing
* @return boolean - True if success and $returnID is false.
* @return string - if $returnID is true and one message is sent.
* @return array - if DEBUG_RETURN is enabled.
*/
public function send($options = array())
{
$this->_validateData();
$data = $this->_prepareData();
$headers = array(
'Accept: application/json',
'Content-Type: application/json',
'X-Postmark-Server-Token: ' . $this->_apiKey
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.postmarkapp.com/email');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) . '/Certificate/cacert.pem');
$return = curl_exec($ch);
$curlError = curl_error($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$this->_log(array(
'messageData' => $data,
'return' => $return,
'curlError' => $curlError,
'httpCode' => $httpCode
));
if (($this->_debugMode & self::DEBUG_VERBOSE) === self::DEBUG_VERBOSE) {
echo "JSON: " . json_encode($data)
. "\nHeaders: \n\t" . implode("\n\t", $headers)
. "\nReturn:\n{$return}"
. "\nCurl error: {$curlError}"
. "\nHTTP code: {$httpCode}";
}
if ($curlError !== '') {
throw new Exception($curlError);
}
if (!$this->_isTwoHundred($httpCode)) {
if ($httpCode == 422) {
$return = json_decode($return);
throw new Exception($return->Message, $return->ErrorCode);
} else {
throw new Exception("Error while mailing. Postmark returned HTTP code {$httpCode} with message \"{$return}\"", $httpCode);
}
}
if (($this->_debugMode & self::DEBUG_RETURN) === self::DEBUG_RETURN) {
return array(
'json' => json_encode($data),
'headers' => $headers,
'return' => $return,
'curlError' => $curlError,
'httpCode' => $httpCode
);
}
// Return the ID of the message sent if the option is set.
if(!empty($options['returnMessageId'])) {
$messageInformation = json_decode($return);
return $messageInformation->MessageID;
}
return true;
}
/**
* Specify subject
*
* @param string $subject E-mail subject
* @return Mail_Postmark
*/
public function &subject($subject)
{
$this->_subject = $subject;
return $this;
}
/**
* You can categorize outgoing email using the optional Tag property.
* If you use different tags for the different types of emails your
* application generates, you will be able to get detailed statistics
* for them through the Postmark user interface.
* Only 1 tag per email is supported.
*
* @param string $tag One tag
* @return Mail_Postmark
*/
public function &tag($tag)
{
$this->_tag = $tag;
return $this;
}
/**
* Specify receiver. Use addTo to add more.
*
* @deprecated Use addTo.
* @param string $address E-mail address used in To
* @param string $name Optional. Name used in To
* @return Mail_Postmark
*/
public function &to($address, $name = null)
{
$this->_to = array();
$this->addTo($address, $name);
return $this;
}
/**
* @param string $type Either 'to', 'cc' or 'bcc'
* @param string $address
* @param string|null $name
* @throws InvalidArgumentException On invalid address
* @throws OverflowException If there are too many email recipients
*/
public function _addRecipient($type, $address, $name = null)
{
$address = trim($address);
if (!$this->_validateAddress($address)) {
throw new InvalidArgumentException("Address \"{$address}\" is invalid");
}
if (count($this->_to) + count($this->_cc) + count($this->_bcc) === 20) {
throw new OverflowException('Too many email recipients');
}
$data = array('address' => $address, 'name' => $name);
switch ($type) {
case self::RECIPIENT_TYPE_TO:
$this->_to[] = $data;
break;
case self::RECIPIENT_TYPE_CC:
$this->_cc[] = $data;
break;
case self::RECIPIENT_TYPE_BCC:
$this->_bcc[] = $data;
break;
}
}
private function _createAddress($address, $name = null)
{
if (isset($name)) {
return '"' . str_replace('"', '', $name) . '" <' . $address . '>';
} else {
return $address;
}
}
/**
* Try to detect the mime type
* @param $filename
* @return string
*/
private function _getMimeType($filename)
{
$extension = pathinfo($filename, PATHINFO_EXTENSION);
if (isset(self::$_mimeTypes[$extension])) {
return self::$_mimeTypes[$extension];
} else if (function_exists('mime_content_type')) {
return mime_content_type($filename);
} else if (function_exists('finfo_file')) {
$fh = finfo_open(FILEINFO_MIME);
$mime = finfo_file($fh, $filename);
finfo_close($fh);
return $mime;
} else if ($image = getimagesize($filename)) {
return $image[2];
} else {
return 'application/octet-stream';
}
}
/**
* If a number is 200-299
* @param $value
* @return bool
*/
private function _isTwoHundred($value)
{
return intval($value / 100) == 2;
}
/**
* Call the logger method, if one exists
*
* @param array $logData
*/
private function _log($logData)
{
if (class_exists('Mail_Postmark_Adapter', false)) {
Mail_Postmark_Adapter::log($logData);
}
}
/**
* Prepares the data array
* @return array
*/
private function _prepareData()
{
$data = array(
'Subject' => $this->_subject
);
$data['From'] = $this->_createAddress($this->_from['address'], $this->_from['name']);
$data['To'] = array();
$data['Cc'] = array();
$data['Bcc'] = array();
foreach ($this->_to as $to) {
$data['To'][] = $this->_createAddress($to['address'], $to['name']);
}
foreach ($this->_cc as $cc) {
$data['Cc'][] = $this->_createAddress($cc['address'], $cc['name']);
}
foreach ($this->_bcc as $bcc) {
$data['Bcc'][] = $this->_createAddress($bcc['address'], $bcc['name']);
}
$data['To'] = implode(', ', $data['To']);
if (empty($data['Cc'])) {
unset($data['Cc']);
} else {
$data['Cc'] = implode(', ', $data['Cc']);
}
if (empty($data['Bcc'])) {
unset($data['Bcc']);
} else {
$data['Bcc'] = implode(', ', $data['Bcc']);
}
if ($this->_replyTo !== null) {
$data['ReplyTo'] = $this->_createAddress($this->_replyTo['address'], $this->_replyTo['name']);
}
if ($this->_messageHtml !== null) {
$data['HtmlBody'] = $this->_messageHtml;
}
if ($this->_messagePlain !== null) {
$data['TextBody'] = $this->_messagePlain;
}
if ($this->_tag !== null) {
$data['Tag'] = $this->_tag;
}
if (!empty($this->_headers)) {
$data['Headers'] = array();
foreach ($this->_headers as $name => $value) {
$data['Headers'][] = array('Name' => $name, 'Value' => $value);
}
}
if (!empty($this->_attachments)) {
$data['Attachments'] = array();
foreach ($this->_attachments as $filename => $file) {
$data['Attachments'][] = array(
'Name' => $filename,
'Content' => $file['content'],
'ContentType' => $file['mimeType']
);
}
}
return $data;
}
/**
* Validates an e-mail address
* @param $email
* @return bool
*/
private function _validateAddress($email)
{
// http://php.net/manual/en/function.filter-var.php
// return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
// filter_var proved to be unworthy (passed [email protected] as valid),
// and was therefore replace with
$regex = "/^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+@((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$/i";
// from http://fightingforalostcause.net/misc/2006/compare-email-regex.php
return preg_match($regex, $email) === 1;
}
/**
* Validate that the email can be sent
*
* @throws BadMethodCallException If From address, To address or Subject is missing
*/
private function _validateData()
{
if ($this->_from['address'] === null) {
throw new BadMethodCallException('From address is not set');
}
if (empty($this->_to)) {
throw new BadMethodCallException('No To address is set');
}
if (!isset($this->_subject)) {
throw new BadMethodCallException('Subject is not set');
}
}
}