2 /*~ class.phpmailer-lite.php
3 .---------------------------------------------------------------------------.
4 | Software: PHPMailer Lite - PHP email class |
6 | Contact: via sourceforge.net support pages (also www.codeworxtech.com) |
7 | Info: http://phpmailer.sourceforge.net |
8 | Support: http://sourceforge.net/projects/phpmailer/ |
9 | ------------------------------------------------------------------------- |
10 | Admin: Andy Prevost (project admininistrator) |
11 | Authors: Andy Prevost (codeworxtech) codeworxtech@users.sourceforge.net |
12 | : Marcus Bointon (coolbru) coolbru@users.sourceforge.net |
13 | Founder: Brent R. Matzelle (original founder) |
14 | Copyright (c) 2004-2009, Andy Prevost. All Rights Reserved. |
15 | Copyright (c) 2001-2003, Brent R. Matzelle |
16 | ------------------------------------------------------------------------- |
17 | License: Distributed under the Lesser General Public License (LGPL) |
18 | http://www.gnu.org/copyleft/lesser.html |
19 | This program is distributed in the hope that it will be useful - WITHOUT |
20 | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
21 | FITNESS FOR A PARTICULAR PURPOSE. |
22 | ------------------------------------------------------------------------- |
23 | We offer a number of paid services (www.codeworxtech.com): |
24 | - Web Hosting on highly optimized fast and secure servers |
25 | - Technology Consulting |
26 | - Oursourcing (highly qualified programmers and graphic designers) |
27 '---------------------------------------------------------------------------'
31 * PHPMailer Lite - PHP email transport class
32 * NOTE: Requires PHP version 5 or later
33 * @package PHPMailer Lite
34 * @author Andy Prevost
35 * @author Marcus Bointon
36 * @copyright 2004 - 2009 Andy Prevost
37 * @version $Id: class.phpmailer-lite.php 447 2009-09-12 13:21:38Z codeworxtech $
38 * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
41 if (version_compare(PHP_VERSION
, '5.0.0', '<') ) exit("Sorry, this version of PHPMailer will only run on PHP version 5 or greater!\n");
45 public static function newFromMessage(
46 PhabricatorMailExternalMessage
$message) {
48 $mailer = new self($use_exceptions = true);
50 // By default, PHPMailerLite sends one mail per recipient. We handle
51 // combining or separating To and Cc higher in the stack, so tell it to
52 // send mail exactly like we ask.
53 $mailer->SingleTo
= false;
55 $mailer->CharSet
= 'utf-8';
56 $mailer->Encoding
= 'base64';
58 $subject = $message->getSubject();
59 if ($subject !== null) {
60 $mailer->Subject
= $subject;
63 $from_address = $message->getFromAddress();
66 $from_address->getAddress(),
67 (string)$from_address->getDisplayName(),
68 $crazy_side_effects = false);
71 $reply_address = $message->getReplyToAddress();
74 $reply_address->getAddress(),
75 (string)$reply_address->getDisplayName());
78 $to_addresses = $message->getToAddresses();
80 foreach ($to_addresses as $address) {
82 $address->getAddress(),
83 (string)$address->getDisplayName());
87 $cc_addresses = $message->getCCAddresses();
89 foreach ($cc_addresses as $address) {
91 $address->getAddress(),
92 (string)$address->getDisplayName());
96 $headers = $message->getHeaders();
98 foreach ($headers as $header) {
99 $name = $header->getName();
100 $value = $header->getValue();
102 if (phutil_utf8_strtolower($name) === 'message-id') {
103 $mailer->MessageID
= $value;
105 $mailer->AddCustomHeader("{$name}: {$value}");
110 $attachments = $message->getAttachments();
112 foreach ($attachments as $attachment) {
113 $mailer->AddStringAttachment(
114 $attachment->getData(),
115 $attachment->getFilename(),
117 $attachment->getMimeType());
121 $text_body = $message->getTextBody();
122 if ($text_body !== null) {
123 $mailer->Body
= $text_body;
126 $html_body = $message->getHTMLBody();
127 if ($html_body !== null) {
128 $mailer->IsHTML(true);
129 $mailer->Body
= $html_body;
130 if ($text_body !== null) {
131 $mailer->AltBody
= $text_body;
141 /////////////////////////////////////////////////
142 // PROPERTIES, PUBLIC
143 /////////////////////////////////////////////////
146 * Email priority (1 = High, 3 = Normal, 5 = low).
149 public $Priority = 3;
152 * Sets the CharSet of the message.
155 public $CharSet = 'iso-8859-1';
158 * Sets the Content-type of the message.
161 public $ContentType = 'text/plain';
164 * Sets the Encoding of the message. Options for this are
165 * "8bit", "7bit", "binary", "base64", and "quoted-printable".
168 public $Encoding = '8bit';
171 * Holds the most recent mailer error message.
174 public $ErrorInfo = '';
177 * Sets the From email address for the message.
180 public $From = 'root@localhost';
183 * Sets the From name of the message.
186 public $FromName = 'Root User';
189 * Sets the Sender email (Return-Path) of the message. If not empty,
190 * will be sent via -f to sendmail
196 * Sets the Subject of the message.
199 public $Subject = '';
202 * Sets the Body of the message. This can be either an HTML or text body.
203 * If HTML then run IsHTML(true).
209 * Sets the text-only body of the message. This automatically sets the
210 * email to multipart/alternative. This body can be read by mail
211 * clients that do not have HTML email capability such as mutt. Clients
212 * that can read HTML will view the normal Body.
215 public $AltBody = '';
218 * Sets word wrapping on the body of the message to a given number of
222 public $WordWrap = 0;
225 * Method to send mail: ("mail", or "sendmail").
228 public $Mailer = 'sendmail';
231 * Sets the path of the sendmail program.
234 public $Sendmail = '/usr/sbin/sendmail';
237 * Sets the email address that a reading confirmation will be sent.
240 public $ConfirmReadingTo = '';
243 * Sets the hostname to use in Message-Id and Received headers
244 * and as default HELO string. If empty, the value returned
245 * by SERVER_NAME is used or 'localhost.localdomain'.
248 public $Hostname = '';
251 * Sets the message ID to be used in the Message-Id header.
252 * If empty, a unique id will be generated.
255 public $MessageID = '';
258 * Provides the ability to have the TO field process individual
259 * emails, instead of sending to entire TO addresses
262 public $SingleTo = true;
265 * If SingleTo is true, this provides the array to hold the email addresses
268 public $SingleToArray = array();
271 * Provides the ability to change the line ending
277 * Used with DKIM DNS Resource Record
280 public $DKIM_selector = 'phpmailer';
283 * Used with DKIM DNS Resource Record
284 * optional, in format of email address 'you@yourdomain.com'
287 public $DKIM_identity = '';
290 * Used with DKIM DNS Resource Record
291 * required, in format of base domain 'yourdomain.com'
294 public $DKIM_domain = '';
297 * Used with DKIM Digital Signing process
301 public $DKIM_passphrase = '';
304 * Used with DKIM DNS Resource Record
305 * required, private key (read from /.htprivkey)
308 public $DKIM_private = '';
311 * Callback Action function name
312 * the function that handles the result of the send email action. Parameters:
313 * bool $result result of the send action
314 * string $to email address of the recipient
315 * string $cc cc email addresses
316 * string $bcc bcc email addresses
317 * string $subject the subject
318 * string $body the email body
321 public $action_function = ''; //'callbackAction';
324 * Sets the PHPMailer Version number
327 public $Version = 'Lite 5.1';
329 /////////////////////////////////////////////////
330 // PROPERTIES, PRIVATE AND PROTECTED
331 /////////////////////////////////////////////////
333 private $to = array();
334 private $cc = array();
335 private $bcc = array();
336 private $ReplyTo = array();
337 private $all_recipients = array();
338 private $attachment = array();
339 private $CustomHeader = array();
340 private $message_type = '';
341 private $boundary = array();
342 protected $language = array();
343 private $error_count = 0;
344 private $sign_cert_file = "";
345 private $sign_key_file = "";
346 private $sign_key_pass = "";
347 private $exceptions = false;
349 /////////////////////////////////////////////////
351 /////////////////////////////////////////////////
353 const STOP_MESSAGE
= 0; // message only, continue processing
354 const STOP_CONTINUE
= 1; // message?, likely ok to continue processing
355 const STOP_CRITICAL
= 2; // message, plus full stop, critical error reached
357 /////////////////////////////////////////////////
358 // METHODS, VARIABLES
359 /////////////////////////////////////////////////
363 * @param boolean $exceptions Should we throw external exceptions?
365 public function __construct($exceptions = false) {
366 $this->exceptions
= ($exceptions == true);
370 * Sets message type to HTML.
371 * @param bool $ishtml
374 public function IsHTML($ishtml = true) {
376 $this->ContentType
= 'text/html';
378 $this->ContentType
= 'text/plain';
383 * Sets Mailer to send message using PHP mail() function.
386 public function IsMail() {
387 $this->Mailer
= 'mail';
391 * Sets Mailer to send message using the $Sendmail program.
394 public function IsSendmail() {
395 if (!stristr(ini_get('sendmail_path'), 'sendmail')) {
396 $this->Sendmail
= '/var/qmail/bin/sendmail';
398 $this->Mailer
= 'sendmail';
402 * Sets Mailer to send message using the qmail MTA.
405 public function IsQmail() {
406 if (stristr(ini_get('sendmail_path'), 'qmail')) {
407 $this->Sendmail
= '/var/qmail/bin/sendmail';
409 $this->Mailer
= 'sendmail';
412 /////////////////////////////////////////////////
413 // METHODS, RECIPIENTS
414 /////////////////////////////////////////////////
417 * Adds a "To" address.
418 * @param string $address
419 * @param string $name
420 * @return boolean true on success, false if address already used
422 public function AddAddress($address, $name = '') {
423 return $this->AddAnAddress('to', $address, $name);
427 * Adds a "Cc" address.
428 * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer.
429 * @param string $address
430 * @param string $name
431 * @return boolean true on success, false if address already used
433 public function AddCC($address, $name = '') {
434 return $this->AddAnAddress('cc', $address, $name);
438 * Adds a "Bcc" address.
439 * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer.
440 * @param string $address
441 * @param string $name
442 * @return boolean true on success, false if address already used
444 public function AddBCC($address, $name = '') {
445 return $this->AddAnAddress('bcc', $address, $name);
449 * Adds a "Reply-to" address.
450 * @param string $address
451 * @param string $name
454 public function AddReplyTo($address, $name = '') {
455 return $this->AddAnAddress('ReplyTo', $address, $name);
459 * Adds an address to one of the recipient arrays
460 * Addresses that have been added already return false, but do not throw exceptions
461 * @param string $kind One of 'to', 'cc', 'bcc', 'ReplyTo'
462 * @param string $address The email address to send to
463 * @param string $name
464 * @return boolean true on success, false if address already used or invalid in some way
467 private function AddAnAddress($kind, $address, $name = '') {
468 if (!preg_match('/^(to|cc|bcc|ReplyTo)$/', $kind)) {
469 echo 'Invalid recipient array: ' . $kind;
472 $address = trim($address);
473 $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
474 if (!self
::ValidateAddress($address)) {
475 $this->SetError($this->Lang('invalid_address').': '. $address);
476 if ($this->exceptions
) {
477 throw new phpmailerException($this->Lang('invalid_address').': '.$address);
479 echo $this->Lang('invalid_address').': '.$address;
482 if ($kind != 'ReplyTo') {
483 if (!isset($this->all_recipients
[strtolower($address)])) {
484 array_push($this->$kind, array($address, $name));
485 $this->all_recipients
[strtolower($address)] = true;
489 if (!array_key_exists(strtolower($address), $this->ReplyTo
)) {
490 $this->ReplyTo
[strtolower($address)] = array($address, $name);
498 * Set the From and FromName properties
499 * @param string $address
500 * @param string $name
503 public function SetFrom($address, $name = '',$auto=1) {
504 $address = trim($address);
505 $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
506 if (!self
::ValidateAddress($address)) {
507 $this->SetError($this->Lang('invalid_address').': '. $address);
508 if ($this->exceptions
) {
509 throw new phpmailerException($this->Lang('invalid_address').': '.$address);
511 echo $this->Lang('invalid_address').': '.$address;
514 $this->From
= $address;
515 $this->FromName
= $name;
517 if (empty($this->ReplyTo
)) {
518 $this->AddAnAddress('ReplyTo', $address, $name);
520 if (empty($this->Sender
)) {
521 $this->Sender
= $address;
528 * Check that a string looks roughly like an email address should
529 * Static so it can be used without instantiation
530 * Tries to use PHP built-in validator in the filter extension (from PHP 5.2), falls back to a reasonably competent regex validator
531 * Conforms approximately to RFC2822
532 * @link http://www.hexillion.com/samples/#Regex Original pattern found here
533 * @param string $address The email address to check
538 public static function ValidateAddress($address) {
539 if (function_exists('filter_var')) { //Introduced in PHP 5.2
540 if(filter_var($address, FILTER_VALIDATE_EMAIL
) === FALSE) {
546 return preg_match('/^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!\.)){0,61}[a-zA-Z0-9_-]?\.)+[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!$)){0,61}[a-zA-Z0-9_]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/', $address);
550 /////////////////////////////////////////////////
551 // METHODS, MAIL SENDING
552 /////////////////////////////////////////////////
555 * Creates message and assigns Mailer. If the message is
556 * not sent successfully then it returns false. Use the ErrorInfo
557 * variable to view description of the error.
560 public function Send() {
562 if ((count($this->to
) +
count($this->cc
) +
count($this->bcc
)) < 1) {
563 throw new phpmailerException($this->Lang('provide_address'), self
::STOP_CRITICAL
);
566 // Set whether the message is multipart/alternative
567 if(!empty($this->AltBody
)) {
568 $this->ContentType
= 'multipart/alternative';
571 $this->error_count
= 0; // reset errors
572 $this->SetMessageType();
573 $header = $this->CreateHeader();
574 $body = $this->CreateBody();
576 if (empty($this->Body
)) {
577 throw new phpmailerException($this->Lang('empty_message'), self
::STOP_CRITICAL
);
580 // digitally sign with DKIM if enabled
581 if ($this->DKIM_domain
&& $this->DKIM_private
) {
582 $header_dkim = $this->DKIM_Add($header,$this->Subject
,$body);
583 $header = str_replace("\r\n","\n",$header_dkim) . $header;
586 // Choose the mailer and send through it
587 switch($this->Mailer
) {
590 return $this->customMailer
->executeSend(
595 $sendAction = $this->SendmailSend($header, $body);
598 $sendAction = $this->MailSend($header, $body);
602 } catch (phpmailerException
$e) {
603 $this->SetError($e->getMessage());
604 if ($this->exceptions
) {
607 echo $e->getMessage()."\n";
613 * Sends mail using the $Sendmail program.
614 * @param string $header The message headers
615 * @param string $body The message body
619 protected function SendmailSend($header, $body) {
620 if ($this->Sender
!= '') {
621 $sendmail = sprintf("%s -oi -f %s -t", escapeshellcmd($this->Sendmail
), escapeshellarg($this->Sender
));
623 $sendmail = sprintf("%s -oi -t", escapeshellcmd($this->Sendmail
));
626 if ($this->SingleTo
=== true) {
627 foreach ($this->SingleToArray
as $key => $val) {
628 $mail = new ExecFuture('%C', $sendmail);
629 $mail->write("To: {$val}\n", true);
630 $mail->write($header.$body);
634 $mail = new ExecFuture('%C', $sendmail);
635 $mail->write($header.$body);
643 * Sends mail using the PHP mail() function.
644 * @param string $header The message headers
645 * @param string $body The message body
649 protected function MailSend($header, $body) {
651 foreach($this->to
as $t) {
652 $toArr[] = $this->AddrFormat($t);
654 $to = implode(', ', $toArr);
656 $params = sprintf("-oi -f %s", $this->Sender
);
657 if ($this->Sender
!= '' && strlen(ini_get('safe_mode'))< 1) {
658 $old_from = ini_get('sendmail_from');
659 ini_set('sendmail_from', $this->Sender
);
660 if ($this->SingleTo
=== true && count($toArr) > 1) {
661 foreach ($toArr as $key => $val) {
662 $rt = @mail
($val, $this->EncodeHeader($this->SecureHeader($this->Subject
)), $body, $header, $params);
663 // implement call back function if it exists
664 $isSent = ($rt == 1) ?
1 : 0;
665 $this->doCallback($isSent,$val,$this->cc
,$this->bcc
,$this->Subject
,$body);
668 $rt = @mail
($to, $this->EncodeHeader($this->SecureHeader($this->Subject
)), $body, $header, $params);
669 // implement call back function if it exists
670 $isSent = ($rt == 1) ?
1 : 0;
671 $this->doCallback($isSent,$to,$this->cc
,$this->bcc
,$this->Subject
,$body);
674 if ($this->SingleTo
=== true && count($toArr) > 1) {
675 foreach ($toArr as $key => $val) {
676 $rt = @mail
($val, $this->EncodeHeader($this->SecureHeader($this->Subject
)), $body, $header, $params);
677 // implement call back function if it exists
678 $isSent = ($rt == 1) ?
1 : 0;
679 $this->doCallback($isSent,$val,$this->cc
,$this->bcc
,$this->Subject
,$body);
682 $rt = @mail
($to, $this->EncodeHeader($this->SecureHeader($this->Subject
)), $body, $header);
683 // implement call back function if it exists
684 $isSent = ($rt == 1) ?
1 : 0;
685 $this->doCallback($isSent,$to,$this->cc
,$this->bcc
,$this->Subject
,$body);
688 if (isset($old_from)) {
689 ini_set('sendmail_from', $old_from);
692 throw new phpmailerException($this->Lang('instantiate'), self
::STOP_CRITICAL
);
698 * Sets the language for all class error messages.
699 * Returns false if it cannot load the language file. The default language is English.
700 * @param string $langcode ISO 639-1 2-character language code (e.g. Portuguese: "br")
701 * @param string $lang_path Path to the language file directory
704 function SetLanguage($langcode = 'en', $lang_path = 'language/') {
705 //Define full set of translatable strings
706 $PHPMAILER_LANG = array(
707 'provide_address' => 'You must provide at least one recipient email address.',
708 'mailer_not_supported' => ' mailer is not supported.',
709 'execute' => 'Could not execute: ',
710 'instantiate' => 'Could not instantiate mail function.',
711 'from_failed' => 'The following From address failed: ',
712 'file_access' => 'Could not access file: ',
713 'file_open' => 'File Error: Could not open file: ',
714 'encoding' => 'Unknown encoding: ',
715 'signing' => 'Signing Error: ',
716 'empty_message' => 'Message body empty',
717 'invalid_address' => 'Invalid address',
718 'variable_set' => 'Cannot set or reset variable: '
720 //Overwrite language-specific strings. This way we'll never have missing translations - no more "language string failed to load"!
722 if ($langcode != 'en') { //There is no English translation file
723 $l = @include
$lang_path.'phpmailer.lang-'.$langcode.'.php';
725 $this->language
= $PHPMAILER_LANG;
726 return ($l == true); //Returns false if language not found
730 * Return the current array of language strings
733 public function GetTranslations() {
734 return $this->language
;
737 /////////////////////////////////////////////////
738 // METHODS, MESSAGE CREATION
739 /////////////////////////////////////////////////
742 * Creates recipient headers.
746 public function AddrAppend($type, $addr) {
747 $addr_str = $type . ': ';
748 $addresses = array();
749 foreach ($addr as $a) {
750 $addresses[] = $this->AddrFormat($a);
752 $addr_str .= implode(', ', $addresses);
753 $addr_str .= $this->LE
;
755 // NOTE: This is a narrow hack to fix an issue with 1000+ characters of
756 // recipients, described in T12372.
757 $addr_str = wordwrap($addr_str, 75, "\n ");
763 * Formats an address correctly.
767 public function AddrFormat($addr) {
768 if (empty($addr[1])) {
769 return $this->SecureHeader($addr[0]);
771 return $this->EncodeHeader($this->SecureHeader($addr[1]), 'phrase') . " <" . $this->SecureHeader($addr[0]) . ">";
776 * Wraps message for use with mailers that do not
777 * automatically perform wrapping and for quoted-printable.
778 * Original written by philippe.
779 * @param string $message The message to wrap
780 * @param integer $length The line length to wrap to
781 * @param boolean $qp_mode Whether to run in Quoted-Printable mode
785 public function WrapText($message, $length, $qp_mode = false) {
786 $soft_break = ($qp_mode) ?
sprintf(" =%s", $this->LE
) : $this->LE
;
787 // If utf-8 encoding is used, we will need to make sure we don't
788 // split multibyte characters when we wrap
789 $is_utf8 = (strtolower($this->CharSet
) == "utf-8");
791 $message = $this->FixEOL($message);
792 if (substr($message, -1) == $this->LE
) {
793 $message = substr($message, 0, -1);
796 $line = explode($this->LE
, $message);
798 for ($i=0 ;$i < count($line); $i++
) {
799 $line_part = explode(' ', $line[$i]);
801 for ($e = 0; $e<count($line_part); $e++
) {
802 $word = $line_part[$e];
803 if ($qp_mode and (strlen($word) > $length)) {
804 $space_left = $length - strlen($buf) - 1;
806 if ($space_left > 20) {
809 $len = $this->UTF8CharBoundary($word, $len);
810 } elseif (substr($word, $len - 1, 1) == "=") {
812 } elseif (substr($word, $len - 2, 1) == "=") {
815 $part = substr($word, 0, $len);
816 $word = substr($word, $len);
818 $message .= $buf . sprintf("=%s", $this->LE
);
820 $message .= $buf . $soft_break;
824 while (strlen($word) > 0) {
827 $len = $this->UTF8CharBoundary($word, $len);
828 } elseif (substr($word, $len - 1, 1) == "=") {
830 } elseif (substr($word, $len - 2, 1) == "=") {
833 $part = substr($word, 0, $len);
834 $word = substr($word, $len);
836 if (strlen($word) > 0) {
837 $message .= $part . sprintf("=%s", $this->LE
);
844 $buf .= ($e == 0) ?
$word : (' ' . $word);
846 if (strlen($buf) > $length and $buf_o != '') {
847 $message .= $buf_o . $soft_break;
852 $message .= $buf . $this->LE
;
859 * Finds last character boundary prior to maxLength in a utf-8
860 * quoted (printable) encoded string.
861 * Original written by Colin Brown.
863 * @param string $encodedText utf-8 QP text
864 * @param int $maxLength find last character boundary prior to this length
867 public function UTF8CharBoundary($encodedText, $maxLength) {
868 $foundSplitPos = false;
870 while (!$foundSplitPos) {
871 $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
872 $encodedCharPos = strpos($lastChunk, "=");
873 if ($encodedCharPos !== false) {
874 // Found start of encoded character byte within $lookBack block.
875 // Check the encoded byte value (the 2 chars after the '=')
876 $hex = substr($encodedText, $maxLength - $lookBack +
$encodedCharPos +
1, 2);
878 if ($dec < 128) { // Single byte character.
879 // If the encoded char was found at pos 0, it will fit
880 // otherwise reduce maxLength to start of the encoded char
881 $maxLength = ($encodedCharPos == 0) ?
$maxLength :
882 $maxLength - ($lookBack - $encodedCharPos);
883 $foundSplitPos = true;
884 } elseif ($dec >= 192) { // First byte of a multi byte character
885 // Reduce maxLength to split at start of character
886 $maxLength = $maxLength - ($lookBack - $encodedCharPos);
887 $foundSplitPos = true;
888 } elseif ($dec < 192) { // Middle byte of a multi byte character, look further back
892 // No encoded character found
893 $foundSplitPos = true;
900 * Set the body wrapping.
904 public function SetWordWrap() {
905 if($this->WordWrap
< 1) {
908 switch($this->message_type
) {
910 case 'alt_attachments':
911 $this->AltBody
= $this->WrapText($this->AltBody
, $this->WordWrap
);
914 $this->Body
= $this->WrapText($this->Body
, $this->WordWrap
);
920 * Assembles message header.
922 * @return string The assembled header
924 public function CreateHeader() {
927 // Set the boundaries
928 $uniq_id = md5(uniqid(time()));
929 $this->boundary
[1] = 'b1_' . $uniq_id;
930 $this->boundary
[2] = 'b2_' . $uniq_id;
932 $result .= $this->HeaderLine('Date', self
::RFCDate());
933 if($this->Sender
== '') {
934 $result .= $this->HeaderLine('Return-Path', trim($this->From
));
936 $result .= $this->HeaderLine('Return-Path', trim($this->Sender
));
939 // To be created automatically by mail()
940 if($this->Mailer
!= 'mail') {
941 if ($this->SingleTo
=== true) {
942 foreach($this->to
as $t) {
943 $this->SingleToArray
[] = $this->AddrFormat($t);
946 if(count($this->to
) > 0) {
947 $result .= $this->AddrAppend('To', $this->to
);
948 } elseif (count($this->cc
) == 0) {
949 $result .= $this->HeaderLine('To', 'undisclosed-recipients:;');
955 $from[0][0] = trim($this->From
);
956 $from[0][1] = $this->FromName
;
957 $result .= $this->AddrAppend('From', $from);
959 // sendmail and mail() extract Cc from the header before sending
960 if(count($this->cc
) > 0) {
961 $result .= $this->AddrAppend('Cc', $this->cc
);
964 // sendmail and mail() extract Bcc from the header before sending
965 if(count($this->bcc
) > 0) {
966 $result .= $this->AddrAppend('Bcc', $this->bcc
);
969 if(count($this->ReplyTo
) > 0) {
970 $result .= $this->AddrAppend('Reply-to', $this->ReplyTo
);
973 // mail() sets the subject itself
974 if($this->Mailer
!= 'mail') {
975 $result .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader($this->Subject
)));
978 if($this->MessageID
!= '') {
979 $result .= $this->HeaderLine('Message-ID',$this->MessageID
);
981 $result .= sprintf("Message-ID: <%s@%s>%s", $uniq_id, $this->ServerHostname(), $this->LE
);
983 $result .= $this->HeaderLine('X-Priority', $this->Priority
);
985 if($this->ConfirmReadingTo
!= '') {
986 $result .= $this->HeaderLine('Disposition-Notification-To', '<' . trim($this->ConfirmReadingTo
) . '>');
989 // Add custom headers
990 for($index = 0; $index < count($this->CustomHeader
); $index++
) {
991 $result .= $this->HeaderLine(trim($this->CustomHeader
[$index][0]), $this->EncodeHeader(trim($this->CustomHeader
[$index][1])));
993 if (!$this->sign_key_file
) {
994 $result .= $this->HeaderLine('MIME-Version', '1.0');
995 $result .= $this->GetMailMIME();
1002 * Returns the message MIME.
1006 public function GetMailMIME() {
1008 switch($this->message_type
) {
1010 $result .= $this->HeaderLine('Content-Transfer-Encoding', $this->Encoding
);
1011 $result .= sprintf("Content-Type: %s; charset=\"%s\"", $this->ContentType
, $this->CharSet
);
1014 case 'alt_attachments':
1015 if($this->InlineImageExists()){
1016 $result .= sprintf("Content-Type: %s;%s\ttype=\"text/html\";%s\tboundary=\"%s\"%s", 'multipart/related', $this->LE
, $this->LE
, $this->boundary
[1], $this->LE
);
1018 $result .= $this->HeaderLine('Content-Type', 'multipart/mixed;');
1019 $result .= $this->TextLine("\tboundary=\"" . $this->boundary
[1] . '"');
1023 $result .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
1024 $result .= $this->TextLine("\tboundary=\"" . $this->boundary
[1] . '"');
1028 if($this->Mailer
!= 'mail') {
1029 $result .= $this->LE
.$this->LE
;
1036 * Assembles the message body. Returns an empty string on failure.
1038 * @return string The assembled message body
1040 public function CreateBody() {
1043 if ($this->sign_key_file
) {
1044 $body .= $this->GetMailMIME();
1047 $this->SetWordWrap();
1049 switch($this->message_type
) {
1051 $body .= $this->GetBoundary($this->boundary
[1], '', 'text/plain', '');
1052 $body .= $this->EncodeString($this->AltBody
, $this->Encoding
);
1053 $body .= $this->LE
.$this->LE
;
1054 $body .= $this->GetBoundary($this->boundary
[1], '', 'text/html', '');
1055 $body .= $this->EncodeString($this->Body
, $this->Encoding
);
1056 $body .= $this->LE
.$this->LE
;
1057 $body .= $this->EndBoundary($this->boundary
[1]);
1060 $body .= $this->EncodeString($this->Body
, $this->Encoding
);
1063 $body .= $this->GetBoundary($this->boundary
[1], '', '', '');
1064 $body .= $this->EncodeString($this->Body
, $this->Encoding
);
1066 $body .= $this->AttachAll();
1068 case 'alt_attachments':
1069 $body .= sprintf("--%s%s", $this->boundary
[1], $this->LE
);
1070 $body .= sprintf("Content-Type: %s;%s" . "\tboundary=\"%s\"%s", 'multipart/alternative', $this->LE
, $this->boundary
[2], $this->LE
.$this->LE
);
1071 $body .= $this->GetBoundary($this->boundary
[2], '', 'text/plain', '') . $this->LE
; // Create text body
1072 $body .= $this->EncodeString($this->AltBody
, $this->Encoding
);
1073 $body .= $this->LE
.$this->LE
;
1074 $body .= $this->GetBoundary($this->boundary
[2], '', 'text/html', '') . $this->LE
; // Create the HTML body
1075 $body .= $this->EncodeString($this->Body
, $this->Encoding
);
1076 $body .= $this->LE
.$this->LE
;
1077 $body .= $this->EndBoundary($this->boundary
[2]);
1078 $body .= $this->AttachAll();
1082 if ($this->IsError()) {
1084 } elseif ($this->sign_key_file
) {
1086 $file = tempnam('', 'mail');
1087 file_put_contents($file, $body); //TODO check this worked
1088 $signed = tempnam("", "signed");
1089 if (@openssl_pkcs7_sign
($file, $signed, "file://".$this->sign_cert_file
, array("file://".$this->sign_key_file
, $this->sign_key_pass
), NULL)) {
1092 $body = file_get_contents($signed);
1096 throw new phpmailerException($this->Lang("signing").openssl_error_string());
1098 } catch (phpmailerException
$e) {
1100 if ($this->exceptions
) {
1110 * Returns the start of a message boundary.
1113 private function GetBoundary($boundary, $charSet, $contentType, $encoding) {
1115 if($charSet == '') {
1116 $charSet = $this->CharSet
;
1118 if($contentType == '') {
1119 $contentType = $this->ContentType
;
1121 if($encoding == '') {
1122 $encoding = $this->Encoding
;
1124 $result .= $this->TextLine('--' . $boundary);
1125 $result .= sprintf("Content-Type: %s; charset = \"%s\"", $contentType, $charSet);
1126 $result .= $this->LE
;
1127 $result .= $this->HeaderLine('Content-Transfer-Encoding', $encoding);
1128 $result .= $this->LE
;
1134 * Returns the end of a message boundary.
1137 private function EndBoundary($boundary) {
1138 return $this->LE
. '--' . $boundary . '--' . $this->LE
;
1142 * Sets the message type.
1146 private function SetMessageType() {
1147 if(count($this->attachment
) < 1 && strlen($this->AltBody
) < 1) {
1148 $this->message_type
= 'plain';
1150 if(count($this->attachment
) > 0) {
1151 $this->message_type
= 'attachments';
1153 if(strlen($this->AltBody
) > 0 && count($this->attachment
) < 1) {
1154 $this->message_type
= 'alt';
1156 if(strlen($this->AltBody
) > 0 && count($this->attachment
) > 0) {
1157 $this->message_type
= 'alt_attachments';
1163 * Returns a formatted header line.
1167 public function HeaderLine($name, $value) {
1168 return $name . ': ' . $value . $this->LE
;
1172 * Returns a formatted mail line.
1176 public function TextLine($value) {
1177 return $value . $this->LE
;
1180 /////////////////////////////////////////////////
1181 // CLASS METHODS, ATTACHMENTS
1182 /////////////////////////////////////////////////
1185 * Adds an attachment from a path on the filesystem.
1186 * Returns false if the file could not be found
1188 * @param string $path Path to the attachment.
1189 * @param string $name Overrides the attachment name.
1190 * @param string $encoding File encoding (see $Encoding).
1191 * @param string $type File extension (MIME) type.
1194 public function AddAttachment($path, $name = '', $encoding = 'base64', $type = 'application/octet-stream') {
1196 if ( !@is_file
($path) ) {
1197 throw new phpmailerException($this->Lang('file_access') . $path, self
::STOP_CONTINUE
);
1199 $filename = basename($path);
1200 if ( $name == '' ) {
1204 $this->attachment
[] = array(
1210 5 => false, // isStringAttachment
1215 } catch (phpmailerException
$e) {
1216 $this->SetError($e->getMessage());
1217 if ($this->exceptions
) {
1220 echo $e->getMessage()."\n";
1221 if ( $e->getCode() == self
::STOP_CRITICAL
) {
1229 * Return the current array of attachments
1232 public function GetAttachments() {
1233 return $this->attachment
;
1237 * Attaches all fs, string, and binary attachments to the message.
1238 * Returns an empty string on failure.
1242 private function AttachAll() {
1243 // Return text of body
1248 // Add all attachments
1249 foreach ($this->attachment
as $attachment) {
1250 // Check for string attachment
1251 $bString = $attachment[5];
1253 $string = $attachment[0];
1255 $path = $attachment[0];
1258 if (in_array($attachment[0], $incl)) { continue; }
1259 $filename = $attachment[1];
1260 $name = $attachment[2];
1261 $encoding = $attachment[3];
1262 $type = $attachment[4];
1263 $disposition = $attachment[6];
1264 $cid = $attachment[7];
1265 $incl[] = $attachment[0];
1266 if ( $disposition == 'inline' && isset($cidUniq[$cid]) ) { continue; }
1267 $cidUniq[$cid] = true;
1269 $mime[] = sprintf("--%s%s", $this->boundary
[1], $this->LE
);
1270 $mime[] = sprintf("Content-Type: %s; name=\"%s\"%s", $type, $this->EncodeHeader($this->SecureHeader($name)), $this->LE
);
1271 $mime[] = sprintf("Content-Transfer-Encoding: %s%s", $encoding, $this->LE
);
1273 if($disposition == 'inline') {
1274 $mime[] = sprintf("Content-ID: <%s>%s", $cid, $this->LE
);
1277 $mime[] = sprintf("Content-Disposition: %s; filename=\"%s\"%s", $disposition, $this->EncodeHeader($this->SecureHeader($name)), $this->LE
.$this->LE
);
1279 // Encode as string attachment
1281 $mime[] = $this->EncodeString($string, $encoding);
1282 if($this->IsError()) {
1285 $mime[] = $this->LE
.$this->LE
;
1287 $mime[] = $this->EncodeFile($path, $encoding);
1288 if($this->IsError()) {
1291 $mime[] = $this->LE
.$this->LE
;
1295 $mime[] = sprintf("--%s--%s", $this->boundary
[1], $this->LE
);
1297 return join('', $mime);
1301 * Encodes attachment in requested format.
1302 * Returns an empty string on failure.
1303 * @param string $path The full path to the file
1304 * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
1309 private function EncodeFile($path, $encoding = 'base64') {
1311 if (!is_readable($path)) {
1312 throw new phpmailerException($this->Lang('file_open') . $path, self
::STOP_CONTINUE
);
1314 if (function_exists('get_magic_quotes')) {
1315 function get_magic_quotes() {
1319 if (PHP_VERSION
< 6) {
1320 $magic_quotes = get_magic_quotes_runtime();
1321 set_magic_quotes_runtime(0);
1323 $file_buffer = file_get_contents($path);
1324 $file_buffer = $this->EncodeString($file_buffer, $encoding);
1325 if (PHP_VERSION
< 6) { set_magic_quotes_runtime($magic_quotes); }
1326 return $file_buffer;
1327 } catch (Exception
$e) {
1328 $this->SetError($e->getMessage());
1334 * Encodes string to requested format.
1335 * Returns an empty string on failure.
1336 * @param string $str The text to encode
1337 * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
1341 public function EncodeString ($str, $encoding = 'base64') {
1343 switch(strtolower($encoding)) {
1345 $encoded = chunk_split(base64_encode($str), 76, $this->LE
);
1349 $encoded = $this->FixEOL($str);
1350 //Make sure it ends with a line break
1351 if (substr($encoded, -(strlen($this->LE
))) != $this->LE
)
1352 $encoded .= $this->LE
;
1357 case 'quoted-printable':
1358 $encoded = $this->EncodeQP($str);
1361 $this->SetError($this->Lang('encoding') . $encoding);
1368 * Encode a header string to best (shortest) of Q, B, quoted or none.
1372 public function EncodeHeader($str, $position = 'text') {
1375 switch (strtolower($position)) {
1377 if (!preg_match('/[\200-\377]/', $str)) {
1378 // Can't use addslashes as we don't know what value has magic_quotes_sybase
1379 $encoded = addcslashes($str, "\0..\37\177\\\"");
1380 if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
1383 return ("\"$encoded\"");
1386 $x = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
1389 $x = preg_match_all('/[()"]/', $str, $matches);
1393 $x +
= preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
1401 $maxlen = 75 - 7 - strlen($this->CharSet
);
1402 // Try to select the encoding which should produce the shortest output
1403 if (strlen($str)/3 < $x) {
1405 if (function_exists('mb_strlen') && $this->HasMultiBytes($str)) {
1406 // Use a custom function which correctly encodes and wraps long
1407 // multibyte strings without breaking lines within a character
1408 $encoded = $this->Base64EncodeWrapMB($str);
1410 $encoded = base64_encode($str);
1411 $maxlen -= $maxlen %
4;
1412 $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
1416 $encoded = $this->EncodeQ($str, $position);
1417 $encoded = $this->WrapText($encoded, $maxlen, true);
1418 $encoded = str_replace('='.$this->LE
, "\n", trim($encoded));
1421 $encoded = preg_replace('/^(.*)$/m', " =?".$this->CharSet
."?$encoding?\\1?=", $encoded);
1422 $encoded = trim(str_replace("\n", $this->LE
, $encoded));
1428 * Checks if a string contains multibyte characters.
1430 * @param string $str multi-byte text to wrap encode
1433 public function HasMultiBytes($str) {
1434 if (function_exists('mb_strlen')) {
1435 return (strlen($str) > mb_strlen($str, $this->CharSet
));
1436 } else { // Assume no multibytes (we can't handle without mbstring functions anyway)
1442 * Correctly encodes and wraps long multibyte strings for mail headers
1443 * without breaking lines within a character.
1444 * Adapted from a function by paravoid at http://uk.php.net/manual/en/function.mb-encode-mimeheader.php
1446 * @param string $str multi-byte text to wrap encode
1449 public function Base64EncodeWrapMB($str) {
1450 $start = "=?".$this->CharSet
."?B?";
1454 $mb_length = mb_strlen($str, $this->CharSet
);
1455 // Each line must have length <= 75, including $start and $end
1456 $length = 75 - strlen($start) - strlen($end);
1457 // Average multi-byte ratio
1458 $ratio = $mb_length / strlen($str);
1459 // Base64 has a 4:3 ratio
1460 $offset = $avgLength = floor($length * $ratio * .75);
1462 for ($i = 0; $i < $mb_length; $i +
= $offset) {
1466 $offset = $avgLength - $lookBack;
1467 $chunk = mb_substr($str, $i, $offset, $this->CharSet
);
1468 $chunk = base64_encode($chunk);
1471 while (strlen($chunk) > $length);
1473 $encoded .= $chunk . $this->LE
;
1476 // Chomp the last linefeed
1477 $encoded = substr($encoded, 0, -strlen($this->LE
));
1482 * Encode string to quoted-printable.
1483 * Only uses standard PHP, slow, but will always work
1485 * @param string $string the text to encode
1486 * @param integer $line_max Number of chars allowed on a line before wrapping
1489 public function EncodeQPphp( $input = '', $line_max = 76, $space_conv = false) {
1490 $hex = array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');
1491 $lines = preg_split('/(?:\r\n|\r|\n)/', $input);
1495 while( list(, $line) = each($lines) ) {
1496 $linlen = strlen($line);
1498 for($i = 0; $i < $linlen; $i++
) {
1499 $c = substr( $line, $i, 1 );
1501 if ( ( $i == 0 ) && ( $dec == 46 ) ) { // convert first point in the line into =2E
1505 if ( $i == ( $linlen - 1 ) ) { // convert space at eol only
1507 } else if ( $space_conv ) {
1510 } elseif ( ($dec == 61) ||
($dec < 32 ) ||
($dec > 126) ) { // always encode "\t", which is *not* required
1511 $h2 = floor($dec/16);
1512 $h1 = floor($dec%16
);
1513 $c = $escape.$hex[$h2].$hex[$h1];
1515 if ( (strlen($newline) +
strlen($c)) >= $line_max ) { // CRLF is not counted
1516 $output .= $newline.$escape.$eol; // soft line break; " =\r\n" is okay
1518 // check if newline first character will be point or not
1525 $output .= $newline.$eol;
1531 * Encode string to RFC2045 (6.7) quoted-printable format
1532 * Uses a PHP5 stream filter to do the encoding about 64x faster than the old version
1533 * Also results in same content as you started with after decoding
1534 * @see EncodeQPphp()
1536 * @param string $string the text to encode
1537 * @param integer $line_max Number of chars allowed on a line before wrapping
1538 * @param boolean $space_conv Dummy param for compatibility with existing EncodeQP function
1540 * @author Marcus Bointon
1542 public function EncodeQP($string, $line_max = 76, $space_conv = false) {
1543 if (function_exists('quoted_printable_encode')) { //Use native function if it's available (>= PHP5.3)
1544 return quoted_printable_encode($string);
1546 $filters = stream_get_filters();
1547 if (!in_array('convert.*', $filters)) { //Got convert stream filter?
1548 return $this->EncodeQPphp($string, $line_max, $space_conv); //Fall back to old implementation
1550 $fp = fopen('php://temp/', 'r+');
1551 $string = preg_replace('/\r\n?/', $this->LE
, $string); //Normalise line breaks
1552 $params = array('line-length' => $line_max, 'line-break-chars' => $this->LE
);
1553 $s = stream_filter_append($fp, 'convert.quoted-printable-encode', STREAM_FILTER_READ
, $params);
1554 fputs($fp, $string);
1556 $out = stream_get_contents($fp);
1557 stream_filter_remove($s);
1558 $out = preg_replace('/^\./m', '=2E', $out); //Encode . if it is first char on a line, workaround for bug in Exchange
1564 * NOTE: Phabricator patch to remove use of "/e". See D2147.
1566 private function encodeQCallback(array $matches) {
1567 return '='.sprintf('%02X', ord($matches[1]));
1571 * Encode string to q encoding.
1572 * @link http://tools.ietf.org/html/rfc2047
1573 * @param string $str the text to encode
1574 * @param string $position Where the text is going to be used, see the RFC for what that means
1578 public function EncodeQ ($str, $position = 'text') {
1580 // NOTE: Phabricator patch to remove use of "/e". See D2147.
1582 // There should not be any EOL in the string
1583 $encoded = preg_replace('/[\r\n]*/', '', $str);
1585 switch (strtolower($position)) {
1587 $encoded = preg_replace_callback(
1588 "/([^A-Za-z0-9!*+\/ -])/",
1589 array($this, 'encodeQCallback'),
1593 $encoded = preg_replace_callback(
1595 array($this, 'encodeQCallback'),
1600 // Replace every high ascii, control =, ? and _ characters
1601 $encoded = preg_replace_callback(
1602 '/([\000-\011\013\014\016-\037\075\077\137\177-\377])/',
1603 array($this, 'encodeQCallback'),
1608 // Replace every spaces to _ (more readable than =20)
1609 $encoded = str_replace(' ', '_', $encoded);
1615 * Adds a string or binary attachment (non-filesystem) to the list.
1616 * This method can be used to attach ascii or binary data,
1617 * such as a BLOB record from a database.
1618 * @param string $string String attachment data.
1619 * @param string $filename Name of the attachment.
1620 * @param string $encoding File encoding (see $Encoding).
1621 * @param string $type File extension (MIME) type.
1624 public function AddStringAttachment($string, $filename, $encoding = 'base64', $type = 'application/octet-stream') {
1625 // Append to $attachment array
1626 $this->attachment
[] = array(
1629 2 => basename($filename),
1632 5 => true, // isStringAttachment
1639 * Adds an embedded attachment. This can include images, sounds, and
1640 * just about any other document. Make sure to set the $type to an
1641 * image type. For JPEG images use "image/jpeg" and for GIF images
1643 * @param string $path Path to the attachment.
1644 * @param string $cid Content ID of the attachment. Use this to identify
1645 * the Id for accessing the image in an HTML form.
1646 * @param string $name Overrides the attachment name.
1647 * @param string $encoding File encoding (see $Encoding).
1648 * @param string $type File extension (MIME) type.
1651 public function AddEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = 'application/octet-stream') {
1653 if ( !@is_file
($path) ) {
1654 $this->SetError($this->Lang('file_access') . $path);
1658 $filename = basename($path);
1659 if ( $name == '' ) {
1663 // Append to $attachment array
1664 $this->attachment
[] = array(
1670 5 => false, // isStringAttachment
1679 * Returns true if an inline attachment is present.
1683 public function InlineImageExists() {
1684 foreach($this->attachment
as $attachment) {
1685 if ($attachment[6] == 'inline') {
1692 /////////////////////////////////////////////////
1693 // CLASS METHODS, MESSAGE RESET
1694 /////////////////////////////////////////////////
1697 * Clears all recipients assigned in the TO array. Returns void.
1700 public function ClearAddresses() {
1701 foreach($this->to
as $to) {
1702 unset($this->all_recipients
[strtolower($to[0])]);
1704 $this->to
= array();
1708 * Clears all recipients assigned in the CC array. Returns void.
1711 public function ClearCCs() {
1712 foreach($this->cc
as $cc) {
1713 unset($this->all_recipients
[strtolower($cc[0])]);
1715 $this->cc
= array();
1719 * Clears all recipients assigned in the BCC array. Returns void.
1722 public function ClearBCCs() {
1723 foreach($this->bcc
as $bcc) {
1724 unset($this->all_recipients
[strtolower($bcc[0])]);
1726 $this->bcc
= array();
1730 * Clears all recipients assigned in the ReplyTo array. Returns void.
1733 public function ClearReplyTos() {
1734 $this->ReplyTo
= array();
1738 * Clears all recipients assigned in the TO, CC and BCC
1739 * array. Returns void.
1742 public function ClearAllRecipients() {
1743 $this->to
= array();
1744 $this->cc
= array();
1745 $this->bcc
= array();
1746 $this->all_recipients
= array();
1750 * Clears all previously set filesystem, string, and binary
1751 * attachments. Returns void.
1754 public function ClearAttachments() {
1755 $this->attachment
= array();
1759 * Clears all custom headers. Returns void.
1762 public function ClearCustomHeaders() {
1763 $this->CustomHeader
= array();
1766 /////////////////////////////////////////////////
1767 // CLASS METHODS, MISCELLANEOUS
1768 /////////////////////////////////////////////////
1771 * Adds the error message to the error container.
1775 protected function SetError($msg) {
1776 $this->error_count++
;
1777 $this->ErrorInfo
= $msg;
1781 * Returns the proper RFC 822 formatted date.
1786 public static function RFCDate() {
1788 $tzs = ($tz < 0) ?
'-' : '+';
1790 $tz = (int)($tz/3600)*100 +
($tz%3600
)/60;
1791 $result = sprintf("%s %s%04d", date('D, j M Y H:i:s'), $tzs, $tz);
1797 * Returns the server hostname or 'localhost.localdomain' if unknown.
1801 private function ServerHostname() {
1802 if (!empty($this->Hostname
)) {
1803 $result = $this->Hostname
;
1804 } elseif (isset($_SERVER['SERVER_NAME'])) {
1805 $result = $_SERVER['SERVER_NAME'];
1807 $result = 'localhost.localdomain';
1814 * Returns a message in the appropriate language.
1818 private function Lang($key) {
1819 if(count($this->language
) < 1) {
1820 $this->SetLanguage('en'); // set the default language
1823 if(isset($this->language
[$key])) {
1824 return $this->language
[$key];
1826 return 'Language string failed to load: ' . $key;
1831 * Returns true if an error occurred.
1835 public function IsError() {
1836 return ($this->error_count
> 0);
1840 * Changes every end of line from CR or LF to CRLF.
1844 private function FixEOL($str) {
1845 $str = str_replace("\r\n", "\n", $str);
1846 $str = str_replace("\r", "\n", $str);
1847 $str = str_replace("\n", $this->LE
, $str);
1852 * Adds a custom header.
1856 public function AddCustomHeader($custom_header) {
1857 $this->CustomHeader
[] = explode(':', $custom_header, 2);
1861 * Evaluates the message and returns modifications for inline images and backgrounds
1865 public function MsgHTML($message, $basedir = '') {
1866 preg_match_all("/(src|background)=\"(.*)\"/Ui", $message, $images);
1867 if(isset($images[2])) {
1868 foreach($images[2] as $i => $url) {
1869 // do not change urls for absolute images (thanks to corvuscorax)
1870 if (!preg_match('#^[A-z]+://#',$url)) {
1871 $filename = basename($url);
1872 $directory = dirname($url);
1873 ($directory == '.')?
$directory='':'';
1874 $cid = 'cid:' . md5($filename);
1875 $ext = pathinfo($filename, PATHINFO_EXTENSION
);
1876 $mimeType = self
::_mime_types($ext);
1877 if ( strlen($basedir) > 1 && substr($basedir,-1) != '/') { $basedir .= '/'; }
1878 if ( strlen($directory) > 1 && substr($directory,-1) != '/') { $directory .= '/'; }
1879 if ( $this->AddEmbeddedImage($basedir.$directory.$filename, md5($filename), $filename, 'base64',$mimeType) ) {
1880 $message = preg_replace("/".$images[1][$i]."=\"".preg_quote($url, '/')."\"/Ui", $images[1][$i]."=\"".$cid."\"", $message);
1885 $this->IsHTML(true);
1886 $this->Body
= $message;
1887 $textMsg = trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/s','',$message)));
1888 if (!empty($textMsg) && empty($this->AltBody
)) {
1889 $this->AltBody
= html_entity_decode($textMsg);
1891 if (empty($this->AltBody
)) {
1892 $this->AltBody
= 'To view this email message, open it in a program that understands HTML!' . "\n\n";
1897 * Gets the MIME type of the embedded or inline image
1898 * @param string File extension
1900 * @return string MIME type of ext
1903 public static function _mime_types($ext = '') {
1905 'hqx' => 'application/mac-binhex40',
1906 'cpt' => 'application/mac-compactpro',
1907 'doc' => 'application/msword',
1908 'bin' => 'application/macbinary',
1909 'dms' => 'application/octet-stream',
1910 'lha' => 'application/octet-stream',
1911 'lzh' => 'application/octet-stream',
1912 'exe' => 'application/octet-stream',
1913 'class' => 'application/octet-stream',
1914 'psd' => 'application/octet-stream',
1915 'so' => 'application/octet-stream',
1916 'sea' => 'application/octet-stream',
1917 'dll' => 'application/octet-stream',
1918 'oda' => 'application/oda',
1919 'pdf' => 'application/pdf',
1920 'ai' => 'application/postscript',
1921 'eps' => 'application/postscript',
1922 'ps' => 'application/postscript',
1923 'smi' => 'application/smil',
1924 'smil' => 'application/smil',
1925 'mif' => 'application/vnd.mif',
1926 'xls' => 'application/vnd.ms-excel',
1927 'ppt' => 'application/vnd.ms-powerpoint',
1928 'wbxml' => 'application/vnd.wap.wbxml',
1929 'wmlc' => 'application/vnd.wap.wmlc',
1930 'dcr' => 'application/x-director',
1931 'dir' => 'application/x-director',
1932 'dxr' => 'application/x-director',
1933 'dvi' => 'application/x-dvi',
1934 'gtar' => 'application/x-gtar',
1935 'php' => 'application/x-httpd-php',
1936 'php4' => 'application/x-httpd-php',
1937 'php3' => 'application/x-httpd-php',
1938 'phtml' => 'application/x-httpd-php',
1939 'phps' => 'application/x-httpd-php-source',
1940 'js' => 'application/x-javascript',
1941 'swf' => 'application/x-shockwave-flash',
1942 'sit' => 'application/x-stuffit',
1943 'tar' => 'application/x-tar',
1944 'tgz' => 'application/x-tar',
1945 'xhtml' => 'application/xhtml+xml',
1946 'xht' => 'application/xhtml+xml',
1947 'zip' => 'application/zip',
1948 'mid' => 'audio/midi',
1949 'midi' => 'audio/midi',
1950 'mpga' => 'audio/mpeg',
1951 'mp2' => 'audio/mpeg',
1952 'mp3' => 'audio/mpeg',
1953 'aif' => 'audio/x-aiff',
1954 'aiff' => 'audio/x-aiff',
1955 'aifc' => 'audio/x-aiff',
1956 'ram' => 'audio/x-pn-realaudio',
1957 'rm' => 'audio/x-pn-realaudio',
1958 'rpm' => 'audio/x-pn-realaudio-plugin',
1959 'ra' => 'audio/x-realaudio',
1960 'rv' => 'video/vnd.rn-realvideo',
1961 'wav' => 'audio/x-wav',
1962 'bmp' => 'image/bmp',
1963 'gif' => 'image/gif',
1964 'jpeg' => 'image/jpeg',
1965 'jpg' => 'image/jpeg',
1966 'jpe' => 'image/jpeg',
1967 'png' => 'image/png',
1968 'tiff' => 'image/tiff',
1969 'tif' => 'image/tiff',
1970 'css' => 'text/css',
1971 'html' => 'text/html',
1972 'htm' => 'text/html',
1973 'shtml' => 'text/html',
1974 'txt' => 'text/plain',
1975 'text' => 'text/plain',
1976 'log' => 'text/plain',
1977 'rtx' => 'text/richtext',
1978 'rtf' => 'text/rtf',
1979 'xml' => 'text/xml',
1980 'xsl' => 'text/xml',
1981 'mpeg' => 'video/mpeg',
1982 'mpg' => 'video/mpeg',
1983 'mpe' => 'video/mpeg',
1984 'qt' => 'video/quicktime',
1985 'mov' => 'video/quicktime',
1986 'avi' => 'video/x-msvideo',
1987 'movie' => 'video/x-sgi-movie',
1988 'doc' => 'application/msword',
1989 'word' => 'application/msword',
1990 'xl' => 'application/excel',
1991 'eml' => 'message/rfc822'
1993 return (!isset($mimes[strtolower($ext)])) ?
'application/octet-stream' : $mimes[strtolower($ext)];
1997 * Set (or reset) Class Objects (variables)
2000 * $page->set('X-Priority', '3');
2003 * @param string $name Parameter Name
2004 * @param mixed $value Parameter Value
2005 * NOTE: will not work with arrays, there are no arrays to set/reset
2006 * @todo Should this not be using __set() magic function?
2008 public function set($name, $value = '') {
2010 if (isset($this->$name) ) {
2011 $this->$name = $value;
2013 throw new phpmailerException($this->Lang('variable_set') . $name, self
::STOP_CRITICAL
);
2015 } catch (Exception
$e) {
2016 $this->SetError($e->getMessage());
2017 if ($e->getCode() == self
::STOP_CRITICAL
) {
2025 * Strips newlines to prevent header injection.
2027 * @param string $str String
2030 public function SecureHeader($str) {
2031 $str = str_replace("\r", '', $str);
2032 $str = str_replace("\n", '', $str);
2037 * Set the private key file and password to sign the message.
2040 * @param string $key_filename Parameter File Name
2041 * @param string $key_pass Password for private key
2043 public function Sign($cert_filename, $key_filename, $key_pass) {
2044 $this->sign_cert_file
= $cert_filename;
2045 $this->sign_key_file
= $key_filename;
2046 $this->sign_key_pass
= $key_pass;
2050 * Set the private key file and password to sign the message.
2053 * @param string $key_filename Parameter File Name
2054 * @param string $key_pass Password for private key
2056 public function DKIM_QP($txt) {
2059 for ($i=0;$i<strlen($txt);$i++
) {
2061 if ( ((0x21 <= $ord) && ($ord <= 0x3A)) ||
$ord == 0x3C ||
((0x3E <= $ord) && ($ord <= 0x7E)) ) {
2064 $line.="=".sprintf("%02X",$ord);
2071 * Generate DKIM signature
2074 * @param string $s Header
2076 public function DKIM_Sign($s) {
2077 $privKeyStr = file_get_contents($this->DKIM_private
);
2078 if ($this->DKIM_passphrase
!='') {
2079 $privKey = openssl_pkey_get_private($privKeyStr,$this->DKIM_passphrase
);
2081 $privKey = $privKeyStr;
2083 if (openssl_sign($s, $signature, $privKey)) {
2084 return base64_encode($signature);
2089 * Generate DKIM Canonicalization Header
2092 * @param string $s Header
2094 public function DKIM_HeaderC($s) {
2095 $s=preg_replace("/\r\n\s+/"," ",$s);
2096 $lines=explode("\r\n",$s);
2097 foreach ($lines as $key=>$line) {
2098 list($heading,$value)=explode(":",$line,2);
2099 $heading=strtolower($heading);
2100 $value=preg_replace("/\s+/"," ",$value) ; // Compress useless spaces
2101 $lines[$key]=$heading.":".trim($value) ; // Don't forget to remove WSP around the value
2103 $s=implode("\r\n",$lines);
2108 * Generate DKIM Canonicalization Body
2111 * @param string $body Message Body
2113 public function DKIM_BodyC($body) {
2114 if ($body == '') return "\r\n";
2115 // stabilize line endings
2116 $body=str_replace("\r\n","\n",$body);
2117 $body=str_replace("\n","\r\n",$body);
2118 // END stabilize line endings
2119 while (substr($body,strlen($body)-4,4) == "\r\n\r\n") {
2120 $body=substr($body,0,strlen($body)-2);
2126 * Create the DKIM header, body, as new header
2129 * @param string $headers_line Header lines
2130 * @param string $subject Subject
2131 * @param string $body Body
2133 public function DKIM_Add($headers_line,$subject,$body) {
2134 $DKIMsignatureType = 'rsa-sha1'; // Signature & hash algorithms
2135 $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body
2136 $DKIMquery = 'dns/txt'; // Query method
2137 $DKIMtime = time() ; // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone)
2138 $subject_header = "Subject: $subject";
2139 $headers = explode("\r\n",$headers_line);
2140 foreach($headers as $header) {
2141 if (strpos($header,'From:') === 0) {
2142 $from_header=$header;
2143 } elseif (strpos($header,'To:') === 0) {
2147 $from = str_replace('|','=7C',$this->DKIM_QP($from_header));
2148 $to = str_replace('|','=7C',$this->DKIM_QP($to_header));
2149 $subject = str_replace('|','=7C',$this->DKIM_QP($subject_header)) ; // Copied header fields (dkim-quoted-printable
2150 $body = $this->DKIM_BodyC($body);
2151 $DKIMlen = strlen($body) ; // Length of body
2152 $DKIMb64 = base64_encode(pack("H*", sha1($body))) ; // Base64 of packed binary SHA-1 hash of body
2153 $ident = ($this->DKIM_identity
== '')?
'' : " i=" . $this->DKIM_identity
. ";";
2154 $dkimhdrs = "DKIM-Signature: v=1; a=" . $DKIMsignatureType . "; q=" . $DKIMquery . "; l=" . $DKIMlen . "; s=" . $this->DKIM_selector
. ";\r\n".
2155 "\tt=" . $DKIMtime . "; c=" . $DKIMcanonicalization . ";\r\n".
2156 "\th=From:To:Subject;\r\n".
2157 "\td=" . $this->DKIM_domain
. ";" . $ident . "\r\n".
2161 "\tbh=" . $DKIMb64 . ";\r\n".
2163 $toSign = $this->DKIM_HeaderC($from_header . "\r\n" . $to_header . "\r\n" . $subject_header . "\r\n" . $dkimhdrs);
2164 $signed = $this->DKIM_Sign($toSign);
2165 return "X-PHPMAILER-DKIM: phpmailer.sourceforge.net\r\n".$dkimhdrs.$signed."\r\n";
2168 protected function doCallback($isSent,$to,$cc,$bcc,$subject,$body) {
2169 if (!empty($this->action_function
) && function_exists($this->action_function
)) {
2170 $params = array($isSent,$to,$cc,$bcc,$subject,$body);
2171 call_user_func_array($this->action_function
,$params);
2176 class phpmailerException
extends Exception
{
2177 public function errorMessage() {
2178 $errorMsg = '<strong>' . $this->getMessage() . "</strong><br />\n";