Merge branch '45699-29' of git://github.com/samhemelryk/moodle
[moodle.git] / lib / phpmailer / class.phpmailer.php
blobcd102a285944f5a73608f598574112c43c110e04
1 <?php
2 /**
3 * PHPMailer - PHP email creation and transport class.
4 * PHP Version 5
5 * @package PHPMailer
6 * @link https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
7 * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
8 * @author Jim Jagielski (jimjag) <jimjag@gmail.com>
9 * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
10 * @author Brent R. Matzelle (original founder)
11 * @copyright 2012 - 2014 Marcus Bointon
12 * @copyright 2010 - 2012 Jim Jagielski
13 * @copyright 2004 - 2009 Andy Prevost
14 * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
15 * @note This program is distributed in the hope that it will be useful - WITHOUT
16 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
17 * FITNESS FOR A PARTICULAR PURPOSE.
20 /**
21 * PHPMailer - PHP email creation and transport class.
22 * @package PHPMailer
23 * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
24 * @author Jim Jagielski (jimjag) <jimjag@gmail.com>
25 * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
26 * @author Brent R. Matzelle (original founder)
28 class PHPMailer
30 /**
31 * The PHPMailer Version number.
32 * @type string
34 public $Version = '5.2.9';
36 /**
37 * Email priority.
38 * Options: 1 = High, 3 = Normal, 5 = low.
39 * @type integer
41 public $Priority = 3;
43 /**
44 * The character set of the message.
45 * @type string
47 public $CharSet = 'iso-8859-1';
49 /**
50 * The MIME Content-type of the message.
51 * @type string
53 public $ContentType = 'text/plain';
55 /**
56 * The message encoding.
57 * Options: "8bit", "7bit", "binary", "base64", and "quoted-printable".
58 * @type string
60 public $Encoding = '8bit';
62 /**
63 * Holds the most recent mailer error message.
64 * @type string
66 public $ErrorInfo = '';
68 /**
69 * The From email address for the message.
70 * @type string
72 public $From = 'root@localhost';
74 /**
75 * The From name of the message.
76 * @type string
78 public $FromName = 'Root User';
80 /**
81 * The Sender email (Return-Path) of the message.
82 * If not empty, will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode.
83 * @type string
85 public $Sender = '';
87 /**
88 * The Return-Path of the message.
89 * If empty, it will be set to either From or Sender.
90 * @type string
91 * @deprecated Email senders should never set a return-path header;
92 * it's the receiver's job (RFC5321 section 4.4), so this no longer does anything.
93 * @link https://tools.ietf.org/html/rfc5321#section-4.4 RFC5321 reference
95 public $ReturnPath = '';
97 /**
98 * The Subject of the message.
99 * @type string
101 public $Subject = '';
104 * An HTML or plain text message body.
105 * If HTML then call isHTML(true).
106 * @type string
108 public $Body = '';
111 * The plain-text message body.
112 * This body can be read by mail clients that do not have HTML email
113 * capability such as mutt & Eudora.
114 * Clients that can read HTML will view the normal Body.
115 * @type string
117 public $AltBody = '';
120 * An iCal message part body.
121 * Only supported in simple alt or alt_inline message types
122 * To generate iCal events, use the bundled extras/EasyPeasyICS.php class or iCalcreator
123 * @link http://sprain.ch/blog/downloads/php-class-easypeasyics-create-ical-files-with-php/
124 * @link http://kigkonsult.se/iCalcreator/
125 * @type string
127 public $Ical = '';
130 * The complete compiled MIME message body.
131 * @access protected
132 * @type string
134 protected $MIMEBody = '';
137 * The complete compiled MIME message headers.
138 * @type string
139 * @access protected
141 protected $MIMEHeader = '';
144 * Extra headers that createHeader() doesn't fold in.
145 * @type string
146 * @access protected
148 protected $mailHeader = '';
151 * Word-wrap the message body to this number of chars.
152 * @type integer
154 public $WordWrap = 0;
157 * Which method to use to send mail.
158 * Options: "mail", "sendmail", or "smtp".
159 * @type string
161 public $Mailer = 'mail';
164 * The path to the sendmail program.
165 * @type string
167 public $Sendmail = '/usr/sbin/sendmail';
170 * Whether mail() uses a fully sendmail-compatible MTA.
171 * One which supports sendmail's "-oi -f" options.
172 * @type boolean
174 public $UseSendmailOptions = true;
177 * Path to PHPMailer plugins.
178 * Useful if the SMTP class is not in the PHP include path.
179 * @type string
180 * @deprecated Should not be needed now there is an autoloader.
182 public $PluginDir = '';
185 * The email address that a reading confirmation should be sent to.
186 * @type string
188 public $ConfirmReadingTo = '';
191 * The hostname to use in Message-Id and Received headers
192 * and as default HELO string.
193 * If empty, the value returned
194 * by SERVER_NAME is used or 'localhost.localdomain'.
195 * @type string
197 public $Hostname = '';
200 * An ID to be used in the Message-Id header.
201 * If empty, a unique id will be generated.
202 * @type string
204 public $MessageID = '';
207 * The message Date to be used in the Date header.
208 * If empty, the current date will be added.
209 * @type string
211 public $MessageDate = '';
214 * SMTP hosts.
215 * Either a single hostname or multiple semicolon-delimited hostnames.
216 * You can also specify a different port
217 * for each host by using this format: [hostname:port]
218 * (e.g. "smtp1.example.com:25;smtp2.example.com").
219 * You can also specify encryption type, for example:
220 * (e.g. "tls://smtp1.example.com:587;ssl://smtp2.example.com:465").
221 * Hosts will be tried in order.
222 * @type string
224 public $Host = 'localhost';
227 * The default SMTP server port.
228 * @type integer
229 * @TODO Why is this needed when the SMTP class takes care of it?
231 public $Port = 25;
234 * The SMTP HELO of the message.
235 * Default is $Hostname.
236 * @type string
237 * @see PHPMailer::$Hostname
239 public $Helo = '';
242 * The secure connection prefix.
243 * Options: "", "ssl" or "tls"
244 * @type string
246 public $SMTPSecure = '';
249 * Whether to use SMTP authentication.
250 * Uses the Username and Password properties.
251 * @type boolean
252 * @see PHPMailer::$Username
253 * @see PHPMailer::$Password
255 public $SMTPAuth = false;
258 * SMTP username.
259 * @type string
261 public $Username = '';
264 * SMTP password.
265 * @type string
267 public $Password = '';
270 * SMTP auth type.
271 * Options are LOGIN (default), PLAIN, NTLM, CRAM-MD5
272 * @type string
274 public $AuthType = '';
277 * SMTP realm.
278 * Used for NTLM auth
279 * @type string
281 public $Realm = '';
284 * SMTP workstation.
285 * Used for NTLM auth
286 * @type string
288 public $Workstation = '';
291 * The SMTP server timeout in seconds.
292 * @type integer
294 public $Timeout = 10;
297 * SMTP class debug output mode.
298 * Debug output level.
299 * Options:
300 * * `0` No output
301 * * `1` Commands
302 * * `2` Data and commands
303 * * `3` As 2 plus connection status
304 * * `4` Low-level data output
305 * @type integer
306 * @see SMTP::$do_debug
308 public $SMTPDebug = 0;
311 * How to handle debug output.
312 * Options:
313 * * `echo` Output plain-text as-is, appropriate for CLI
314 * * `html` Output escaped, line breaks converted to `<br>`, appropriate for browser output
315 * * `error_log` Output to error log as configured in php.ini
317 * Alternatively, you can provide a callable expecting two params: a message string and the debug level:
318 * <code>
319 * $mail->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";};
320 * </code>
321 * @type string|callable
322 * @see SMTP::$Debugoutput
324 public $Debugoutput = 'echo';
327 * Whether to keep SMTP connection open after each message.
328 * If this is set to true then to close the connection
329 * requires an explicit call to smtpClose().
330 * @type boolean
332 public $SMTPKeepAlive = false;
335 * Whether to split multiple to addresses into multiple messages
336 * or send them all in one message.
337 * @type boolean
339 public $SingleTo = false;
342 * Storage for addresses when SingleTo is enabled.
343 * @type array
344 * @TODO This should really not be public
346 public $SingleToArray = array();
349 * Whether to generate VERP addresses on send.
350 * Only applicable when sending via SMTP.
351 * @link http://en.wikipedia.org/wiki/Variable_envelope_return_path
352 * @link http://www.postfix.org/VERP_README.html Postfix VERP info
353 * @type boolean
355 public $do_verp = false;
358 * Whether to allow sending messages with an empty body.
359 * @type boolean
361 public $AllowEmpty = false;
364 * The default line ending.
365 * @note The default remains "\n". We force CRLF where we know
366 * it must be used via self::CRLF.
367 * @type string
369 public $LE = "\n";
372 * DKIM selector.
373 * @type string
375 public $DKIM_selector = '';
378 * DKIM Identity.
379 * Usually the email address used as the source of the email
380 * @type string
382 public $DKIM_identity = '';
385 * DKIM passphrase.
386 * Used if your key is encrypted.
387 * @type string
389 public $DKIM_passphrase = '';
392 * DKIM signing domain name.
393 * @example 'example.com'
394 * @type string
396 public $DKIM_domain = '';
399 * DKIM private key file path.
400 * @type string
402 public $DKIM_private = '';
405 * Callback Action function name.
407 * The function that handles the result of the send email action.
408 * It is called out by send() for each email sent.
410 * Value can be any php callable: http://www.php.net/is_callable
412 * Parameters:
413 * boolean $result result of the send action
414 * string $to email address of the recipient
415 * string $cc cc email addresses
416 * string $bcc bcc email addresses
417 * string $subject the subject
418 * string $body the email body
419 * string $from email address of sender
420 * @type string
422 public $action_function = '';
425 * What to use in the X-Mailer header.
426 * Options: null for default, whitespace for none, or a string to use
427 * @type string
429 public $XMailer = '';
432 * An instance of the SMTP sender class.
433 * @type SMTP
434 * @access protected
436 protected $smtp = null;
439 * The array of 'to' addresses.
440 * @type array
441 * @access protected
443 protected $to = array();
446 * The array of 'cc' addresses.
447 * @type array
448 * @access protected
450 protected $cc = array();
453 * The array of 'bcc' addresses.
454 * @type array
455 * @access protected
457 protected $bcc = array();
460 * The array of reply-to names and addresses.
461 * @type array
462 * @access protected
464 protected $ReplyTo = array();
467 * An array of all kinds of addresses.
468 * Includes all of $to, $cc, $bcc, $replyto
469 * @type array
470 * @access protected
472 protected $all_recipients = array();
475 * The array of attachments.
476 * @type array
477 * @access protected
479 protected $attachment = array();
482 * The array of custom headers.
483 * @type array
484 * @access protected
486 protected $CustomHeader = array();
489 * The most recent Message-ID (including angular brackets).
490 * @type string
491 * @access protected
493 protected $lastMessageID = '';
496 * The message's MIME type.
497 * @type string
498 * @access protected
500 protected $message_type = '';
503 * The array of MIME boundary strings.
504 * @type array
505 * @access protected
507 protected $boundary = array();
510 * The array of available languages.
511 * @type array
512 * @access protected
514 protected $language = array();
517 * The number of errors encountered.
518 * @type integer
519 * @access protected
521 protected $error_count = 0;
524 * The S/MIME certificate file path.
525 * @type string
526 * @access protected
528 protected $sign_cert_file = '';
531 * The S/MIME key file path.
532 * @type string
533 * @access protected
535 protected $sign_key_file = '';
538 * The S/MIME password for the key.
539 * Used only if the key is encrypted.
540 * @type string
541 * @access protected
543 protected $sign_key_pass = '';
546 * Whether to throw exceptions for errors.
547 * @type boolean
548 * @access protected
550 protected $exceptions = false;
553 * Error severity: message only, continue processing.
555 const STOP_MESSAGE = 0;
558 * Error severity: message, likely ok to continue processing.
560 const STOP_CONTINUE = 1;
563 * Error severity: message, plus full stop, critical error reached.
565 const STOP_CRITICAL = 2;
568 * SMTP RFC standard line ending.
570 const CRLF = "\r\n";
573 * Constructor.
574 * @param boolean $exceptions Should we throw external exceptions?
576 public function __construct($exceptions = false)
578 $this->exceptions = ($exceptions == true);
582 * Destructor.
584 public function __destruct()
586 if ($this->Mailer == 'smtp') { //close any open SMTP connection nicely
587 $this->smtpClose();
592 * Call mail() in a safe_mode-aware fashion.
593 * Also, unless sendmail_path points to sendmail (or something that
594 * claims to be sendmail), don't pass params (not a perfect fix,
595 * but it will do)
596 * @param string $to To
597 * @param string $subject Subject
598 * @param string $body Message Body
599 * @param string $header Additional Header(s)
600 * @param string $params Params
601 * @access private
602 * @return boolean
604 private function mailPassthru($to, $subject, $body, $header, $params)
606 //Check overloading of mail function to avoid double-encoding
607 if (ini_get('mbstring.func_overload') & 1) {
608 $subject = $this->secureHeader($subject);
609 } else {
610 $subject = $this->encodeHeader($this->secureHeader($subject));
612 if (ini_get('safe_mode') || !($this->UseSendmailOptions)) {
613 $result = @mail($to, $subject, $body, $header);
614 } else {
615 $result = @mail($to, $subject, $body, $header, $params);
617 return $result;
621 * Output debugging info via user-defined method.
622 * Only generates output if SMTP debug output is enabled (@see SMTP::$do_debug).
623 * @see PHPMailer::$Debugoutput
624 * @see PHPMailer::$SMTPDebug
625 * @param string $str
627 protected function edebug($str)
629 if ($this->SMTPDebug <= 0) {
630 return;
632 if (is_callable($this->Debugoutput)) {
633 call_user_func($this->Debugoutput, $str, $this->SMTPDebug);
634 return;
636 switch ($this->Debugoutput) {
637 case 'error_log':
638 //Don't output, just log
639 error_log($str);
640 break;
641 case 'html':
642 //Cleans up output a bit for a better looking, HTML-safe output
643 echo htmlentities(
644 preg_replace('/[\r\n]+/', '', $str),
645 ENT_QUOTES,
646 'UTF-8'
648 . "<br>\n";
649 break;
650 case 'echo':
651 default:
652 //Normalize line breaks
653 $str = preg_replace('/(\r\n|\r|\n)/ms', "\n", $str);
654 echo gmdate('Y-m-d H:i:s') . "\t" . str_replace(
655 "\n",
656 "\n \t ",
657 trim($str)
658 ) . "\n";
663 * Sets message type to HTML or plain.
664 * @param boolean $isHtml True for HTML mode.
665 * @return void
667 public function isHTML($isHtml = true)
669 if ($isHtml) {
670 $this->ContentType = 'text/html';
671 } else {
672 $this->ContentType = 'text/plain';
677 * Send messages using SMTP.
678 * @return void
680 public function isSMTP()
682 $this->Mailer = 'smtp';
686 * Send messages using PHP's mail() function.
687 * @return void
689 public function isMail()
691 $this->Mailer = 'mail';
695 * Send messages using $Sendmail.
696 * @return void
698 public function isSendmail()
700 $ini_sendmail_path = ini_get('sendmail_path');
702 if (!stristr($ini_sendmail_path, 'sendmail')) {
703 $this->Sendmail = '/usr/sbin/sendmail';
704 } else {
705 $this->Sendmail = $ini_sendmail_path;
707 $this->Mailer = 'sendmail';
711 * Send messages using qmail.
712 * @return void
714 public function isQmail()
716 $ini_sendmail_path = ini_get('sendmail_path');
718 if (!stristr($ini_sendmail_path, 'qmail')) {
719 $this->Sendmail = '/var/qmail/bin/qmail-inject';
720 } else {
721 $this->Sendmail = $ini_sendmail_path;
723 $this->Mailer = 'qmail';
727 * Add a "To" address.
728 * @param string $address
729 * @param string $name
730 * @return boolean true on success, false if address already used
732 public function addAddress($address, $name = '')
734 return $this->addAnAddress('to', $address, $name);
738 * Add a "CC" address.
739 * @note: This function works with the SMTP mailer on win32, not with the "mail" mailer.
740 * @param string $address
741 * @param string $name
742 * @return boolean true on success, false if address already used
744 public function addCC($address, $name = '')
746 return $this->addAnAddress('cc', $address, $name);
750 * Add a "BCC" address.
751 * @note: This function works with the SMTP mailer on win32, not with the "mail" mailer.
752 * @param string $address
753 * @param string $name
754 * @return boolean true on success, false if address already used
756 public function addBCC($address, $name = '')
758 return $this->addAnAddress('bcc', $address, $name);
762 * Add a "Reply-to" address.
763 * @param string $address
764 * @param string $name
765 * @return boolean
767 public function addReplyTo($address, $name = '')
769 return $this->addAnAddress('Reply-To', $address, $name);
773 * Add an address to one of the recipient arrays.
774 * Addresses that have been added already return false, but do not throw exceptions
775 * @param string $kind One of 'to', 'cc', 'bcc', 'ReplyTo'
776 * @param string $address The email address to send to
777 * @param string $name
778 * @throws phpmailerException
779 * @return boolean true on success, false if address already used or invalid in some way
780 * @access protected
782 protected function addAnAddress($kind, $address, $name = '')
784 if (!preg_match('/^(to|cc|bcc|Reply-To)$/', $kind)) {
785 $this->setError($this->lang('Invalid recipient array') . ': ' . $kind);
786 $this->edebug($this->lang('Invalid recipient array') . ': ' . $kind);
787 if ($this->exceptions) {
788 throw new phpmailerException('Invalid recipient array: ' . $kind);
790 return false;
792 $address = trim($address);
793 $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
794 if (!$this->validateAddress($address)) {
795 $this->setError($this->lang('invalid_address') . ': ' . $address);
796 $this->edebug($this->lang('invalid_address') . ': ' . $address);
797 if ($this->exceptions) {
798 throw new phpmailerException($this->lang('invalid_address') . ': ' . $address);
800 return false;
802 if ($kind != 'Reply-To') {
803 if (!isset($this->all_recipients[strtolower($address)])) {
804 array_push($this->$kind, array($address, $name));
805 $this->all_recipients[strtolower($address)] = true;
806 return true;
808 } else {
809 if (!array_key_exists(strtolower($address), $this->ReplyTo)) {
810 $this->ReplyTo[strtolower($address)] = array($address, $name);
811 return true;
814 return false;
818 * Set the From and FromName properties.
819 * @param string $address
820 * @param string $name
821 * @param boolean $auto Whether to also set the Sender address, defaults to true
822 * @throws phpmailerException
823 * @return boolean
825 public function setFrom($address, $name = '', $auto = true)
827 $address = trim($address);
828 $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
829 if (!$this->validateAddress($address)) {
830 $this->setError($this->lang('invalid_address') . ': ' . $address);
831 $this->edebug($this->lang('invalid_address') . ': ' . $address);
832 if ($this->exceptions) {
833 throw new phpmailerException($this->lang('invalid_address') . ': ' . $address);
835 return false;
837 $this->From = $address;
838 $this->FromName = $name;
839 if ($auto) {
840 if (empty($this->Sender)) {
841 $this->Sender = $address;
844 return true;
848 * Return the Message-ID header of the last email.
849 * Technically this is the value from the last time the headers were created,
850 * but it's also the message ID of the last sent message except in
851 * pathological cases.
852 * @return string
854 public function getLastMessageID()
856 return $this->lastMessageID;
860 * Check that a string looks like an email address.
861 * @param string $address The email address to check
862 * @param string $patternselect A selector for the validation pattern to use :
863 * * `auto` Pick strictest one automatically;
864 * * `pcre8` Use the squiloople.com pattern, requires PCRE > 8.0, PHP >= 5.3.2, 5.2.14;
865 * * `pcre` Use old PCRE implementation;
866 * * `php` Use PHP built-in FILTER_VALIDATE_EMAIL; same as pcre8 but does not allow 'dotless' domains;
867 * * `html5` Use the pattern given by the HTML5 spec for 'email' type form input elements.
868 * * `noregex` Don't use a regex: super fast, really dumb.
869 * @return boolean
870 * @static
871 * @access public
873 public static function validateAddress($address, $patternselect = 'auto')
875 if (!$patternselect or $patternselect == 'auto') {
876 //Check this constant first so it works when extension_loaded() is disabled by safe mode
877 //Constant was added in PHP 5.2.4
878 if (defined('PCRE_VERSION')) {
879 //This pattern can get stuck in a recursive loop in PCRE <= 8.0.2
880 if (version_compare(PCRE_VERSION, '8.0.3') >= 0) {
881 $patternselect = 'pcre8';
882 } else {
883 $patternselect = 'pcre';
885 } elseif (function_exists('extension_loaded') and extension_loaded('pcre')) {
886 //Fall back to older PCRE
887 $patternselect = 'pcre';
888 } else {
889 //Filter_var appeared in PHP 5.2.0 and does not require the PCRE extension
890 if (version_compare(PHP_VERSION, '5.2.0') >= 0) {
891 $patternselect = 'php';
892 } else {
893 $patternselect = 'noregex';
897 switch ($patternselect) {
898 case 'pcre8':
900 * Uses the same RFC5322 regex on which FILTER_VALIDATE_EMAIL is based, but allows dotless domains.
901 * @link http://squiloople.com/2009/12/20/email-address-validation/
902 * @copyright 2009-2010 Michael Rushton
903 * Feel free to use and redistribute this code. But please keep this copyright notice.
905 return (boolean)preg_match(
906 '/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)' .
907 '((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)' .
908 '(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)' .
909 '([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*' .
910 '(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)' .
911 '(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}' .
912 '|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:' .
913 '|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}' .
914 '|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD',
915 $address
917 case 'pcre':
918 //An older regex that doesn't need a recent PCRE
919 return (boolean)preg_match(
920 '/^(?!(?>"?(?>\\\[ -~]|[^"])"?){255,})(?!(?>"?(?>\\\[ -~]|[^"])"?){65,}@)(?>' .
921 '[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*")' .
922 '(?>\.(?>[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*"))*' .
923 '@(?>(?![a-z0-9-]{64,})(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>\.(?![a-z0-9-]{64,})' .
924 '(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)){0,126}|\[(?:(?>IPv6:(?>(?>[a-f0-9]{1,4})(?>:' .
925 '[a-f0-9]{1,4}){7}|(?!(?:.*[a-f0-9][:\]]){8,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?' .
926 '::(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?))|(?>(?>IPv6:(?>[a-f0-9]{1,4}(?>:' .
927 '[a-f0-9]{1,4}){5}:|(?!(?:.*[a-f0-9]:){6,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4})?' .
928 '::(?>(?:[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4}):)?))?(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}' .
929 '|[1-9]?[0-9])(?>\.(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}))\])$/isD',
930 $address
932 case 'html5':
934 * This is the pattern used in the HTML5 spec for validation of 'email' type form input elements.
935 * @link http://www.whatwg.org/specs/web-apps/current-work/#e-mail-state-(type=email)
937 return (boolean)preg_match(
938 '/^[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}' .
939 '[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/sD',
940 $address
942 case 'noregex':
943 //No PCRE! Do something _very_ approximate!
944 //Check the address is 3 chars or longer and contains an @ that's not the first or last char
945 return (strlen($address) >= 3
946 and strpos($address, '@') >= 1
947 and strpos($address, '@') != strlen($address) - 1);
948 case 'php':
949 default:
950 return (boolean)filter_var($address, FILTER_VALIDATE_EMAIL);
955 * Create a message and send it.
956 * Uses the sending method specified by $Mailer.
957 * @throws phpmailerException
958 * @return boolean false on error - See the ErrorInfo property for details of the error.
960 public function send()
962 try {
963 if (!$this->preSend()) {
964 return false;
966 return $this->postSend();
967 } catch (phpmailerException $exc) {
968 $this->mailHeader = '';
969 $this->setError($exc->getMessage());
970 if ($this->exceptions) {
971 throw $exc;
973 return false;
978 * Prepare a message for sending.
979 * @throws phpmailerException
980 * @return boolean
982 public function preSend()
984 try {
985 $this->mailHeader = '';
986 if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) {
987 throw new phpmailerException($this->lang('provide_address'), self::STOP_CRITICAL);
990 // Set whether the message is multipart/alternative
991 if (!empty($this->AltBody)) {
992 $this->ContentType = 'multipart/alternative';
995 $this->error_count = 0; // reset errors
996 $this->setMessageType();
997 // Refuse to send an empty message unless we are specifically allowing it
998 if (!$this->AllowEmpty and empty($this->Body)) {
999 throw new phpmailerException($this->lang('empty_message'), self::STOP_CRITICAL);
1002 $this->MIMEHeader = $this->createHeader();
1003 $this->MIMEBody = $this->createBody();
1005 // To capture the complete message when using mail(), create
1006 // an extra header list which createHeader() doesn't fold in
1007 if ($this->Mailer == 'mail') {
1008 if (count($this->to) > 0) {
1009 $this->mailHeader .= $this->addrAppend('To', $this->to);
1010 } else {
1011 $this->mailHeader .= $this->headerLine('To', 'undisclosed-recipients:;');
1013 $this->mailHeader .= $this->headerLine(
1014 'Subject',
1015 $this->encodeHeader($this->secureHeader(trim($this->Subject)))
1019 // Sign with DKIM if enabled
1020 if (!empty($this->DKIM_domain)
1021 && !empty($this->DKIM_private)
1022 && !empty($this->DKIM_selector)
1023 && !empty($this->DKIM_domain)
1024 && file_exists($this->DKIM_private)) {
1025 $header_dkim = $this->DKIM_Add(
1026 $this->MIMEHeader . $this->mailHeader,
1027 $this->encodeHeader($this->secureHeader($this->Subject)),
1028 $this->MIMEBody
1030 $this->MIMEHeader = rtrim($this->MIMEHeader, "\r\n ") . self::CRLF .
1031 str_replace("\r\n", "\n", $header_dkim) . self::CRLF;
1033 return true;
1035 } catch (phpmailerException $exc) {
1036 $this->setError($exc->getMessage());
1037 if ($this->exceptions) {
1038 throw $exc;
1040 return false;
1045 * Actually send a message.
1046 * Send the email via the selected mechanism
1047 * @throws phpmailerException
1048 * @return boolean
1050 public function postSend()
1052 try {
1053 // Choose the mailer and send through it
1054 switch ($this->Mailer) {
1055 case 'sendmail':
1056 case 'qmail':
1057 return $this->sendmailSend($this->MIMEHeader, $this->MIMEBody);
1058 case 'smtp':
1059 return $this->smtpSend($this->MIMEHeader, $this->MIMEBody);
1060 case 'mail':
1061 return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
1062 default:
1063 $sendMethod = $this->Mailer.'Send';
1064 if (method_exists($this, $sendMethod)) {
1065 return $this->$sendMethod($this->MIMEHeader, $this->MIMEBody);
1068 return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
1070 } catch (phpmailerException $exc) {
1071 $this->setError($exc->getMessage());
1072 $this->edebug($exc->getMessage());
1073 if ($this->exceptions) {
1074 throw $exc;
1077 return false;
1081 * Send mail using the $Sendmail program.
1082 * @param string $header The message headers
1083 * @param string $body The message body
1084 * @see PHPMailer::$Sendmail
1085 * @throws phpmailerException
1086 * @access protected
1087 * @return boolean
1089 protected function sendmailSend($header, $body)
1091 if ($this->Sender != '') {
1092 if ($this->Mailer == 'qmail') {
1093 $sendmail = sprintf('%s -f%s', escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
1094 } else {
1095 $sendmail = sprintf('%s -oi -f%s -t', escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
1097 } else {
1098 if ($this->Mailer == 'qmail') {
1099 $sendmail = sprintf('%s', escapeshellcmd($this->Sendmail));
1100 } else {
1101 $sendmail = sprintf('%s -oi -t', escapeshellcmd($this->Sendmail));
1104 if ($this->SingleTo === true) {
1105 foreach ($this->SingleToArray as $toAddr) {
1106 if (!@$mail = popen($sendmail, 'w')) {
1107 throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1109 fputs($mail, 'To: ' . $toAddr . "\n");
1110 fputs($mail, $header);
1111 fputs($mail, $body);
1112 $result = pclose($mail);
1113 $this->doCallback(
1114 ($result == 0),
1115 array($toAddr),
1116 $this->cc,
1117 $this->bcc,
1118 $this->Subject,
1119 $body,
1120 $this->From
1122 if ($result != 0) {
1123 throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1126 } else {
1127 if (!@$mail = popen($sendmail, 'w')) {
1128 throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1130 fputs($mail, $header);
1131 fputs($mail, $body);
1132 $result = pclose($mail);
1133 $this->doCallback(($result == 0), $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From);
1134 if ($result != 0) {
1135 throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1138 return true;
1142 * Send mail using the PHP mail() function.
1143 * @param string $header The message headers
1144 * @param string $body The message body
1145 * @link http://www.php.net/manual/en/book.mail.php
1146 * @throws phpmailerException
1147 * @access protected
1148 * @return boolean
1150 protected function mailSend($header, $body)
1152 $toArr = array();
1153 foreach ($this->to as $toaddr) {
1154 $toArr[] = $this->addrFormat($toaddr);
1156 $to = implode(', ', $toArr);
1158 if (empty($this->Sender)) {
1159 $params = ' ';
1160 } else {
1161 $params = sprintf('-f%s', $this->Sender);
1163 if ($this->Sender != '' and !ini_get('safe_mode')) {
1164 $old_from = ini_get('sendmail_from');
1165 ini_set('sendmail_from', $this->Sender);
1167 $result = false;
1168 if ($this->SingleTo === true && count($toArr) > 1) {
1169 foreach ($toArr as $toAddr) {
1170 $result = $this->mailPassthru($toAddr, $this->Subject, $body, $header, $params);
1171 $this->doCallback($result, array($toAddr), $this->cc, $this->bcc, $this->Subject, $body, $this->From);
1173 } else {
1174 $result = $this->mailPassthru($to, $this->Subject, $body, $header, $params);
1175 $this->doCallback($result, $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From);
1177 if (isset($old_from)) {
1178 ini_set('sendmail_from', $old_from);
1180 if (!$result) {
1181 throw new phpmailerException($this->lang('instantiate'), self::STOP_CRITICAL);
1183 return true;
1187 * Get an instance to use for SMTP operations.
1188 * Override this function to load your own SMTP implementation
1189 * @return SMTP
1191 public function getSMTPInstance()
1193 if (!is_object($this->smtp)) {
1194 $this->smtp = new SMTP;
1196 return $this->smtp;
1200 * Send mail via SMTP.
1201 * Returns false if there is a bad MAIL FROM, RCPT, or DATA input.
1202 * Uses the PHPMailerSMTP class by default.
1203 * @see PHPMailer::getSMTPInstance() to use a different class.
1204 * @param string $header The message headers
1205 * @param string $body The message body
1206 * @throws phpmailerException
1207 * @uses SMTP
1208 * @access protected
1209 * @return boolean
1211 protected function smtpSend($header, $body)
1213 $bad_rcpt = array();
1215 if (!$this->smtpConnect()) {
1216 throw new phpmailerException($this->lang('smtp_connect_failed'), self::STOP_CRITICAL);
1218 $smtp_from = ($this->Sender == '') ? $this->From : $this->Sender;
1219 if (!$this->smtp->mail($smtp_from)) {
1220 $this->setError($this->lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp->getError()));
1221 throw new phpmailerException($this->ErrorInfo, self::STOP_CRITICAL);
1224 // Attempt to send to all recipients
1225 foreach ($this->to as $to) {
1226 if (!$this->smtp->recipient($to[0])) {
1227 $bad_rcpt[] = $to[0];
1228 $isSent = false;
1229 } else {
1230 $isSent = true;
1232 $this->doCallback($isSent, array($to[0]), array(), array(), $this->Subject, $body, $this->From);
1234 foreach ($this->cc as $cc) {
1235 if (!$this->smtp->recipient($cc[0])) {
1236 $bad_rcpt[] = $cc[0];
1237 $isSent = false;
1238 } else {
1239 $isSent = true;
1241 $this->doCallback($isSent, array(), array($cc[0]), array(), $this->Subject, $body, $this->From);
1243 foreach ($this->bcc as $bcc) {
1244 if (!$this->smtp->recipient($bcc[0])) {
1245 $bad_rcpt[] = $bcc[0];
1246 $isSent = false;
1247 } else {
1248 $isSent = true;
1250 $this->doCallback($isSent, array(), array(), array($bcc[0]), $this->Subject, $body, $this->From);
1253 // Only send the DATA command if we have viable recipients
1254 if ((count($this->all_recipients) > count($bad_rcpt)) and !$this->smtp->data($header . $body)) {
1255 throw new phpmailerException($this->lang('data_not_accepted'), self::STOP_CRITICAL);
1257 if ($this->SMTPKeepAlive == true) {
1258 $this->smtp->reset();
1259 } else {
1260 $this->smtp->quit();
1261 $this->smtp->close();
1263 if (count($bad_rcpt) > 0) { // Create error message for any bad addresses
1264 throw new phpmailerException(
1265 $this->lang('recipients_failed') . implode(', ', $bad_rcpt),
1266 self::STOP_CONTINUE
1269 return true;
1273 * Initiate a connection to an SMTP server.
1274 * Returns false if the operation failed.
1275 * @param array $options An array of options compatible with stream_context_create()
1276 * @uses SMTP
1277 * @access public
1278 * @throws phpmailerException
1279 * @return boolean
1281 public function smtpConnect($options = array())
1283 if (is_null($this->smtp)) {
1284 $this->smtp = $this->getSMTPInstance();
1287 // Already connected?
1288 if ($this->smtp->connected()) {
1289 return true;
1292 $this->smtp->setTimeout($this->Timeout);
1293 $this->smtp->setDebugLevel($this->SMTPDebug);
1294 $this->smtp->setDebugOutput($this->Debugoutput);
1295 $this->smtp->setVerp($this->do_verp);
1296 $hosts = explode(';', $this->Host);
1297 $lastexception = null;
1299 foreach ($hosts as $hostentry) {
1300 $hostinfo = array();
1301 if (!preg_match('/^((ssl|tls):\/\/)*([a-zA-Z0-9\.-]*):?([0-9]*)$/', trim($hostentry), $hostinfo)) {
1302 // Not a valid host entry
1303 continue;
1305 // $hostinfo[2]: optional ssl or tls prefix
1306 // $hostinfo[3]: the hostname
1307 // $hostinfo[4]: optional port number
1308 // The host string prefix can temporarily override the current setting for SMTPSecure
1309 // If it's not specified, the default value is used
1310 $prefix = '';
1311 $tls = ($this->SMTPSecure == 'tls');
1312 if ($hostinfo[2] == 'ssl' or ($hostinfo[2] == '' and $this->SMTPSecure == 'ssl')) {
1313 $prefix = 'ssl://';
1314 $tls = false; // Can't have SSL and TLS at once
1315 } elseif ($hostinfo[2] == 'tls') {
1316 $tls = true;
1317 // tls doesn't use a prefix
1319 $host = $hostinfo[3];
1320 $port = $this->Port;
1321 $tport = (integer)$hostinfo[4];
1322 if ($tport > 0 and $tport < 65536) {
1323 $port = $tport;
1325 if ($this->smtp->connect($prefix . $host, $port, $this->Timeout, $options)) {
1326 try {
1327 if ($this->Helo) {
1328 $hello = $this->Helo;
1329 } else {
1330 $hello = $this->serverHostname();
1332 $this->smtp->hello($hello);
1334 if ($tls) {
1335 if (!$this->smtp->startTLS()) {
1336 throw new phpmailerException($this->lang('connect_host'));
1338 // We must resend HELO after tls negotiation
1339 $this->smtp->hello($hello);
1341 if ($this->SMTPAuth) {
1342 if (!$this->smtp->authenticate(
1343 $this->Username,
1344 $this->Password,
1345 $this->AuthType,
1346 $this->Realm,
1347 $this->Workstation
1350 throw new phpmailerException($this->lang('authenticate'));
1353 return true;
1354 } catch (phpmailerException $exc) {
1355 $lastexception = $exc;
1356 // We must have connected, but then failed TLS or Auth, so close connection nicely
1357 $this->smtp->quit();
1361 // If we get here, all connection attempts have failed, so close connection hard
1362 $this->smtp->close();
1363 // As we've caught all exceptions, just report whatever the last one was
1364 if ($this->exceptions and !is_null($lastexception)) {
1365 throw $lastexception;
1367 return false;
1371 * Close the active SMTP session if one exists.
1372 * @return void
1374 public function smtpClose()
1376 if ($this->smtp !== null) {
1377 if ($this->smtp->connected()) {
1378 $this->smtp->quit();
1379 $this->smtp->close();
1385 * Set the language for error messages.
1386 * Returns false if it cannot load the language file.
1387 * The default language is English.
1388 * @param string $langcode ISO 639-1 2-character language code (e.g. French is "fr")
1389 * @param string $lang_path Path to the language file directory, with trailing separator (slash)
1390 * @return boolean
1391 * @access public
1393 public function setLanguage($langcode = 'en', $lang_path = '')
1395 // Define full set of translatable strings in English
1396 $PHPMAILER_LANG = array(
1397 'authenticate' => 'SMTP Error: Could not authenticate.',
1398 'connect_host' => 'SMTP Error: Could not connect to SMTP host.',
1399 'data_not_accepted' => 'SMTP Error: data not accepted.',
1400 'empty_message' => 'Message body empty',
1401 'encoding' => 'Unknown encoding: ',
1402 'execute' => 'Could not execute: ',
1403 'file_access' => 'Could not access file: ',
1404 'file_open' => 'File Error: Could not open file: ',
1405 'from_failed' => 'The following From address failed: ',
1406 'instantiate' => 'Could not instantiate mail function.',
1407 'invalid_address' => 'Invalid address',
1408 'mailer_not_supported' => ' mailer is not supported.',
1409 'provide_address' => 'You must provide at least one recipient email address.',
1410 'recipients_failed' => 'SMTP Error: The following recipients failed: ',
1411 'signing' => 'Signing Error: ',
1412 'smtp_connect_failed' => 'SMTP connect() failed.',
1413 'smtp_error' => 'SMTP server error: ',
1414 'variable_set' => 'Cannot set or reset variable: '
1416 if (empty($lang_path)) {
1417 // Calculate an absolute path so it can work if CWD is not here
1418 $lang_path = dirname(__FILE__). DIRECTORY_SEPARATOR . 'language'. DIRECTORY_SEPARATOR;
1420 $foundlang = true;
1421 $lang_file = $lang_path . 'phpmailer.lang-' . $langcode . '.php';
1422 if ($langcode != 'en') { // There is no English translation file
1423 // Make sure language file path is readable
1424 if (!is_readable($lang_file)) {
1425 $foundlang = false;
1426 } else {
1427 // Overwrite language-specific strings.
1428 // This way we'll never have missing translations.
1429 $foundlang = include $lang_file;
1432 $this->language = $PHPMAILER_LANG;
1433 return ($foundlang == true); // Returns false if language not found
1437 * Get the array of strings for the current language.
1438 * @return array
1440 public function getTranslations()
1442 return $this->language;
1446 * Create recipient headers.
1447 * @access public
1448 * @param string $type
1449 * @param array $addr An array of recipient,
1450 * where each recipient is a 2-element indexed array with element 0 containing an address
1451 * and element 1 containing a name, like:
1452 * array(array('joe@example.com', 'Joe User'), array('zoe@example.com', 'Zoe User'))
1453 * @return string
1455 public function addrAppend($type, $addr)
1457 $addresses = array();
1458 foreach ($addr as $address) {
1459 $addresses[] = $this->addrFormat($address);
1461 return $type . ': ' . implode(', ', $addresses) . $this->LE;
1465 * Format an address for use in a message header.
1466 * @access public
1467 * @param array $addr A 2-element indexed array, element 0 containing an address, element 1 containing a name
1468 * like array('joe@example.com', 'Joe User')
1469 * @return string
1471 public function addrFormat($addr)
1473 if (empty($addr[1])) { // No name provided
1474 return $this->secureHeader($addr[0]);
1475 } else {
1476 return $this->encodeHeader($this->secureHeader($addr[1]), 'phrase') . ' <' . $this->secureHeader(
1477 $addr[0]
1478 ) . '>';
1483 * Word-wrap message.
1484 * For use with mailers that do not automatically perform wrapping
1485 * and for quoted-printable encoded messages.
1486 * Original written by philippe.
1487 * @param string $message The message to wrap
1488 * @param integer $length The line length to wrap to
1489 * @param boolean $qp_mode Whether to run in Quoted-Printable mode
1490 * @access public
1491 * @return string
1493 public function wrapText($message, $length, $qp_mode = false)
1495 $soft_break = ($qp_mode) ? sprintf(' =%s', $this->LE) : $this->LE;
1496 // If utf-8 encoding is used, we will need to make sure we don't
1497 // split multibyte characters when we wrap
1498 $is_utf8 = (strtolower($this->CharSet) == 'utf-8');
1499 $lelen = strlen($this->LE);
1500 $crlflen = strlen(self::CRLF);
1502 $message = $this->fixEOL($message);
1503 if (substr($message, -$lelen) == $this->LE) {
1504 $message = substr($message, 0, -$lelen);
1507 $line = explode($this->LE, $message); // Magic. We know fixEOL uses $LE
1508 $message = '';
1509 for ($i = 0; $i < count($line); $i++) {
1510 $line_part = explode(' ', $line[$i]);
1511 $buf = '';
1512 for ($e = 0; $e < count($line_part); $e++) {
1513 $word = $line_part[$e];
1514 if ($qp_mode and (strlen($word) > $length)) {
1515 $space_left = $length - strlen($buf) - $crlflen;
1516 if ($e != 0) {
1517 if ($space_left > 20) {
1518 $len = $space_left;
1519 if ($is_utf8) {
1520 $len = $this->utf8CharBoundary($word, $len);
1521 } elseif (substr($word, $len - 1, 1) == '=') {
1522 $len--;
1523 } elseif (substr($word, $len - 2, 1) == '=') {
1524 $len -= 2;
1526 $part = substr($word, 0, $len);
1527 $word = substr($word, $len);
1528 $buf .= ' ' . $part;
1529 $message .= $buf . sprintf('=%s', self::CRLF);
1530 } else {
1531 $message .= $buf . $soft_break;
1533 $buf = '';
1535 while (strlen($word) > 0) {
1536 if ($length <= 0) {
1537 break;
1539 $len = $length;
1540 if ($is_utf8) {
1541 $len = $this->utf8CharBoundary($word, $len);
1542 } elseif (substr($word, $len - 1, 1) == '=') {
1543 $len--;
1544 } elseif (substr($word, $len - 2, 1) == '=') {
1545 $len -= 2;
1547 $part = substr($word, 0, $len);
1548 $word = substr($word, $len);
1550 if (strlen($word) > 0) {
1551 $message .= $part . sprintf('=%s', self::CRLF);
1552 } else {
1553 $buf = $part;
1556 } else {
1557 $buf_o = $buf;
1558 $buf .= ($e == 0) ? $word : (' ' . $word);
1560 if (strlen($buf) > $length and $buf_o != '') {
1561 $message .= $buf_o . $soft_break;
1562 $buf = $word;
1566 $message .= $buf . self::CRLF;
1569 return $message;
1573 * Find the last character boundary prior to $maxLength in a utf-8
1574 * quoted (printable) encoded string.
1575 * Original written by Colin Brown.
1576 * @access public
1577 * @param string $encodedText utf-8 QP text
1578 * @param integer $maxLength find last character boundary prior to this length
1579 * @return integer
1581 public function utf8CharBoundary($encodedText, $maxLength)
1583 $foundSplitPos = false;
1584 $lookBack = 3;
1585 while (!$foundSplitPos) {
1586 $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
1587 $encodedCharPos = strpos($lastChunk, '=');
1588 if ($encodedCharPos !== false) {
1589 // Found start of encoded character byte within $lookBack block.
1590 // Check the encoded byte value (the 2 chars after the '=')
1591 $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
1592 $dec = hexdec($hex);
1593 if ($dec < 128) { // Single byte character.
1594 // If the encoded char was found at pos 0, it will fit
1595 // otherwise reduce maxLength to start of the encoded char
1596 $maxLength = ($encodedCharPos == 0) ? $maxLength :
1597 $maxLength - ($lookBack - $encodedCharPos);
1598 $foundSplitPos = true;
1599 } elseif ($dec >= 192) { // First byte of a multi byte character
1600 // Reduce maxLength to split at start of character
1601 $maxLength = $maxLength - ($lookBack - $encodedCharPos);
1602 $foundSplitPos = true;
1603 } elseif ($dec < 192) { // Middle byte of a multi byte character, look further back
1604 $lookBack += 3;
1606 } else {
1607 // No encoded character found
1608 $foundSplitPos = true;
1611 return $maxLength;
1615 * Set the body wrapping.
1616 * @access public
1617 * @return void
1619 public function setWordWrap()
1621 if ($this->WordWrap < 1) {
1622 return;
1625 switch ($this->message_type) {
1626 case 'alt':
1627 case 'alt_inline':
1628 case 'alt_attach':
1629 case 'alt_inline_attach':
1630 $this->AltBody = $this->wrapText($this->AltBody, $this->WordWrap);
1631 break;
1632 default:
1633 $this->Body = $this->wrapText($this->Body, $this->WordWrap);
1634 break;
1639 * Assemble message headers.
1640 * @access public
1641 * @return string The assembled headers
1643 public function createHeader()
1645 $result = '';
1647 // Set the boundaries
1648 $uniq_id = md5(uniqid(time()));
1649 $this->boundary[1] = 'b1_' . $uniq_id;
1650 $this->boundary[2] = 'b2_' . $uniq_id;
1651 $this->boundary[3] = 'b3_' . $uniq_id;
1653 if ($this->MessageDate == '') {
1654 $this->MessageDate = self::rfcDate();
1656 $result .= $this->headerLine('Date', $this->MessageDate);
1659 // To be created automatically by mail()
1660 if ($this->SingleTo === true) {
1661 if ($this->Mailer != 'mail') {
1662 foreach ($this->to as $toaddr) {
1663 $this->SingleToArray[] = $this->addrFormat($toaddr);
1666 } else {
1667 if (count($this->to) > 0) {
1668 if ($this->Mailer != 'mail') {
1669 $result .= $this->addrAppend('To', $this->to);
1671 } elseif (count($this->cc) == 0) {
1672 $result .= $this->headerLine('To', 'undisclosed-recipients:;');
1676 $result .= $this->addrAppend('From', array(array(trim($this->From), $this->FromName)));
1678 // sendmail and mail() extract Cc from the header before sending
1679 if (count($this->cc) > 0) {
1680 $result .= $this->addrAppend('Cc', $this->cc);
1683 // sendmail and mail() extract Bcc from the header before sending
1684 if ((
1685 $this->Mailer == 'sendmail' or $this->Mailer == 'qmail' or $this->Mailer == 'mail'
1687 and count($this->bcc) > 0
1689 $result .= $this->addrAppend('Bcc', $this->bcc);
1692 if (count($this->ReplyTo) > 0) {
1693 $result .= $this->addrAppend('Reply-To', $this->ReplyTo);
1696 // mail() sets the subject itself
1697 if ($this->Mailer != 'mail') {
1698 $result .= $this->headerLine('Subject', $this->encodeHeader($this->secureHeader($this->Subject)));
1701 if ($this->MessageID != '') {
1702 $this->lastMessageID = $this->MessageID;
1703 } else {
1704 $this->lastMessageID = sprintf('<%s@%s>', $uniq_id, $this->ServerHostname());
1706 $result .= $this->HeaderLine('Message-ID', $this->lastMessageID);
1707 $result .= $this->headerLine('X-Priority', $this->Priority);
1708 if ($this->XMailer == '') {
1709 $result .= $this->headerLine(
1710 'X-Mailer',
1711 'PHPMailer ' . $this->Version . ' (https://github.com/PHPMailer/PHPMailer/)'
1713 } else {
1714 $myXmailer = trim($this->XMailer);
1715 if ($myXmailer) {
1716 $result .= $this->headerLine('X-Mailer', $myXmailer);
1720 if ($this->ConfirmReadingTo != '') {
1721 $result .= $this->headerLine('Disposition-Notification-To', '<' . trim($this->ConfirmReadingTo) . '>');
1724 // Add custom headers
1725 for ($index = 0; $index < count($this->CustomHeader); $index++) {
1726 $result .= $this->headerLine(
1727 trim($this->CustomHeader[$index][0]),
1728 $this->encodeHeader(trim($this->CustomHeader[$index][1]))
1731 if (!$this->sign_key_file) {
1732 $result .= $this->headerLine('MIME-Version', '1.0');
1733 $result .= $this->getMailMIME();
1736 return $result;
1740 * Get the message MIME type headers.
1741 * @access public
1742 * @return string
1744 public function getMailMIME()
1746 $result = '';
1747 $ismultipart = true;
1748 switch ($this->message_type) {
1749 case 'inline':
1750 $result .= $this->headerLine('Content-Type', 'multipart/related;');
1751 $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
1752 break;
1753 case 'attach':
1754 case 'inline_attach':
1755 case 'alt_attach':
1756 case 'alt_inline_attach':
1757 $result .= $this->headerLine('Content-Type', 'multipart/mixed;');
1758 $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
1759 break;
1760 case 'alt':
1761 case 'alt_inline':
1762 $result .= $this->headerLine('Content-Type', 'multipart/alternative;');
1763 $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
1764 break;
1765 default:
1766 // Catches case 'plain': and case '':
1767 $result .= $this->textLine('Content-Type: ' . $this->ContentType . '; charset=' . $this->CharSet);
1768 $ismultipart = false;
1769 break;
1771 // RFC1341 part 5 says 7bit is assumed if not specified
1772 if ($this->Encoding != '7bit') {
1773 // RFC 2045 section 6.4 says multipart MIME parts may only use 7bit, 8bit or binary CTE
1774 if ($ismultipart) {
1775 if ($this->Encoding == '8bit') {
1776 $result .= $this->headerLine('Content-Transfer-Encoding', '8bit');
1778 // The only remaining alternatives are quoted-printable and base64, which are both 7bit compatible
1779 } else {
1780 $result .= $this->headerLine('Content-Transfer-Encoding', $this->Encoding);
1784 if ($this->Mailer != 'mail') {
1785 $result .= $this->LE;
1788 return $result;
1792 * Returns the whole MIME message.
1793 * Includes complete headers and body.
1794 * Only valid post preSend().
1795 * @see PHPMailer::preSend()
1796 * @access public
1797 * @return string
1799 public function getSentMIMEMessage()
1801 return $this->MIMEHeader . $this->mailHeader . self::CRLF . $this->MIMEBody;
1806 * Assemble the message body.
1807 * Returns an empty string on failure.
1808 * @access public
1809 * @throws phpmailerException
1810 * @return string The assembled message body
1812 public function createBody()
1814 $body = '';
1816 if ($this->sign_key_file) {
1817 $body .= $this->getMailMIME() . $this->LE;
1820 $this->setWordWrap();
1822 $bodyEncoding = $this->Encoding;
1823 $bodyCharSet = $this->CharSet;
1824 if ($bodyEncoding == '8bit' and !$this->has8bitChars($this->Body)) {
1825 $bodyEncoding = '7bit';
1826 $bodyCharSet = 'us-ascii';
1828 $altBodyEncoding = $this->Encoding;
1829 $altBodyCharSet = $this->CharSet;
1830 if ($altBodyEncoding == '8bit' and !$this->has8bitChars($this->AltBody)) {
1831 $altBodyEncoding = '7bit';
1832 $altBodyCharSet = 'us-ascii';
1834 switch ($this->message_type) {
1835 case 'inline':
1836 $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
1837 $body .= $this->encodeString($this->Body, $bodyEncoding);
1838 $body .= $this->LE . $this->LE;
1839 $body .= $this->attachAll('inline', $this->boundary[1]);
1840 break;
1841 case 'attach':
1842 $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
1843 $body .= $this->encodeString($this->Body, $bodyEncoding);
1844 $body .= $this->LE . $this->LE;
1845 $body .= $this->attachAll('attachment', $this->boundary[1]);
1846 break;
1847 case 'inline_attach':
1848 $body .= $this->textLine('--' . $this->boundary[1]);
1849 $body .= $this->headerLine('Content-Type', 'multipart/related;');
1850 $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
1851 $body .= $this->LE;
1852 $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, '', $bodyEncoding);
1853 $body .= $this->encodeString($this->Body, $bodyEncoding);
1854 $body .= $this->LE . $this->LE;
1855 $body .= $this->attachAll('inline', $this->boundary[2]);
1856 $body .= $this->LE;
1857 $body .= $this->attachAll('attachment', $this->boundary[1]);
1858 break;
1859 case 'alt':
1860 $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, 'text/plain', $altBodyEncoding);
1861 $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
1862 $body .= $this->LE . $this->LE;
1863 $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, 'text/html', $bodyEncoding);
1864 $body .= $this->encodeString($this->Body, $bodyEncoding);
1865 $body .= $this->LE . $this->LE;
1866 if (!empty($this->Ical)) {
1867 $body .= $this->getBoundary($this->boundary[1], '', 'text/calendar; method=REQUEST', '');
1868 $body .= $this->encodeString($this->Ical, $this->Encoding);
1869 $body .= $this->LE . $this->LE;
1871 $body .= $this->endBoundary($this->boundary[1]);
1872 break;
1873 case 'alt_inline':
1874 $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, 'text/plain', $altBodyEncoding);
1875 $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
1876 $body .= $this->LE . $this->LE;
1877 $body .= $this->textLine('--' . $this->boundary[1]);
1878 $body .= $this->headerLine('Content-Type', 'multipart/related;');
1879 $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
1880 $body .= $this->LE;
1881 $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, 'text/html', $bodyEncoding);
1882 $body .= $this->encodeString($this->Body, $bodyEncoding);
1883 $body .= $this->LE . $this->LE;
1884 $body .= $this->attachAll('inline', $this->boundary[2]);
1885 $body .= $this->LE;
1886 $body .= $this->endBoundary($this->boundary[1]);
1887 break;
1888 case 'alt_attach':
1889 $body .= $this->textLine('--' . $this->boundary[1]);
1890 $body .= $this->headerLine('Content-Type', 'multipart/alternative;');
1891 $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
1892 $body .= $this->LE;
1893 $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, 'text/plain', $altBodyEncoding);
1894 $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
1895 $body .= $this->LE . $this->LE;
1896 $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, 'text/html', $bodyEncoding);
1897 $body .= $this->encodeString($this->Body, $bodyEncoding);
1898 $body .= $this->LE . $this->LE;
1899 $body .= $this->endBoundary($this->boundary[2]);
1900 $body .= $this->LE;
1901 $body .= $this->attachAll('attachment', $this->boundary[1]);
1902 break;
1903 case 'alt_inline_attach':
1904 $body .= $this->textLine('--' . $this->boundary[1]);
1905 $body .= $this->headerLine('Content-Type', 'multipart/alternative;');
1906 $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
1907 $body .= $this->LE;
1908 $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, 'text/plain', $altBodyEncoding);
1909 $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
1910 $body .= $this->LE . $this->LE;
1911 $body .= $this->textLine('--' . $this->boundary[2]);
1912 $body .= $this->headerLine('Content-Type', 'multipart/related;');
1913 $body .= $this->textLine("\tboundary=\"" . $this->boundary[3] . '"');
1914 $body .= $this->LE;
1915 $body .= $this->getBoundary($this->boundary[3], $bodyCharSet, 'text/html', $bodyEncoding);
1916 $body .= $this->encodeString($this->Body, $bodyEncoding);
1917 $body .= $this->LE . $this->LE;
1918 $body .= $this->attachAll('inline', $this->boundary[3]);
1919 $body .= $this->LE;
1920 $body .= $this->endBoundary($this->boundary[2]);
1921 $body .= $this->LE;
1922 $body .= $this->attachAll('attachment', $this->boundary[1]);
1923 break;
1924 default:
1925 // catch case 'plain' and case ''
1926 $body .= $this->encodeString($this->Body, $bodyEncoding);
1927 break;
1930 if ($this->isError()) {
1931 $body = '';
1932 } elseif ($this->sign_key_file) {
1933 try {
1934 if (!defined('PKCS7_TEXT')) {
1935 throw new phpmailerException($this->lang('signing') . ' OpenSSL extension missing.');
1937 // @TODO would be nice to use php://temp streams here, but need to wrap for PHP < 5.1
1938 $file = tempnam(sys_get_temp_dir(), 'mail');
1939 file_put_contents($file, $body); // @TODO check this worked
1940 $signed = tempnam(sys_get_temp_dir(), 'signed');
1941 if (@openssl_pkcs7_sign(
1942 $file,
1943 $signed,
1944 'file://' . realpath($this->sign_cert_file),
1945 array('file://' . realpath($this->sign_key_file), $this->sign_key_pass),
1946 null
1949 @unlink($file);
1950 $body = file_get_contents($signed);
1951 @unlink($signed);
1952 } else {
1953 @unlink($file);
1954 @unlink($signed);
1955 throw new phpmailerException($this->lang('signing') . openssl_error_string());
1957 } catch (phpmailerException $exc) {
1958 $body = '';
1959 if ($this->exceptions) {
1960 throw $exc;
1964 return $body;
1968 * Return the start of a message boundary.
1969 * @access protected
1970 * @param string $boundary
1971 * @param string $charSet
1972 * @param string $contentType
1973 * @param string $encoding
1974 * @return string
1976 protected function getBoundary($boundary, $charSet, $contentType, $encoding)
1978 $result = '';
1979 if ($charSet == '') {
1980 $charSet = $this->CharSet;
1982 if ($contentType == '') {
1983 $contentType = $this->ContentType;
1985 if ($encoding == '') {
1986 $encoding = $this->Encoding;
1988 $result .= $this->textLine('--' . $boundary);
1989 $result .= sprintf('Content-Type: %s; charset=%s', $contentType, $charSet);
1990 $result .= $this->LE;
1991 // RFC1341 part 5 says 7bit is assumed if not specified
1992 if ($encoding != '7bit') {
1993 $result .= $this->headerLine('Content-Transfer-Encoding', $encoding);
1995 $result .= $this->LE;
1997 return $result;
2001 * Return the end of a message boundary.
2002 * @access protected
2003 * @param string $boundary
2004 * @return string
2006 protected function endBoundary($boundary)
2008 return $this->LE . '--' . $boundary . '--' . $this->LE;
2012 * Set the message type.
2013 * PHPMailer only supports some preset message types,
2014 * not arbitrary MIME structures.
2015 * @access protected
2016 * @return void
2018 protected function setMessageType()
2020 $type = array();
2021 if ($this->alternativeExists()) {
2022 $type[] = 'alt';
2024 if ($this->inlineImageExists()) {
2025 $type[] = 'inline';
2027 if ($this->attachmentExists()) {
2028 $type[] = 'attach';
2030 $this->message_type = implode('_', $type);
2031 if ($this->message_type == '') {
2032 $this->message_type = 'plain';
2037 * Format a header line.
2038 * @access public
2039 * @param string $name
2040 * @param string $value
2041 * @return string
2043 public function headerLine($name, $value)
2045 return $name . ': ' . $value . $this->LE;
2049 * Return a formatted mail line.
2050 * @access public
2051 * @param string $value
2052 * @return string
2054 public function textLine($value)
2056 return $value . $this->LE;
2060 * Add an attachment from a path on the filesystem.
2061 * Returns false if the file could not be found or read.
2062 * @param string $path Path to the attachment.
2063 * @param string $name Overrides the attachment name.
2064 * @param string $encoding File encoding (see $Encoding).
2065 * @param string $type File extension (MIME) type.
2066 * @param string $disposition Disposition to use
2067 * @throws phpmailerException
2068 * @return boolean
2070 public function addAttachment($path, $name = '', $encoding = 'base64', $type = '', $disposition = 'attachment')
2072 try {
2073 if (!@is_file($path)) {
2074 throw new phpmailerException($this->lang('file_access') . $path, self::STOP_CONTINUE);
2077 // If a MIME type is not specified, try to work it out from the file name
2078 if ($type == '') {
2079 $type = self::filenameToType($path);
2082 $filename = basename($path);
2083 if ($name == '') {
2084 $name = $filename;
2087 $this->attachment[] = array(
2088 0 => $path,
2089 1 => $filename,
2090 2 => $name,
2091 3 => $encoding,
2092 4 => $type,
2093 5 => false, // isStringAttachment
2094 6 => $disposition,
2095 7 => 0
2098 } catch (phpmailerException $exc) {
2099 $this->setError($exc->getMessage());
2100 $this->edebug($exc->getMessage());
2101 if ($this->exceptions) {
2102 throw $exc;
2104 return false;
2106 return true;
2110 * Return the array of attachments.
2111 * @return array
2113 public function getAttachments()
2115 return $this->attachment;
2119 * Attach all file, string, and binary attachments to the message.
2120 * Returns an empty string on failure.
2121 * @access protected
2122 * @param string $disposition_type
2123 * @param string $boundary
2124 * @return string
2126 protected function attachAll($disposition_type, $boundary)
2128 // Return text of body
2129 $mime = array();
2130 $cidUniq = array();
2131 $incl = array();
2133 // Add all attachments
2134 foreach ($this->attachment as $attachment) {
2135 // Check if it is a valid disposition_filter
2136 if ($attachment[6] == $disposition_type) {
2137 // Check for string attachment
2138 $string = '';
2139 $path = '';
2140 $bString = $attachment[5];
2141 if ($bString) {
2142 $string = $attachment[0];
2143 } else {
2144 $path = $attachment[0];
2147 $inclhash = md5(serialize($attachment));
2148 if (in_array($inclhash, $incl)) {
2149 continue;
2151 $incl[] = $inclhash;
2152 $name = $attachment[2];
2153 $encoding = $attachment[3];
2154 $type = $attachment[4];
2155 $disposition = $attachment[6];
2156 $cid = $attachment[7];
2157 if ($disposition == 'inline' && isset($cidUniq[$cid])) {
2158 continue;
2160 $cidUniq[$cid] = true;
2162 $mime[] = sprintf('--%s%s', $boundary, $this->LE);
2163 $mime[] = sprintf(
2164 'Content-Type: %s; name="%s"%s',
2165 $type,
2166 $this->encodeHeader($this->secureHeader($name)),
2167 $this->LE
2169 // RFC1341 part 5 says 7bit is assumed if not specified
2170 if ($encoding != '7bit') {
2171 $mime[] = sprintf('Content-Transfer-Encoding: %s%s', $encoding, $this->LE);
2174 if ($disposition == 'inline') {
2175 $mime[] = sprintf('Content-ID: <%s>%s', $cid, $this->LE);
2178 // If a filename contains any of these chars, it should be quoted,
2179 // but not otherwise: RFC2183 & RFC2045 5.1
2180 // Fixes a warning in IETF's msglint MIME checker
2181 // Allow for bypassing the Content-Disposition header totally
2182 if (!(empty($disposition))) {
2183 $encoded_name = $this->encodeHeader($this->secureHeader($name));
2184 if (preg_match('/[ \(\)<>@,;:\\"\/\[\]\?=]/', $encoded_name)) {
2185 $mime[] = sprintf(
2186 'Content-Disposition: %s; filename="%s"%s',
2187 $disposition,
2188 $encoded_name,
2189 $this->LE . $this->LE
2191 } else {
2192 $mime[] = sprintf(
2193 'Content-Disposition: %s; filename=%s%s',
2194 $disposition,
2195 $encoded_name,
2196 $this->LE . $this->LE
2199 } else {
2200 $mime[] = $this->LE;
2203 // Encode as string attachment
2204 if ($bString) {
2205 $mime[] = $this->encodeString($string, $encoding);
2206 if ($this->isError()) {
2207 return '';
2209 $mime[] = $this->LE . $this->LE;
2210 } else {
2211 $mime[] = $this->encodeFile($path, $encoding);
2212 if ($this->isError()) {
2213 return '';
2215 $mime[] = $this->LE . $this->LE;
2220 $mime[] = sprintf('--%s--%s', $boundary, $this->LE);
2222 return implode('', $mime);
2226 * Encode a file attachment in requested format.
2227 * Returns an empty string on failure.
2228 * @param string $path The full path to the file
2229 * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
2230 * @throws phpmailerException
2231 * @see EncodeFile(encodeFile
2232 * @access protected
2233 * @return string
2235 protected function encodeFile($path, $encoding = 'base64')
2237 try {
2238 if (!is_readable($path)) {
2239 throw new phpmailerException($this->lang('file_open') . $path, self::STOP_CONTINUE);
2241 $magic_quotes = get_magic_quotes_runtime();
2242 if ($magic_quotes) {
2243 if (version_compare(PHP_VERSION, '5.3.0', '<')) {
2244 set_magic_quotes_runtime(false);
2245 } else {
2246 //Doesn't exist in PHP 5.4, but we don't need to check because
2247 //get_magic_quotes_runtime always returns false in 5.4+
2248 //so it will never get here
2249 ini_set('magic_quotes_runtime', 0);
2252 $file_buffer = file_get_contents($path);
2253 $file_buffer = $this->encodeString($file_buffer, $encoding);
2254 if ($magic_quotes) {
2255 if (version_compare(PHP_VERSION, '5.3.0', '<')) {
2256 set_magic_quotes_runtime($magic_quotes);
2257 } else {
2258 ini_set('magic_quotes_runtime', ($magic_quotes?'1':'0'));
2261 return $file_buffer;
2262 } catch (Exception $exc) {
2263 $this->setError($exc->getMessage());
2264 return '';
2269 * Encode a string in requested format.
2270 * Returns an empty string on failure.
2271 * @param string $str The text to encode
2272 * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
2273 * @access public
2274 * @return string
2276 public function encodeString($str, $encoding = 'base64')
2278 $encoded = '';
2279 switch (strtolower($encoding)) {
2280 case 'base64':
2281 $encoded = chunk_split(base64_encode($str), 76, $this->LE);
2282 break;
2283 case '7bit':
2284 case '8bit':
2285 $encoded = $this->fixEOL($str);
2286 // Make sure it ends with a line break
2287 if (substr($encoded, -(strlen($this->LE))) != $this->LE) {
2288 $encoded .= $this->LE;
2290 break;
2291 case 'binary':
2292 $encoded = $str;
2293 break;
2294 case 'quoted-printable':
2295 $encoded = $this->encodeQP($str);
2296 break;
2297 default:
2298 $this->setError($this->lang('encoding') . $encoding);
2299 break;
2301 return $encoded;
2305 * Encode a header string optimally.
2306 * Picks shortest of Q, B, quoted-printable or none.
2307 * @access public
2308 * @param string $str
2309 * @param string $position
2310 * @return string
2312 public function encodeHeader($str, $position = 'text')
2314 $matchcount = 0;
2315 switch (strtolower($position)) {
2316 case 'phrase':
2317 if (!preg_match('/[\200-\377]/', $str)) {
2318 // Can't use addslashes as we don't know the value of magic_quotes_sybase
2319 $encoded = addcslashes($str, "\0..\37\177\\\"");
2320 if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
2321 return ($encoded);
2322 } else {
2323 return ("\"$encoded\"");
2326 $matchcount = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
2327 break;
2328 /** @noinspection PhpMissingBreakStatementInspection */
2329 case 'comment':
2330 $matchcount = preg_match_all('/[()"]/', $str, $matches);
2331 // Intentional fall-through
2332 case 'text':
2333 default:
2334 $matchcount += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
2335 break;
2338 if ($matchcount == 0) { // There are no chars that need encoding
2339 return ($str);
2342 $maxlen = 75 - 7 - strlen($this->CharSet);
2343 // Try to select the encoding which should produce the shortest output
2344 if ($matchcount > strlen($str) / 3) {
2345 // More than a third of the content will need encoding, so B encoding will be most efficient
2346 $encoding = 'B';
2347 if (function_exists('mb_strlen') && $this->hasMultiBytes($str)) {
2348 // Use a custom function which correctly encodes and wraps long
2349 // multibyte strings without breaking lines within a character
2350 $encoded = $this->base64EncodeWrapMB($str, "\n");
2351 } else {
2352 $encoded = base64_encode($str);
2353 $maxlen -= $maxlen % 4;
2354 $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
2356 } else {
2357 $encoding = 'Q';
2358 $encoded = $this->encodeQ($str, $position);
2359 $encoded = $this->wrapText($encoded, $maxlen, true);
2360 $encoded = str_replace('=' . self::CRLF, "\n", trim($encoded));
2363 $encoded = preg_replace('/^(.*)$/m', ' =?' . $this->CharSet . "?$encoding?\\1?=", $encoded);
2364 $encoded = trim(str_replace("\n", $this->LE, $encoded));
2366 return $encoded;
2370 * Check if a string contains multi-byte characters.
2371 * @access public
2372 * @param string $str multi-byte text to wrap encode
2373 * @return boolean
2375 public function hasMultiBytes($str)
2377 if (function_exists('mb_strlen')) {
2378 return (strlen($str) > mb_strlen($str, $this->CharSet));
2379 } else { // Assume no multibytes (we can't handle without mbstring functions anyway)
2380 return false;
2385 * Does a string contain any 8-bit chars (in any charset)?
2386 * @param string $text
2387 * @return boolean
2389 public function has8bitChars($text)
2391 return (boolean)preg_match('/[\x80-\xFF]/', $text);
2395 * Encode and wrap long multibyte strings for mail headers
2396 * without breaking lines within a character.
2397 * Adapted from a function by paravoid
2398 * @link http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283
2399 * @access public
2400 * @param string $str multi-byte text to wrap encode
2401 * @param string $linebreak string to use as linefeed/end-of-line
2402 * @return string
2404 public function base64EncodeWrapMB($str, $linebreak = null)
2406 $start = '=?' . $this->CharSet . '?B?';
2407 $end = '?=';
2408 $encoded = '';
2409 if ($linebreak === null) {
2410 $linebreak = $this->LE;
2413 $mb_length = mb_strlen($str, $this->CharSet);
2414 // Each line must have length <= 75, including $start and $end
2415 $length = 75 - strlen($start) - strlen($end);
2416 // Average multi-byte ratio
2417 $ratio = $mb_length / strlen($str);
2418 // Base64 has a 4:3 ratio
2419 $avgLength = floor($length * $ratio * .75);
2421 for ($i = 0; $i < $mb_length; $i += $offset) {
2422 $lookBack = 0;
2423 do {
2424 $offset = $avgLength - $lookBack;
2425 $chunk = mb_substr($str, $i, $offset, $this->CharSet);
2426 $chunk = base64_encode($chunk);
2427 $lookBack++;
2428 } while (strlen($chunk) > $length);
2429 $encoded .= $chunk . $linebreak;
2432 // Chomp the last linefeed
2433 $encoded = substr($encoded, 0, -strlen($linebreak));
2434 return $encoded;
2438 * Encode a string in quoted-printable format.
2439 * According to RFC2045 section 6.7.
2440 * @access public
2441 * @param string $string The text to encode
2442 * @param integer $line_max Number of chars allowed on a line before wrapping
2443 * @return string
2444 * @link http://www.php.net/manual/en/function.quoted-printable-decode.php#89417 Adapted from this comment
2446 public function encodeQP($string, $line_max = 76)
2448 if (function_exists('quoted_printable_encode')) { // Use native function if it's available (>= PHP5.3)
2449 return $this->fixEOL(quoted_printable_encode($string));
2451 // Fall back to a pure PHP implementation
2452 $string = str_replace(
2453 array('%20', '%0D%0A.', '%0D%0A', '%'),
2454 array(' ', "\r\n=2E", "\r\n", '='),
2455 rawurlencode($string)
2457 $string = preg_replace('/[^\r\n]{' . ($line_max - 3) . '}[^=\r\n]{2}/', "$0=\r\n", $string);
2458 return $this->fixEOL($string);
2462 * Backward compatibility wrapper for an old QP encoding function that was removed.
2463 * @see PHPMailer::encodeQP()
2464 * @access public
2465 * @param string $string
2466 * @param integer $line_max
2467 * @param boolean $space_conv
2468 * @return string
2469 * @deprecated Use encodeQP instead.
2471 public function encodeQPphp(
2472 $string,
2473 $line_max = 76,
2474 /** @noinspection PhpUnusedParameterInspection */ $space_conv = false
2476 return $this->encodeQP($string, $line_max);
2480 * Encode a string using Q encoding.
2481 * @link http://tools.ietf.org/html/rfc2047
2482 * @param string $str the text to encode
2483 * @param string $position Where the text is going to be used, see the RFC for what that means
2484 * @access public
2485 * @return string
2487 public function encodeQ($str, $position = 'text')
2489 // There should not be any EOL in the string
2490 $pattern = '';
2491 $encoded = str_replace(array("\r", "\n"), '', $str);
2492 switch (strtolower($position)) {
2493 case 'phrase':
2494 // RFC 2047 section 5.3
2495 $pattern = '^A-Za-z0-9!*+\/ -';
2496 break;
2497 /** @noinspection PhpMissingBreakStatementInspection */
2498 case 'comment':
2499 // RFC 2047 section 5.2
2500 $pattern = '\(\)"';
2501 // intentional fall-through
2502 // for this reason we build the $pattern without including delimiters and []
2503 case 'text':
2504 default:
2505 // RFC 2047 section 5.1
2506 // Replace every high ascii, control, =, ? and _ characters
2507 $pattern = '\000-\011\013\014\016-\037\075\077\137\177-\377' . $pattern;
2508 break;
2510 $matches = array();
2511 if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) {
2512 // If the string contains an '=', make sure it's the first thing we replace
2513 // so as to avoid double-encoding
2514 $eqkey = array_search('=', $matches[0]);
2515 if ($eqkey !== false) {
2516 unset($matches[0][$eqkey]);
2517 array_unshift($matches[0], '=');
2519 foreach (array_unique($matches[0]) as $char) {
2520 $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded);
2523 // Replace every spaces to _ (more readable than =20)
2524 return str_replace(' ', '_', $encoded);
2529 * Add a string or binary attachment (non-filesystem).
2530 * This method can be used to attach ascii or binary data,
2531 * such as a BLOB record from a database.
2532 * @param string $string String attachment data.
2533 * @param string $filename Name of the attachment.
2534 * @param string $encoding File encoding (see $Encoding).
2535 * @param string $type File extension (MIME) type.
2536 * @param string $disposition Disposition to use
2537 * @return void
2539 public function addStringAttachment(
2540 $string,
2541 $filename,
2542 $encoding = 'base64',
2543 $type = '',
2544 $disposition = 'attachment'
2546 // If a MIME type is not specified, try to work it out from the file name
2547 if ($type == '') {
2548 $type = self::filenameToType($filename);
2550 // Append to $attachment array
2551 $this->attachment[] = array(
2552 0 => $string,
2553 1 => $filename,
2554 2 => basename($filename),
2555 3 => $encoding,
2556 4 => $type,
2557 5 => true, // isStringAttachment
2558 6 => $disposition,
2559 7 => 0
2564 * Add an embedded (inline) attachment from a file.
2565 * This can include images, sounds, and just about any other document type.
2566 * These differ from 'regular' attachmants in that they are intended to be
2567 * displayed inline with the message, not just attached for download.
2568 * This is used in HTML messages that embed the images
2569 * the HTML refers to using the $cid value.
2570 * @param string $path Path to the attachment.
2571 * @param string $cid Content ID of the attachment; Use this to reference
2572 * the content when using an embedded image in HTML.
2573 * @param string $name Overrides the attachment name.
2574 * @param string $encoding File encoding (see $Encoding).
2575 * @param string $type File MIME type.
2576 * @param string $disposition Disposition to use
2577 * @return boolean True on successfully adding an attachment
2579 public function addEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = '', $disposition = 'inline')
2581 if (!@is_file($path)) {
2582 $this->setError($this->lang('file_access') . $path);
2583 return false;
2586 // If a MIME type is not specified, try to work it out from the file name
2587 if ($type == '') {
2588 $type = self::filenameToType($path);
2591 $filename = basename($path);
2592 if ($name == '') {
2593 $name = $filename;
2596 // Append to $attachment array
2597 $this->attachment[] = array(
2598 0 => $path,
2599 1 => $filename,
2600 2 => $name,
2601 3 => $encoding,
2602 4 => $type,
2603 5 => false, // isStringAttachment
2604 6 => $disposition,
2605 7 => $cid
2607 return true;
2611 * Add an embedded stringified attachment.
2612 * This can include images, sounds, and just about any other document type.
2613 * Be sure to set the $type to an image type for images:
2614 * JPEG images use 'image/jpeg', GIF uses 'image/gif', PNG uses 'image/png'.
2615 * @param string $string The attachment binary data.
2616 * @param string $cid Content ID of the attachment; Use this to reference
2617 * the content when using an embedded image in HTML.
2618 * @param string $name
2619 * @param string $encoding File encoding (see $Encoding).
2620 * @param string $type MIME type.
2621 * @param string $disposition Disposition to use
2622 * @return boolean True on successfully adding an attachment
2624 public function addStringEmbeddedImage(
2625 $string,
2626 $cid,
2627 $name = '',
2628 $encoding = 'base64',
2629 $type = '',
2630 $disposition = 'inline'
2632 // If a MIME type is not specified, try to work it out from the name
2633 if ($type == '') {
2634 $type = self::filenameToType($name);
2637 // Append to $attachment array
2638 $this->attachment[] = array(
2639 0 => $string,
2640 1 => $name,
2641 2 => $name,
2642 3 => $encoding,
2643 4 => $type,
2644 5 => true, // isStringAttachment
2645 6 => $disposition,
2646 7 => $cid
2648 return true;
2652 * Check if an inline attachment is present.
2653 * @access public
2654 * @return boolean
2656 public function inlineImageExists()
2658 foreach ($this->attachment as $attachment) {
2659 if ($attachment[6] == 'inline') {
2660 return true;
2663 return false;
2667 * Check if an attachment (non-inline) is present.
2668 * @return boolean
2670 public function attachmentExists()
2672 foreach ($this->attachment as $attachment) {
2673 if ($attachment[6] == 'attachment') {
2674 return true;
2677 return false;
2681 * Check if this message has an alternative body set.
2682 * @return boolean
2684 public function alternativeExists()
2686 return !empty($this->AltBody);
2690 * Clear all To recipients.
2691 * @return void
2693 public function clearAddresses()
2695 foreach ($this->to as $to) {
2696 unset($this->all_recipients[strtolower($to[0])]);
2698 $this->to = array();
2702 * Clear all CC recipients.
2703 * @return void
2705 public function clearCCs()
2707 foreach ($this->cc as $cc) {
2708 unset($this->all_recipients[strtolower($cc[0])]);
2710 $this->cc = array();
2714 * Clear all BCC recipients.
2715 * @return void
2717 public function clearBCCs()
2719 foreach ($this->bcc as $bcc) {
2720 unset($this->all_recipients[strtolower($bcc[0])]);
2722 $this->bcc = array();
2726 * Clear all ReplyTo recipients.
2727 * @return void
2729 public function clearReplyTos()
2731 $this->ReplyTo = array();
2735 * Clear all recipient types.
2736 * @return void
2738 public function clearAllRecipients()
2740 $this->to = array();
2741 $this->cc = array();
2742 $this->bcc = array();
2743 $this->all_recipients = array();
2747 * Clear all filesystem, string, and binary attachments.
2748 * @return void
2750 public function clearAttachments()
2752 $this->attachment = array();
2756 * Clear all custom headers.
2757 * @return void
2759 public function clearCustomHeaders()
2761 $this->CustomHeader = array();
2765 * Add an error message to the error container.
2766 * @access protected
2767 * @param string $msg
2768 * @return void
2770 protected function setError($msg)
2772 $this->error_count++;
2773 if ($this->Mailer == 'smtp' and !is_null($this->smtp)) {
2774 $lasterror = $this->smtp->getError();
2775 if (!empty($lasterror) and array_key_exists('smtp_msg', $lasterror)) {
2776 $msg .= '<p>' . $this->lang('smtp_error') . $lasterror['smtp_msg'] . "</p>\n";
2779 $this->ErrorInfo = $msg;
2783 * Return an RFC 822 formatted date.
2784 * @access public
2785 * @return string
2786 * @static
2788 public static function rfcDate()
2790 // Set the time zone to whatever the default is to avoid 500 errors
2791 // Will default to UTC if it's not set properly in php.ini
2792 date_default_timezone_set(@date_default_timezone_get());
2793 return date('D, j M Y H:i:s O');
2797 * Get the server hostname.
2798 * Returns 'localhost.localdomain' if unknown.
2799 * @access protected
2800 * @return string
2802 protected function serverHostname()
2804 $result = 'localhost.localdomain';
2805 if (!empty($this->Hostname)) {
2806 $result = $this->Hostname;
2807 } elseif (isset($_SERVER) and array_key_exists('SERVER_NAME', $_SERVER) and !empty($_SERVER['SERVER_NAME'])) {
2808 $result = $_SERVER['SERVER_NAME'];
2809 } elseif (function_exists('gethostname') && gethostname() !== false) {
2810 $result = gethostname();
2811 } elseif (php_uname('n') !== false) {
2812 $result = php_uname('n');
2814 return $result;
2818 * Get an error message in the current language.
2819 * @access protected
2820 * @param string $key
2821 * @return string
2823 protected function lang($key)
2825 if (count($this->language) < 1) {
2826 $this->setLanguage('en'); // set the default language
2829 if (isset($this->language[$key])) {
2830 return $this->language[$key];
2831 } else {
2832 return 'Language string failed to load: ' . $key;
2837 * Check if an error occurred.
2838 * @access public
2839 * @return boolean True if an error did occur.
2841 public function isError()
2843 return ($this->error_count > 0);
2847 * Ensure consistent line endings in a string.
2848 * Changes every end of line from CRLF, CR or LF to $this->LE.
2849 * @access public
2850 * @param string $str String to fixEOL
2851 * @return string
2853 public function fixEOL($str)
2855 // Normalise to \n
2856 $nstr = str_replace(array("\r\n", "\r"), "\n", $str);
2857 // Now convert LE as needed
2858 if ($this->LE !== "\n") {
2859 $nstr = str_replace("\n", $this->LE, $nstr);
2861 return $nstr;
2865 * Add a custom header.
2866 * $name value can be overloaded to contain
2867 * both header name and value (name:value)
2868 * @access public
2869 * @param string $name Custom header name
2870 * @param string $value Header value
2871 * @return void
2873 public function addCustomHeader($name, $value = null)
2875 if ($value === null) {
2876 // Value passed in as name:value
2877 $this->CustomHeader[] = explode(':', $name, 2);
2878 } else {
2879 $this->CustomHeader[] = array($name, $value);
2884 * Create a message from an HTML string.
2885 * Automatically makes modifications for inline images and backgrounds
2886 * and creates a plain-text version by converting the HTML.
2887 * Overwrites any existing values in $this->Body and $this->AltBody
2888 * @access public
2889 * @param string $message HTML message string
2890 * @param string $basedir baseline directory for path
2891 * @param boolean $advanced Whether to use the advanced HTML to text converter
2892 * @return string $message
2894 public function msgHTML($message, $basedir = '', $advanced = false)
2896 preg_match_all('/(src|background)=["\'](.*)["\']/Ui', $message, $images);
2897 if (isset($images[2])) {
2898 foreach ($images[2] as $imgindex => $url) {
2899 // Convert data URIs into embedded images
2900 if (preg_match('#^data:(image[^;,]*)(;base64)?,#', $url, $match)) {
2901 $data = substr($url, strpos($url, ','));
2902 if ($match[2]) {
2903 $data = base64_decode($data);
2904 } else {
2905 $data = rawurldecode($data);
2907 $cid = md5($url) . '@phpmailer.0'; // RFC2392 S 2
2908 if ($this->addStringEmbeddedImage($data, $cid, '', 'base64', $match[1])) {
2909 $message = preg_replace(
2910 '/' . $images[1][$imgindex] . '=["\']' . preg_quote($url, '/') . '["\']/Ui',
2911 $images[1][$imgindex] . '="cid:' . $cid . '"',
2912 $message
2915 } elseif (!preg_match('#^[A-z]+://#', $url)) {
2916 // Do not change urls for absolute images (thanks to corvuscorax)
2917 $filename = basename($url);
2918 $directory = dirname($url);
2919 if ($directory == '.') {
2920 $directory = '';
2922 $cid = md5($url) . '@phpmailer.0'; // RFC2392 S 2
2923 if (strlen($basedir) > 1 && substr($basedir, -1) != '/') {
2924 $basedir .= '/';
2926 if (strlen($directory) > 1 && substr($directory, -1) != '/') {
2927 $directory .= '/';
2929 if ($this->addEmbeddedImage(
2930 $basedir . $directory . $filename,
2931 $cid,
2932 $filename,
2933 'base64',
2934 self::_mime_types(self::mb_pathinfo($filename, PATHINFO_EXTENSION))
2937 $message = preg_replace(
2938 '/' . $images[1][$imgindex] . '=["\']' . preg_quote($url, '/') . '["\']/Ui',
2939 $images[1][$imgindex] . '="cid:' . $cid . '"',
2940 $message
2946 $this->isHTML(true);
2947 // Convert all message body line breaks to CRLF, makes quoted-printable encoding work much better
2948 $this->Body = $this->normalizeBreaks($message);
2949 $this->AltBody = $this->normalizeBreaks($this->html2text($message, $advanced));
2950 if (empty($this->AltBody)) {
2951 $this->AltBody = 'To view this email message, open it in a program that understands HTML!' .
2952 self::CRLF . self::CRLF;
2954 return $this->Body;
2958 * Convert an HTML string into plain text.
2959 * @param string $html The HTML text to convert
2960 * @param boolean $advanced Should this use the more complex html2text converter or just a simple one?
2961 * @return string
2963 public function html2text($html, $advanced = false)
2965 if ($advanced) {
2966 require_once 'extras/class.html2text.php';
2967 $htmlconverter = new html2text($html);
2968 return $htmlconverter->get_text();
2970 return html_entity_decode(
2971 trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/si', '', $html))),
2972 ENT_QUOTES,
2973 $this->CharSet
2978 * Get the MIME type for a file extension.
2979 * @param string $ext File extension
2980 * @access public
2981 * @return string MIME type of file.
2982 * @static
2984 public static function _mime_types($ext = '')
2986 $mimes = array(
2987 'xl' => 'application/excel',
2988 'hqx' => 'application/mac-binhex40',
2989 'cpt' => 'application/mac-compactpro',
2990 'bin' => 'application/macbinary',
2991 'doc' => 'application/msword',
2992 'word' => 'application/msword',
2993 'class' => 'application/octet-stream',
2994 'dll' => 'application/octet-stream',
2995 'dms' => 'application/octet-stream',
2996 'exe' => 'application/octet-stream',
2997 'lha' => 'application/octet-stream',
2998 'lzh' => 'application/octet-stream',
2999 'psd' => 'application/octet-stream',
3000 'sea' => 'application/octet-stream',
3001 'so' => 'application/octet-stream',
3002 'oda' => 'application/oda',
3003 'pdf' => 'application/pdf',
3004 'ai' => 'application/postscript',
3005 'eps' => 'application/postscript',
3006 'ps' => 'application/postscript',
3007 'smi' => 'application/smil',
3008 'smil' => 'application/smil',
3009 'mif' => 'application/vnd.mif',
3010 'xls' => 'application/vnd.ms-excel',
3011 'ppt' => 'application/vnd.ms-powerpoint',
3012 'wbxml' => 'application/vnd.wap.wbxml',
3013 'wmlc' => 'application/vnd.wap.wmlc',
3014 'dcr' => 'application/x-director',
3015 'dir' => 'application/x-director',
3016 'dxr' => 'application/x-director',
3017 'dvi' => 'application/x-dvi',
3018 'gtar' => 'application/x-gtar',
3019 'php3' => 'application/x-httpd-php',
3020 'php4' => 'application/x-httpd-php',
3021 'php' => 'application/x-httpd-php',
3022 'phtml' => 'application/x-httpd-php',
3023 'phps' => 'application/x-httpd-php-source',
3024 'js' => 'application/x-javascript',
3025 'swf' => 'application/x-shockwave-flash',
3026 'sit' => 'application/x-stuffit',
3027 'tar' => 'application/x-tar',
3028 'tgz' => 'application/x-tar',
3029 'xht' => 'application/xhtml+xml',
3030 'xhtml' => 'application/xhtml+xml',
3031 'zip' => 'application/zip',
3032 'mid' => 'audio/midi',
3033 'midi' => 'audio/midi',
3034 'mp2' => 'audio/mpeg',
3035 'mp3' => 'audio/mpeg',
3036 'mpga' => 'audio/mpeg',
3037 'aif' => 'audio/x-aiff',
3038 'aifc' => 'audio/x-aiff',
3039 'aiff' => 'audio/x-aiff',
3040 'ram' => 'audio/x-pn-realaudio',
3041 'rm' => 'audio/x-pn-realaudio',
3042 'rpm' => 'audio/x-pn-realaudio-plugin',
3043 'ra' => 'audio/x-realaudio',
3044 'wav' => 'audio/x-wav',
3045 'bmp' => 'image/bmp',
3046 'gif' => 'image/gif',
3047 'jpeg' => 'image/jpeg',
3048 'jpe' => 'image/jpeg',
3049 'jpg' => 'image/jpeg',
3050 'png' => 'image/png',
3051 'tiff' => 'image/tiff',
3052 'tif' => 'image/tiff',
3053 'eml' => 'message/rfc822',
3054 'css' => 'text/css',
3055 'html' => 'text/html',
3056 'htm' => 'text/html',
3057 'shtml' => 'text/html',
3058 'log' => 'text/plain',
3059 'text' => 'text/plain',
3060 'txt' => 'text/plain',
3061 'rtx' => 'text/richtext',
3062 'rtf' => 'text/rtf',
3063 'vcf' => 'text/vcard',
3064 'vcard' => 'text/vcard',
3065 'xml' => 'text/xml',
3066 'xsl' => 'text/xml',
3067 'mpeg' => 'video/mpeg',
3068 'mpe' => 'video/mpeg',
3069 'mpg' => 'video/mpeg',
3070 'mov' => 'video/quicktime',
3071 'qt' => 'video/quicktime',
3072 'rv' => 'video/vnd.rn-realvideo',
3073 'avi' => 'video/x-msvideo',
3074 'movie' => 'video/x-sgi-movie'
3076 return (array_key_exists(strtolower($ext), $mimes) ? $mimes[strtolower($ext)]: 'application/octet-stream');
3080 * Map a file name to a MIME type.
3081 * Defaults to 'application/octet-stream', i.e.. arbitrary binary data.
3082 * @param string $filename A file name or full path, does not need to exist as a file
3083 * @return string
3084 * @static
3086 public static function filenameToType($filename)
3088 // In case the path is a URL, strip any query string before getting extension
3089 $qpos = strpos($filename, '?');
3090 if ($qpos !== false) {
3091 $filename = substr($filename, 0, $qpos);
3093 $pathinfo = self::mb_pathinfo($filename);
3094 return self::_mime_types($pathinfo['extension']);
3098 * Multi-byte-safe pathinfo replacement.
3099 * Drop-in replacement for pathinfo(), but multibyte-safe, cross-platform-safe, old-version-safe.
3100 * Works similarly to the one in PHP >= 5.2.0
3101 * @link http://www.php.net/manual/en/function.pathinfo.php#107461
3102 * @param string $path A filename or path, does not need to exist as a file
3103 * @param integer|string $options Either a PATHINFO_* constant,
3104 * or a string name to return only the specified piece, allows 'filename' to work on PHP < 5.2
3105 * @return string|array
3106 * @static
3108 public static function mb_pathinfo($path, $options = null)
3110 $ret = array('dirname' => '', 'basename' => '', 'extension' => '', 'filename' => '');
3111 $pathinfo = array();
3112 if (preg_match('%^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^\.\\\\/]+?)|))[\\\\/\.]*$%im', $path, $pathinfo)) {
3113 if (array_key_exists(1, $pathinfo)) {
3114 $ret['dirname'] = $pathinfo[1];
3116 if (array_key_exists(2, $pathinfo)) {
3117 $ret['basename'] = $pathinfo[2];
3119 if (array_key_exists(5, $pathinfo)) {
3120 $ret['extension'] = $pathinfo[5];
3122 if (array_key_exists(3, $pathinfo)) {
3123 $ret['filename'] = $pathinfo[3];
3126 switch ($options) {
3127 case PATHINFO_DIRNAME:
3128 case 'dirname':
3129 return $ret['dirname'];
3130 case PATHINFO_BASENAME:
3131 case 'basename':
3132 return $ret['basename'];
3133 case PATHINFO_EXTENSION:
3134 case 'extension':
3135 return $ret['extension'];
3136 case PATHINFO_FILENAME:
3137 case 'filename':
3138 return $ret['filename'];
3139 default:
3140 return $ret;
3145 * Set or reset instance properties.
3147 * Usage Example:
3148 * $page->set('X-Priority', '3');
3150 * @access public
3151 * @param string $name
3152 * @param mixed $value
3153 * NOTE: will not work with arrays, there are no arrays to set/reset
3154 * @throws phpmailerException
3155 * @return boolean
3156 * @TODO Should this not be using __set() magic function?
3158 public function set($name, $value = '')
3160 try {
3161 if (isset($this->$name)) {
3162 $this->$name = $value;
3163 } else {
3164 throw new phpmailerException($this->lang('variable_set') . $name, self::STOP_CRITICAL);
3166 } catch (Exception $exc) {
3167 $this->setError($exc->getMessage());
3168 if ($exc->getCode() == self::STOP_CRITICAL) {
3169 return false;
3172 return true;
3176 * Strip newlines to prevent header injection.
3177 * @access public
3178 * @param string $str
3179 * @return string
3181 public function secureHeader($str)
3183 return trim(str_replace(array("\r", "\n"), '', $str));
3187 * Normalize line breaks in a string.
3188 * Converts UNIX LF, Mac CR and Windows CRLF line breaks into a single line break format.
3189 * Defaults to CRLF (for message bodies) and preserves consecutive breaks.
3190 * @param string $text
3191 * @param string $breaktype What kind of line break to use, defaults to CRLF
3192 * @return string
3193 * @access public
3194 * @static
3196 public static function normalizeBreaks($text, $breaktype = "\r\n")
3198 return preg_replace('/(\r\n|\r|\n)/ms', $breaktype, $text);
3203 * Set the public and private key files and password for S/MIME signing.
3204 * @access public
3205 * @param string $cert_filename
3206 * @param string $key_filename
3207 * @param string $key_pass Password for private key
3209 public function sign($cert_filename, $key_filename, $key_pass)
3211 $this->sign_cert_file = $cert_filename;
3212 $this->sign_key_file = $key_filename;
3213 $this->sign_key_pass = $key_pass;
3217 * Quoted-Printable-encode a DKIM header.
3218 * @access public
3219 * @param string $txt
3220 * @return string
3222 public function DKIM_QP($txt)
3224 $line = '';
3225 for ($i = 0; $i < strlen($txt); $i++) {
3226 $ord = ord($txt[$i]);
3227 if (((0x21 <= $ord) && ($ord <= 0x3A)) || $ord == 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E))) {
3228 $line .= $txt[$i];
3229 } else {
3230 $line .= '=' . sprintf('%02X', $ord);
3233 return $line;
3237 * Generate a DKIM signature.
3238 * @access public
3239 * @param string $signHeader
3240 * @throws phpmailerException
3241 * @return string
3243 public function DKIM_Sign($signHeader)
3245 if (!defined('PKCS7_TEXT')) {
3246 if ($this->exceptions) {
3247 throw new phpmailerException($this->lang('signing') . ' OpenSSL extension missing.');
3249 return '';
3251 $privKeyStr = file_get_contents($this->DKIM_private);
3252 if ($this->DKIM_passphrase != '') {
3253 $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase);
3254 } else {
3255 $privKey = $privKeyStr;
3257 if (openssl_sign($signHeader, $signature, $privKey)) {
3258 return base64_encode($signature);
3260 return '';
3264 * Generate a DKIM canonicalization header.
3265 * @access public
3266 * @param string $signHeader Header
3267 * @return string
3269 public function DKIM_HeaderC($signHeader)
3271 $signHeader = preg_replace('/\r\n\s+/', ' ', $signHeader);
3272 $lines = explode("\r\n", $signHeader);
3273 foreach ($lines as $key => $line) {
3274 list($heading, $value) = explode(':', $line, 2);
3275 $heading = strtolower($heading);
3276 $value = preg_replace('/\s+/', ' ', $value); // Compress useless spaces
3277 $lines[$key] = $heading . ':' . trim($value); // Don't forget to remove WSP around the value
3279 $signHeader = implode("\r\n", $lines);
3280 return $signHeader;
3284 * Generate a DKIM canonicalization body.
3285 * @access public
3286 * @param string $body Message Body
3287 * @return string
3289 public function DKIM_BodyC($body)
3291 if ($body == '') {
3292 return "\r\n";
3294 // stabilize line endings
3295 $body = str_replace("\r\n", "\n", $body);
3296 $body = str_replace("\n", "\r\n", $body);
3297 // END stabilize line endings
3298 while (substr($body, strlen($body) - 4, 4) == "\r\n\r\n") {
3299 $body = substr($body, 0, strlen($body) - 2);
3301 return $body;
3305 * Create the DKIM header and body in a new message header.
3306 * @access public
3307 * @param string $headers_line Header lines
3308 * @param string $subject Subject
3309 * @param string $body Body
3310 * @return string
3312 public function DKIM_Add($headers_line, $subject, $body)
3314 $DKIMsignatureType = 'rsa-sha1'; // Signature & hash algorithms
3315 $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body
3316 $DKIMquery = 'dns/txt'; // Query method
3317 $DKIMtime = time(); // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone)
3318 $subject_header = "Subject: $subject";
3319 $headers = explode($this->LE, $headers_line);
3320 $from_header = '';
3321 $to_header = '';
3322 $current = '';
3323 foreach ($headers as $header) {
3324 if (strpos($header, 'From:') === 0) {
3325 $from_header = $header;
3326 $current = 'from_header';
3327 } elseif (strpos($header, 'To:') === 0) {
3328 $to_header = $header;
3329 $current = 'to_header';
3330 } else {
3331 if ($current && strpos($header, ' =?') === 0) {
3332 $current .= $header;
3333 } else {
3334 $current = '';
3338 $from = str_replace('|', '=7C', $this->DKIM_QP($from_header));
3339 $to = str_replace('|', '=7C', $this->DKIM_QP($to_header));
3340 $subject = str_replace(
3341 '|',
3342 '=7C',
3343 $this->DKIM_QP($subject_header)
3344 ); // Copied header fields (dkim-quoted-printable)
3345 $body = $this->DKIM_BodyC($body);
3346 $DKIMlen = strlen($body); // Length of body
3347 $DKIMb64 = base64_encode(pack('H*', sha1($body))); // Base64 of packed binary SHA-1 hash of body
3348 $ident = ($this->DKIM_identity == '') ? '' : ' i=' . $this->DKIM_identity . ';';
3349 $dkimhdrs = 'DKIM-Signature: v=1; a=' .
3350 $DKIMsignatureType . '; q=' .
3351 $DKIMquery . '; l=' .
3352 $DKIMlen . '; s=' .
3353 $this->DKIM_selector .
3354 ";\r\n" .
3355 "\tt=" . $DKIMtime . '; c=' . $DKIMcanonicalization . ";\r\n" .
3356 "\th=From:To:Subject;\r\n" .
3357 "\td=" . $this->DKIM_domain . ';' . $ident . "\r\n" .
3358 "\tz=$from\r\n" .
3359 "\t|$to\r\n" .
3360 "\t|$subject;\r\n" .
3361 "\tbh=" . $DKIMb64 . ";\r\n" .
3362 "\tb=";
3363 $toSign = $this->DKIM_HeaderC(
3364 $from_header . "\r\n" . $to_header . "\r\n" . $subject_header . "\r\n" . $dkimhdrs
3366 $signed = $this->DKIM_Sign($toSign);
3367 return $dkimhdrs . $signed . "\r\n";
3371 * Allows for public read access to 'to' property.
3372 * @access public
3373 * @return array
3375 public function getToAddresses()
3377 return $this->to;
3381 * Allows for public read access to 'cc' property.
3382 * @access public
3383 * @return array
3385 public function getCcAddresses()
3387 return $this->cc;
3391 * Allows for public read access to 'bcc' property.
3392 * @access public
3393 * @return array
3395 public function getBccAddresses()
3397 return $this->bcc;
3401 * Allows for public read access to 'ReplyTo' property.
3402 * @access public
3403 * @return array
3405 public function getReplyToAddresses()
3407 return $this->ReplyTo;
3411 * Allows for public read access to 'all_recipients' property.
3412 * @access public
3413 * @return array
3415 public function getAllRecipientAddresses()
3417 return $this->all_recipients;
3421 * Perform a callback.
3422 * @param boolean $isSent
3423 * @param array $to
3424 * @param array $cc
3425 * @param array $bcc
3426 * @param string $subject
3427 * @param string $body
3428 * @param string $from
3430 protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body, $from)
3432 if (!empty($this->action_function) && is_callable($this->action_function)) {
3433 $params = array($isSent, $to, $cc, $bcc, $subject, $body, $from);
3434 call_user_func_array($this->action_function, $params);
3440 * PHPMailer exception handler
3441 * @package PHPMailer
3443 class phpmailerException extends Exception
3446 * Prettify error message output
3447 * @return string
3449 public function errorMessage()
3451 $errorMsg = '<strong>' . $this->getMessage() . "</strong><br />\n";
3452 return $errorMsg;