· 8 years ago · Feb 02, 2018, 02:44 AM
1<?php
2/**
3*
4* Copyright (c) 2011, Dan Myers.
5* Parts copyright (c) 2008, Donovan Schonknecht.
6* All rights reserved.
7*
8* Redistribution and use in source and binary forms, with or without
9* modification, are permitted provided that the following conditions are met:
10*
11* - Redistributions of source code must retain the above copyright notice,
12* this list of conditions and the following disclaimer.
13* - Redistributions in binary form must reproduce the above copyright
14* notice, this list of conditions and the following disclaimer in the
15* documentation and/or other materials provided with the distribution.
16*
17* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
21* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27* POSSIBILITY OF SUCH DAMAGE.
28*
29* This is a modified BSD license (the third clause has been removed).
30* The BSD license may be found here:
31* http://www.opensource.org/licenses/bsd-license.php
32*
33* Amazon Simple Email Service is a trademark of Amazon.com, Inc. or its affiliates.
34*
35* SimpleEmailService is based on Donovan Schonknecht's Amazon S3 PHP class, found here:
36* http://undesigned.org.za/2007/10/22/amazon-s3-php-class
37*
38*/
39
40/**
41* Amazon SimpleEmailService PHP class
42*
43* @link http://sourceforge.net/projects/php-aws-ses/
44* version 0.8.2
45*
46*/
47class SimpleEmailService
48{
49 protected $__accessKey; // AWS Access key
50 protected $__secretKey; // AWS Secret key
51 protected $__host;
52
53 public function getAccessKey() { return $this->__accessKey; }
54 public function getSecretKey() { return $this->__secretKey; }
55 public function getHost() { return $this->__host; }
56
57 protected $__verifyHost = 1;
58 protected $__verifyPeer = 0;
59
60 // verifyHost and verifyPeer determine whether curl verifies ssl certificates.
61 // It may be necessary to disable these checks on certain systems.
62 // These only have an effect if SSL is enabled.
63 public function verifyHost() { return $this->__verifyHost; }
64 public function enableVerifyHost($enable = true) { $this->__verifyHost = $enable; }
65
66 public function verifyPeer() { return $this->__verifyPeer; }
67 public function enableVerifyPeer($enable = true) { $this->__verifyPeer = $enable; }
68
69 /**
70 * Constructor
71 *
72 * @param string $accessKey Access key
73 * @param string $secretKey Secret key
74 * @return void
75 */
76 public function __construct($accessKey = null, $secretKey = null, $host = 'email.us-east-1.amazonaws.com') {
77 if ($accessKey !== null && $secretKey !== null) {
78 $this->setAuth($accessKey, $secretKey);
79 }
80 $this->__host = $host;
81 }
82
83 /**
84 * Set AWS access key and secret key
85 *
86 * @param string $accessKey Access key
87 * @param string $secretKey Secret key
88 * @return void
89 */
90 public function setAuth($accessKey, $secretKey) {
91 $this->__accessKey = $accessKey;
92 $this->__secretKey = $secretKey;
93 }
94
95 /**
96 * Lists the email addresses that have been verified and can be used as the 'From' address
97 *
98 * @return An array containing two items: a list of verified email addresses, and the request id.
99 */
100 public function ListIdentities() {
101 $rest = new SimpleEmailServiceRequest($this, 'GET');
102 $rest->setParameter('Action', 'ListIdentities');
103
104 $rest = $rest->getResponse();
105 if($rest->error === false && $rest->code !== 200) {
106 $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
107 }
108 if($rest->error !== false) {
109 $this->__triggerError('ListIdentities', $rest->error);
110 return false;
111 }
112
113 $response = array();
114 if(!isset($rest->body)) {
115 return $response;
116 }
117
118 $addresses = array();
119 foreach($rest->body->ListIdentitiesResult->Identities->member as $address) {
120 $addresses[] = (string)$address;
121 }
122
123 $response['Addresses'] = $addresses;
124 $response['RequestId'] = (string)$rest->body->ResponseMetadata->RequestId;
125
126 return $response;
127 }
128
129 public function getIdentityVerificationAttributes($identity) {
130 $from_email_domain_array = explode('@', $identity);
131 $from_email_domain = $from_email_domain_array[1];
132
133 $rest = new SimpleEmailServiceRequest($this, 'POST');
134 $rest->setParameter('Action', 'GetIdentityVerificationAttributes');
135 $rest->setParameter('Identities.member.1', $identity);
136 $rest->setParameter('Identities.member.2', $from_email_domain);
137
138 $rest = $rest->getResponse();
139 if($rest->error === false && $rest->code !== 200) {
140 $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
141 }
142 if($rest->error !== false) {
143 $this->__triggerError('GetIdentityVerificationAttributes', $rest->error);
144 return false;
145 }
146
147 $response = array();
148 if(!isset($rest->body)) {
149 return $response;
150 }
151
152 $statuses = array();
153 foreach($rest->body->GetIdentityVerificationAttributesResult->VerificationAttributes->entry as $entry) {
154 $statuses[] = (string)$entry->value->VerificationStatus;
155 }
156
157 $response['VerificationStatus'] = $statuses;
158 $response['RequestId'] = (string)$rest->body->ResponseMetadata->RequestId;
159
160 return $response;
161 }
162
163 /**
164 * Requests verification of the provided email address, so it can be used
165 * as the 'From' address when sending emails through SimpleEmailService.
166 *
167 * After submitting this request, you should receive a verification email
168 * from Amazon at the specified address containing instructions to follow.
169 *
170 * @param string email The email address to get verified
171 * @return The request id for this request.
172 */
173 public function verifyEmailAddress($email) {
174 $rest = new SimpleEmailServiceRequest($this, 'POST');
175 $rest->setParameter('Action', 'VerifyEmailAddress');
176 $rest->setParameter('EmailAddress', $email);
177
178 $rest = $rest->getResponse();
179 if($rest->error === false && $rest->code !== 200) {
180 $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
181 }
182 if($rest->error !== false) {
183 $this->__triggerError('verifyEmailAddress', $rest->error);
184 return false;
185 }
186
187 $response['RequestId'] = (string)$rest->body->ResponseMetadata->RequestId;
188 return $response;
189 }
190
191 /**
192 * Removes the specified email address from the list of verified addresses.
193 *
194 * @param string email The email address to remove
195 * @return The request id for this request.
196 */
197 public function deleteVerifiedEmailAddress($email) {
198 $rest = new SimpleEmailServiceRequest($this, 'DELETE');
199 $rest->setParameter('Action', 'DeleteVerifiedEmailAddress');
200 $rest->setParameter('EmailAddress', $email);
201
202 $rest = $rest->getResponse();
203 if($rest->error === false && $rest->code !== 200) {
204 $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
205 }
206 if($rest->error !== false) {
207 $this->__triggerError('deleteVerifiedEmailAddress', $rest->error);
208 return false;
209 }
210
211 $response['RequestId'] = (string)$rest->body->ResponseMetadata->RequestId;
212 return $response;
213 }
214
215 /**
216 * Given an identity (an email address or a domain), sets the Amazon Simple Notification Service (Amazon SNS) topic to which Amazon SES will publish bounce, complaint, and/or delivery notifications for emails sent with that identity as the Source..
217 *
218 */
219 public function SetIdentityNotificationTopic($identity, $sns_topic, $notification_type) {
220 $rest = new SimpleEmailServiceRequest($this, 'POST');
221 $rest->setParameter('Action', 'SetIdentityNotificationTopic');
222 $rest->setParameter('Identity', $identity);
223 $rest->setParameter('SnsTopic', $sns_topic);
224 $rest->setParameter('NotificationType', $notification_type);
225
226 $rest = $rest->getResponse();
227 if($rest->error === false && $rest->code !== 200) {
228 $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
229 }
230 if($rest->error !== false) {
231 $this->__triggerError('SetIdentityNotificationTopic', $rest->error);
232 return false;
233 }
234
235 $response['RequestId'] = (string)$rest->body->ResponseMetadata->RequestId;
236 return $response;
237 }
238
239 /**
240 * Retrieves information on the current activity limits for this account.
241 * See http://docs.amazonwebservices.com/ses/latest/APIReference/API_GetSendQuota.html
242 *
243 * @return An array containing information on this account's activity limits.
244 */
245 public function getSendQuota() {
246 $rest = new SimpleEmailServiceRequest($this, 'GET');
247 $rest->setParameter('Action', 'GetSendQuota');
248
249 $rest = $rest->getResponse();
250 if($rest->error === false && $rest->code !== 200) {
251 $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
252 }
253 if($rest->error !== false) {
254 $this->__triggerError('getSendQuota', $rest->error);
255 $err_code = $rest->error['Error']['Code'];
256 return $err_code;
257 }
258
259 $response = array();
260 if(!isset($rest->body)) {
261 return $response;
262 }
263
264 $response['Max24HourSend'] = (string)$rest->body->GetSendQuotaResult->Max24HourSend;
265 $response['MaxSendRate'] = (string)$rest->body->GetSendQuotaResult->MaxSendRate;
266 $response['SentLast24Hours'] = (string)$rest->body->GetSendQuotaResult->SentLast24Hours;
267 $response['RequestId'] = (string)$rest->body->ResponseMetadata->RequestId;
268
269 return $response;
270 }
271
272 /**
273 * Retrieves statistics for the last two weeks of activity on this account.
274 * See http://docs.amazonwebservices.com/ses/latest/APIReference/API_GetSendStatistics.html
275 *
276 * @return An array of activity statistics. Each array item covers a 15-minute period.
277 */
278 public function getSendStatistics() {
279 $rest = new SimpleEmailServiceRequest($this, 'GET');
280 $rest->setParameter('Action', 'GetSendStatistics');
281
282 $rest = $rest->getResponse();
283 if($rest->error === false && $rest->code !== 200) {
284 $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
285 }
286 if($rest->error !== false) {
287 $this->__triggerError('getSendStatistics', $rest->error);
288 return false;
289 }
290
291 $response = array();
292 if(!isset($rest->body)) {
293 return $response;
294 }
295
296 $datapoints = array();
297 foreach($rest->body->GetSendStatisticsResult->SendDataPoints->member as $datapoint) {
298 $p = array();
299 $p['Bounces'] = (string)$datapoint->Bounces;
300 $p['Complaints'] = (string)$datapoint->Complaints;
301 $p['DeliveryAttempts'] = (string)$datapoint->DeliveryAttempts;
302 $p['Rejects'] = (string)$datapoint->Rejects;
303 $p['Timestamp'] = (string)$datapoint->Timestamp;
304
305 $datapoints[] = $p;
306 }
307
308 $response['SendDataPoints'] = $datapoints;
309 $response['RequestId'] = (string)$rest->body->ResponseMetadata->RequestId;
310
311 return $response;
312 }
313
314 /**
315 * Retrieves statistics for the last two weeks of activity on this account.
316 * See http://docs.amazonwebservices.com/ses/latest/APIReference/API_GetSendStatistics.html
317 *
318 * @return An array of activity statistics. Each array item covers a 15-minute period.
319 */
320 public function setIdentityFeedbackForwardingEnabled($from_email, $val) {
321 $rest = new SimpleEmailServiceRequest($this, 'GET');
322 $rest->setParameter('Action', 'SetIdentityFeedbackForwardingEnabled');
323 $rest->setParameter('ForwardingEnabled', $val);
324 $rest->setParameter('Identity', $from_email);
325
326 $rest = $rest->getResponse();
327 /*
328 if($rest->error === false && $rest->code !== 200) {
329 $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
330 }
331 if($rest->error !== false) {
332 $this->__triggerError('SetIdentityFeedbackForwardingEnabled', $rest->error);
333 return false;
334 }
335 */
336
337 $response = array();
338 if(!isset($rest->body)) {
339 return $response;
340 }
341
342 return $response;
343 }
344
345
346 /**
347 * Given a SimpleEmailServiceMessage object, submits the message to the service for sending.
348 *
349 * @return An array containing the unique identifier for this message and a separate request id.
350 * Returns false if the provided message is missing any required fields.
351 */
352 public function sendEmail($sesMessage) {
353 if(!$sesMessage->validate()) {
354 $this->__triggerError('sendEmail', 'Message failed validation.');
355 return false;
356 }
357
358 $rest = new SimpleEmailServiceRequest($this, 'POST');
359 $rest->setParameter('Action', 'SendEmail');
360
361 $i = 1;
362 foreach($sesMessage->to as $to) {
363 $rest->setParameter('Destination.ToAddresses.member.'.$i, $to);
364 $i++;
365 }
366
367 if(is_array($sesMessage->cc)) {
368 $i = 1;
369 foreach($sesMessage->cc as $cc) {
370 $rest->setParameter('Destination.CcAddresses.member.'.$i, $cc);
371 $i++;
372 }
373 }
374
375 if(is_array($sesMessage->bcc)) {
376 $i = 1;
377 foreach($sesMessage->bcc as $bcc) {
378 $rest->setParameter('Destination.BccAddresses.member.'.$i, $bcc);
379 $i++;
380 }
381 }
382
383 if(is_array($sesMessage->replyto)) {
384 $i = 1;
385 foreach($sesMessage->replyto as $replyto) {
386 $rest->setParameter('ReplyToAddresses.member.'.$i, $replyto);
387 $i++;
388 }
389 }
390
391 $rest->setParameter('Source', $sesMessage->from);
392
393 if($sesMessage->returnpath != null) {
394 $rest->setParameter('ReturnPath', $sesMessage->returnpath);
395 }
396
397 if($sesMessage->subject != null && strlen($sesMessage->subject) > 0) {
398 $rest->setParameter('Message.Subject.Data', $sesMessage->subject);
399 if($sesMessage->subjectCharset != null && strlen($sesMessage->subjectCharset) > 0) {
400 $rest->setParameter('Message.Subject.Charset', $sesMessage->subjectCharset);
401 }
402 }
403
404
405 if($sesMessage->messagetext != null && strlen($sesMessage->messagetext) > 0) {
406 $rest->setParameter('Message.Body.Text.Data', $sesMessage->messagetext);
407 if($sesMessage->messageTextCharset != null && strlen($sesMessage->messageTextCharset) > 0) {
408 $rest->setParameter('Message.Body.Text.Charset', $sesMessage->messageTextCharset);
409 }
410 }
411
412 if($sesMessage->messagehtml != null && strlen($sesMessage->messagehtml) > 0) {
413 $rest->setParameter('Message.Body.Html.Data', $sesMessage->messagehtml);
414 if($sesMessage->messageHtmlCharset != null && strlen($sesMessage->messageHtmlCharset) > 0) {
415 $rest->setParameter('Message.Body.Html.Charset', $sesMessage->messageHtmlCharset);
416 }
417 }
418
419 $rest = $rest->getResponse();
420 if($rest->error === false && $rest->code !== 200) {
421 $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
422 }
423 if($rest->error !== false) {
424 $this->__triggerError('sendEmail', $rest->error);
425 return false;
426 }
427
428 $response['MessageId'] = (string)$rest->body->SendEmailResult->MessageId;
429 $response['RequestId'] = (string)$rest->body->ResponseMetadata->RequestId;
430 return $response;
431 }
432
433 /**
434 * Trigger an error message
435 *
436 * @internal Used by member functions to output errors
437 * @param array $error Array containing error information
438 * @return string
439 */
440 public function __triggerError($functionname, $error)
441 {
442 if($error == false) {
443 trigger_error(sprintf("SimpleEmailService::%s(): Encountered an error, but no description given", $functionname), E_USER_WARNING);
444 }
445 else if(isset($error['curl']) && $error['curl'])
446 {
447 trigger_error(sprintf("SimpleEmailService::%s(): %s %s", $functionname, $error['code'], $error['message']), E_USER_WARNING);
448 }
449 else if(isset($error['Error']))
450 {
451 $e = $error['Error'];
452 $message = sprintf("SimpleEmailService::%s(): %s - %s: %s\nRequest Id: %s\n", $functionname, $e['Type'], $e['Code'], $e['Message'], $error['RequestId']);
453 trigger_error($message, E_USER_WARNING);
454 }
455 else {
456 trigger_error(sprintf("SimpleEmailService::%s(): Encountered an error: %s", $functionname, $error), E_USER_WARNING);
457 }
458 }
459}
460
461final class SimpleEmailServiceRequest
462{
463 private $ses, $verb, $parameters = array();
464 public $response;
465
466 /**
467 * Constructor
468 *
469 * @param string $ses The SimpleEmailService object making this request
470 * @param string $action action
471 * @param string $verb HTTP verb
472 * @return mixed
473 */
474 function __construct($ses, $verb) {
475 $this->ses = $ses;
476 $this->verb = $verb;
477 $this->response = new STDClass;
478 $this->response->error = false;
479 }
480
481 /**
482 * Set request parameter
483 *
484 * @param string $key Key
485 * @param string $value Value
486 * @param boolean $replace Whether to replace the key if it already exists (default true)
487 * @return void
488 */
489 public function setParameter($key, $value, $replace = true) {
490 if(!$replace && isset($this->parameters[$key]))
491 {
492 $temp = (array)($this->parameters[$key]);
493 $temp[] = $value;
494 $this->parameters[$key] = $temp;
495 }
496 else
497 {
498 $this->parameters[$key] = $value;
499 }
500 }
501
502 /**
503 * Get the response
504 *
505 * @return object | false
506 */
507 public function getResponse() {
508
509 $params = array();
510 foreach ($this->parameters as $var => $value)
511 {
512 if(is_array($value))
513 {
514 foreach($value as $v)
515 {
516 $params[] = $var.'='.$this->__customUrlEncode($v);
517 }
518 }
519 else
520 {
521 $params[] = $var.'='.$this->__customUrlEncode($value);
522 }
523 }
524
525 sort($params, SORT_STRING);
526
527 // must be in format 'Sun, 06 Nov 1994 08:49:37 GMT'
528 $date = gmdate('D, d M Y H:i:s e');
529
530 $query = implode('&', $params);
531
532 $headers = array();
533 $headers[] = 'Date: '.$date;
534 $headers[] = 'Host: '.$this->ses->getHost();
535
536 $auth = 'AWS3-HTTPS AWSAccessKeyId='.$this->ses->getAccessKey();
537 $auth .= ',Algorithm=HmacSHA256,Signature='.$this->__getSignature($date);
538 $headers[] = 'X-Amzn-Authorization: '.$auth;
539
540 $url = 'https://'.$this->ses->getHost().'/';
541
542 // Basic setup
543 $curl = curl_init();
544 curl_setopt($curl, CURLOPT_USERAGENT, 'SimpleEmailService/php');
545
546 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, ($this->ses->verifyHost() ? 2 : 0));
547 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, ($this->ses->verifyPeer() ? 1 : 0));
548
549 // Request types
550 switch ($this->verb) {
551 case 'GET':
552 $url .= '?'.$query;
553 break;
554 case 'POST':
555 curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $this->verb);
556 curl_setopt($curl, CURLOPT_POSTFIELDS, $query);
557 $headers[] = 'Content-Type: application/x-www-form-urlencoded';
558 break;
559 case 'DELETE':
560 $url .= '?'.$query;
561 curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
562 break;
563 default: break;
564 }
565 curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
566 curl_setopt($curl, CURLOPT_HEADER, false);
567
568 curl_setopt($curl, CURLOPT_URL, $url);
569 curl_setopt($curl, CURLOPT_RETURNTRANSFER, false);
570 curl_setopt($curl, CURLOPT_WRITEFUNCTION, array(&$this, '__responseWriteCallback'));
571 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
572
573 // Execute, grab errors
574 if (curl_exec($curl)) {
575 $this->response->code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
576 } else {
577 $this->response->error = array(
578 'curl' => true,
579 'code' => curl_errno($curl),
580 'message' => curl_error($curl),
581 'resource' => $this->resource
582 );
583 }
584
585 @curl_close($curl);
586
587 // Parse body into XML
588 if ($this->response->error === false && isset($this->response->body)) {
589 $this->response->body = simplexml_load_string($this->response->body);
590
591 // Grab SES errors
592 if (!in_array($this->response->code, array(200, 201, 202, 204))
593 && isset($this->response->body->Error)) {
594 $error = $this->response->body->Error;
595 $output = array();
596 $output['curl'] = false;
597 $output['Error'] = array();
598 $output['Error']['Type'] = (string)$error->Type;
599 $output['Error']['Code'] = (string)$error->Code;
600 $output['Error']['Message'] = (string)$error->Message;
601 $output['RequestId'] = (string)$this->response->body->RequestId;
602
603 $this->response->error = $output;
604 unset($this->response->body);
605 }
606 }
607
608 return $this->response;
609 }
610
611 /**
612 * CURL write callback
613 *
614 * @param resource &$curl CURL resource
615 * @param string &$data Data
616 * @return integer
617 */
618 private function __responseWriteCallback(&$curl, &$data) {
619 $this->response->body .= $data;
620 return strlen($data);
621 }
622
623 /**
624 * Contributed by afx114
625 * URL encode the parameters as per http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/index.html?Query_QueryAuth.html
626 * PHP's rawurlencode() follows RFC 1738, not RFC 3986 as required by Amazon. The only difference is the tilde (~), so convert it back after rawurlencode
627 * See: http://www.morganney.com/blog/API/AWS-Product-Advertising-API-Requires-a-Signed-Request.php
628 *
629 * @param string $var String to encode
630 * @return string
631 */
632 private function __customUrlEncode($var) {
633 return str_replace('%7E', '~', rawurlencode($var));
634 }
635
636 /**
637 * Generate the auth string using Hmac-SHA256
638 *
639 * @internal Used by SimpleDBRequest::getResponse()
640 * @param string $string String to sign
641 * @return string
642 */
643 private function __getSignature($string) {
644 return base64_encode(hash_hmac('sha256', $string, $this->ses->getSecretKey(), true));
645 }
646}
647
648
649final class SimpleEmailServiceMessage {
650
651 // these are public for convenience only
652 // these are not to be used outside of the SimpleEmailService class!
653 public $to, $cc, $bcc, $replyto;
654 public $from, $returnpath;
655 public $subject, $messagetext, $messagehtml;
656 public $subjectCharset, $messageTextCharset, $messageHtmlCharset;
657
658 function __construct() {
659 $this->to = array();
660 $this->cc = array();
661 $this->bcc = array();
662 $this->replyto = array();
663
664 $this->from = null;
665 $this->returnpath = null;
666
667 $this->subject = null;
668 $this->messagetext = null;
669 $this->messagehtml = null;
670
671 $this->subjectCharset = null;
672 $this->messageTextCharset = null;
673 $this->messageHtmlCharset = null;
674 }
675
676
677 /**
678 * addTo, addCC, addBCC, and addReplyTo have the following behavior:
679 * If a single address is passed, it is appended to the current list of addresses.
680 * If an array of addresses is passed, that array is merged into the current list.
681 */
682 function addTo($to) {
683 if(!is_array($to)) {
684 $this->to[] = $to;
685 }
686 else {
687 $this->to = array_merge($this->to, $to);
688 }
689 }
690
691 function addCC($cc) {
692 if(!is_array($cc)) {
693 $this->cc[] = $cc;
694 }
695 else {
696 $this->cc = array_merge($this->cc, $cc);
697 }
698 }
699
700 function addBCC($bcc) {
701 if(!is_array($bcc)) {
702 $this->bcc[] = $bcc;
703 }
704 else {
705 $this->bcc = array_merge($this->bcc, $bcc);
706 }
707 }
708
709 function addReplyTo($replyto) {
710 if(!is_array($replyto)) {
711 $this->replyto[] = $replyto;
712 }
713 else {
714 $this->replyto = array_merge($this->replyto, $replyto);
715 }
716 }
717
718 function setFrom($from) {
719 $this->from = $from;
720 }
721
722 function setReturnPath($returnpath) {
723 $this->returnpath = $returnpath;
724 }
725
726 function setSubject($subject) {
727 $this->subject = $subject;
728 }
729
730 function setSubjectCharset($charset) {
731 $this->subjectCharset = $charset;
732 }
733
734 function setMessageFromString($text, $html = null) {
735 $this->messagetext = $text;
736 $this->messagehtml = $html;
737 }
738
739 function setMessageFromFile($textfile, $htmlfile = null) {
740 if(file_exists($textfile) && is_file($textfile) && is_readable($textfile)) {
741 $this->messagetext = file_get_contents($textfile);
742 } else {
743 $this->messagetext = null;
744 }
745 if(file_exists($htmlfile) && is_file($htmlfile) && is_readable($htmlfile)) {
746 $this->messagehtml = file_get_contents($htmlfile);
747 } else {
748 $this->messagehtml = null;
749 }
750 }
751
752 function setMessageFromURL($texturl, $htmlurl = null) {
753 if($texturl !== null) {
754 $this->messagetext = file_get_contents($texturl);
755 } else {
756 $this->messagetext = null;
757 }
758 if($htmlurl !== null) {
759 $this->messagehtml = file_get_contents($htmlurl);
760 } else {
761 $this->messagehtml = null;
762 }
763 }
764
765 function setMessageCharset($textCharset, $htmlCharset = null) {
766 $this->messageTextCharset = $textCharset;
767 $this->messageHtmlCharset = $htmlCharset;
768 }
769
770 /**
771 * Validates whether the message object has sufficient information to submit a request to SES.
772 * This does not guarantee the message will arrive, nor that the request will succeed;
773 * instead, it makes sure that no required fields are missing.
774 *
775 * This is used internally before attempting a SendEmail or SendRawEmail request,
776 * but it can be used outside of this file if verification is desired.
777 * May be useful if e.g. the data is being populated from a form; developers can generally
778 * use this function to verify completeness instead of writing custom logic.
779 *
780 * @return boolean
781 */
782 public function validate() {
783 if(count($this->to) == 0)
784 return false;
785 if($this->from == null || strlen($this->from) == 0)
786 return false;
787 // messages require at least one of: subject, messagetext, messagehtml.
788 if(($this->subject == null || strlen($this->subject) == 0)
789 && ($this->messagetext == null || strlen($this->messagetext) == 0)
790 && ($this->messagehtml == null || strlen($this->messagehtml) == 0))
791 {
792 return false;
793 }
794
795 return true;
796 }
797}