2 /*~ class.phpmailer.php
3 .---------------------------------------------------------------------------.
4 | Software: PHPMailer - PHP email class |
6 | Contact: via sourceforge.net support pages (also www.worxware.com) |
7 | Info: http://phpmailer.sourceforge.net |
8 | Support: http://sourceforge.net/projects/phpmailer/ |
9 | ------------------------------------------------------------------------- |
10 | Admin: Andy Prevost (project admininistrator) |
11 | Authors: Andy Prevost (codeworxtech) codeworxtech@users.sourceforge.net |
12 | : Marcus Bointon (coolbru) coolbru@users.sourceforge.net |
13 | Founder: Brent R. Matzelle (original founder) |
14 | Copyright (c) 2004-2009, Andy Prevost. All Rights Reserved. |
15 | Copyright (c) 2001-2003, Brent R. Matzelle |
16 | ------------------------------------------------------------------------- |
17 | License: Distributed under the Lesser General Public License (LGPL) |
18 | http://www.gnu.org/copyleft/lesser.html |
19 | This program is distributed in the hope that it will be useful - WITHOUT |
20 | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
21 | FITNESS FOR A PARTICULAR PURPOSE. |
22 | ------------------------------------------------------------------------- |
23 | We offer a number of paid services (www.worxware.com): |
24 | - Web Hosting on highly optimized fast and secure servers |
25 | - Technology Consulting |
26 | - Oursourcing (highly qualified programmers and graphic designers) |
27 '---------------------------------------------------------------------------'
31 * PHPMailer - PHP email transport class
32 * NOTE: Requires PHP version 5 or later
34 * @author Andy Prevost
35 * @author Marcus Bointon
36 * @copyright 2004 - 2009 Andy Prevost
37 * @version $Id: class.phpmailer.php 447 2009-05-25 01:36:38Z codeworxtech $
38 * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
41 if (version_compare(PHP_VERSION, '5.0.0', '<') ) exit("Sorry, this version of PHPMailer will only run on PHP version 5 or greater!\n");
45 /////////////////////////////////////////////////
47 /////////////////////////////////////////////////
50 * Email priority (1 = High, 3 = Normal, 5 = low).
56 * Sets the CharSet of the message.
59 public $CharSet = 'iso-8859-1';
62 * Sets the Content-type of the message.
65 public $ContentType = 'text/plain';
68 * Sets the Encoding of the message. Options for this are
69 * "8bit", "7bit", "binary", "base64", and "quoted-printable".
72 public $Encoding = '8bit';
75 * Holds the most recent mailer error message.
78 public $ErrorInfo = '';
81 * Sets the From email address for the message.
84 public $From = 'root@localhost';
87 * Sets the From name of the message.
90 public $FromName = 'Root User';
93 * Sets the Sender email (Return-Path) of the message. If not empty,
94 * will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode.
100 * Sets the Subject of the message.
103 public $Subject = '';
106 * Sets the Body of the message. This can be either an HTML or text body.
107 * If HTML then run IsHTML(true).
113 * Sets the text-only body of the message. This automatically sets the
114 * email to multipart/alternative. This body can be read by mail
115 * clients that do not have HTML email capability such as mutt. Clients
116 * that can read HTML will view the normal Body.
119 public $AltBody = '';
122 * Sets word wrapping on the body of the message to a given number of
126 public $WordWrap = 0;
129 * Method to send mail: ("mail", "sendmail", or "smtp").
132 public $Mailer = 'mail';
135 * Sets the path of the sendmail program.
138 public $Sendmail = '/usr/sbin/sendmail';
141 * Path to PHPMailer plugins. Useful if the SMTP class
142 * is in a different directory than the PHP include path.
145 public $PluginDir = '';
148 * Sets the email address that a reading confirmation will be sent.
151 public $ConfirmReadingTo = '';
154 * Sets the hostname to use in Message-Id and Received headers
155 * and as default HELO string. If empty, the value returned
156 * by SERVER_NAME is used or 'localhost.localdomain'.
159 public $Hostname = '';
162 * Sets the message ID to be used in the Message-Id header.
163 * If empty, a unique id will be generated.
166 public $MessageID = '';
168 /////////////////////////////////////////////////
169 // PROPERTIES FOR SMTP
170 /////////////////////////////////////////////////
173 * Sets the SMTP hosts. All hosts must be separated by a
174 * semicolon. You can also specify a different port
175 * for each host by using this format: [hostname:port]
176 * (e.g. "smtp1.example.com:25;smtp2.example.com").
177 * Hosts will be tried in order.
180 public $Host = 'localhost';
183 * Sets the default SMTP server port.
189 * Sets the SMTP HELO of the message (Default is $Hostname).
195 * Sets connection prefix.
196 * Options are "", "ssl" or "tls"
199 public $SMTPSecure = '';
202 * Sets SMTP authentication. Utilizes the Username and Password variables.
205 public $SMTPAuth = false;
208 * Sets SMTP username.
211 public $Username = '';
214 * Sets SMTP password.
217 public $Password = '';
220 * Sets the SMTP server timeout in seconds.
221 * This function will not work with the win32 version.
224 public $Timeout = 10;
227 * Sets SMTP class debugging on or off.
230 public $SMTPDebug = false;
233 * Prevents the SMTP connection from being closed after each mail
234 * sending. If this is set to true then to close the connection
235 * requires an explicit call to SmtpClose().
238 public $SMTPKeepAlive = false;
241 * Provides the ability to have the TO field process individual
242 * emails, instead of sending to entire TO addresses
245 public $SingleTo = false;
248 * If SingleTo is true, this provides the array to hold the email addresses
251 public $SingleToArray = array();
254 * Provides the ability to change the line ending
260 * Used with DKIM DNS Resource Record
263 public $DKIM_selector = 'phpmailer';
266 * Used with DKIM DNS Resource Record
267 * optional, in format of email address 'you@yourdomain.com'
270 public $DKIM_identity = '';
273 * Used with DKIM DNS Resource Record
274 * optional, in format of email address 'you@yourdomain.com'
277 public $DKIM_domain = '';
280 * Used with DKIM DNS Resource Record
281 * optional, in format of email address 'you@yourdomain.com'
284 public $DKIM_private = '';
287 * Callback Action function name
288 * the function that handles the result of the send email action. Parameters:
289 * bool $result result of the send action
290 * string $to email address of the recipient
291 * string $cc cc email addresses
292 * string $bcc bcc email addresses
293 * string $subject the subject
294 * string $body the email body
297 public $action_function = ''; //'callbackAction';
300 * Sets the PHPMailer Version number
303 public $Version = '5.1';
305 /////////////////////////////////////////////////
306 // PROPERTIES, PRIVATE AND PROTECTED
307 /////////////////////////////////////////////////
309 private $smtp = NULL;
310 private $to = array();
311 private $cc = array();
312 private $bcc = array();
313 private $ReplyTo = array();
314 private $all_recipients = array();
315 private $attachment = array();
316 private $CustomHeader = array();
317 private $message_type = '';
318 private $boundary = array();
319 protected $language = array();
320 private $error_count = 0;
321 private $sign_cert_file = "";
322 private $sign_key_file = "";
323 private $sign_key_pass = "";
324 private $exceptions = false;
326 /////////////////////////////////////////////////
328 /////////////////////////////////////////////////
330 const STOP_MESSAGE = 0; // message only, continue processing
331 const STOP_CONTINUE = 1; // message?, likely ok to continue processing
332 const STOP_CRITICAL = 2; // message, plus full stop, critical error reached
334 /////////////////////////////////////////////////
335 // METHODS, VARIABLES
336 /////////////////////////////////////////////////
340 * @param boolean $exceptions Should we throw external exceptions?
342 public function __construct($exceptions = false) {
343 $this->exceptions = ($exceptions == true);
347 * Sets message type to HTML.
348 * @param bool $ishtml
351 public function IsHTML($ishtml = true) {
353 $this->ContentType = 'text/html';
355 $this->ContentType = 'text/plain';
360 * Sets Mailer to send message using SMTP.
363 public function IsSMTP() {
364 $this->Mailer = 'smtp';
368 * Sets Mailer to send message using PHP mail() function.
371 public function IsMail() {
372 $this->Mailer = 'mail';
376 * Sets Mailer to send message using the $Sendmail program.
379 public function IsSendmail() {
380 if (!stristr(ini_get('sendmail_path'), 'sendmail')) {
381 $this->Sendmail = '/var/qmail/bin/sendmail';
383 $this->Mailer = 'sendmail';
387 * Sets Mailer to send message using the qmail MTA.
390 public function IsQmail() {
391 if (stristr(ini_get('sendmail_path'), 'qmail')) {
392 $this->Sendmail = '/var/qmail/bin/sendmail';
394 $this->Mailer = 'sendmail';
397 /////////////////////////////////////////////////
398 // METHODS, RECIPIENTS
399 /////////////////////////////////////////////////
402 * Adds a "To" address.
403 * @param string $address
404 * @param string $name
405 * @return boolean true on success, false if address already used
407 public function AddAddress($address, $name = '') {
408 return $this->AddAnAddress('to', $address, $name);
412 * Adds a "Cc" address.
413 * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer.
414 * @param string $address
415 * @param string $name
416 * @return boolean true on success, false if address already used
418 public function AddCC($address, $name = '') {
419 return $this->AddAnAddress('cc', $address, $name);
423 * Adds a "Bcc" address.
424 * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer.
425 * @param string $address
426 * @param string $name
427 * @return boolean true on success, false if address already used
429 public function AddBCC($address, $name = '') {
430 return $this->AddAnAddress('bcc', $address, $name);
434 * Adds a "Reply-to" address.
435 * @param string $address
436 * @param string $name
439 public function AddReplyTo($address, $name = '') {
440 return $this->AddAnAddress('ReplyTo', $address, $name);
444 * Adds an address to one of the recipient arrays
445 * Addresses that have been added already return false, but do not throw exceptions
446 * @param string $kind One of 'to', 'cc', 'bcc', 'ReplyTo'
447 * @param string $address The email address to send to
448 * @param string $name
449 * @return boolean true on success, false if address already used or invalid in some way
452 private function AddAnAddress($kind, $address, $name = '') {
453 if (!preg_match('/^(to|cc|bcc|ReplyTo)$/', $kind)) {
454 echo 'Invalid recipient array: ' . kind;
457 $address = trim($address);
458 $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
459 if (!self::ValidateAddress($address)) {
460 $this->SetError($this->Lang('invalid_address').': '. $address);
461 if ($this->exceptions) {
462 throw new phpmailerException($this->Lang('invalid_address').': '.$address);
464 echo $this->Lang('invalid_address').': '.$address;
467 if ($kind != 'ReplyTo') {
468 if (!isset($this->all_recipients[strtolower($address)])) {
469 array_push($this->$kind, array($address, $name));
470 $this->all_recipients[strtolower($address)] = true;
474 if (!array_key_exists(strtolower($address), $this->ReplyTo)) {
475 $this->ReplyTo[strtolower($address)] = array($address, $name);
483 * Set the From and FromName properties
484 * @param string $address
485 * @param string $name
488 public function SetFrom($address, $name = '',$auto=1) {
489 $address = trim($address);
490 $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
491 if (!self::ValidateAddress($address)) {
492 $this->SetError($this->Lang('invalid_address').': '. $address);
493 if ($this->exceptions) {
494 throw new phpmailerException($this->Lang('invalid_address').': '.$address);
496 echo $this->Lang('invalid_address').': '.$address;
499 $this->From = $address;
500 $this->FromName = $name;
502 if (empty($this->ReplyTo)) {
503 $this->AddAnAddress('ReplyTo', $address, $name);
505 if (empty($this->Sender)) {
506 $this->Sender = $address;
513 * Check that a string looks roughly like an email address should
514 * Static so it can be used without instantiation
515 * Tries to use PHP built-in validator in the filter extension (from PHP 5.2), falls back to a reasonably competent regex validator
516 * Conforms approximately to RFC2822
517 * @link http://www.hexillion.com/samples/#Regex Original pattern found here
518 * @param string $address The email address to check
523 public static function ValidateAddress($address) {
524 if (function_exists('filter_var')) { //Introduced in PHP 5.2
525 if(filter_var($address, FILTER_VALIDATE_EMAIL) === FALSE) {
531 return preg_match('/^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!\.)){0,61}[a-zA-Z0-9_-]?\.)+[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!$)){0,61}[a-zA-Z0-9_]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/', $address);
535 /////////////////////////////////////////////////
536 // METHODS, MAIL SENDING
537 /////////////////////////////////////////////////
540 * Creates message and assigns Mailer. If the message is
541 * not sent successfully then it returns false. Use the ErrorInfo
542 * variable to view description of the error.
545 public function Send() {
547 if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) {
548 throw new phpmailerException($this->Lang('provide_address'), self::STOP_CRITICAL);
551 // Set whether the message is multipart/alternative
552 if(!empty($this->AltBody)) {
553 $this->ContentType = 'multipart/alternative';
556 $this->error_count = 0; // reset errors
557 $this->SetMessageType();
558 $header = $this->CreateHeader();
559 $body = $this->CreateBody();
561 if (empty($this->Body)) {
562 throw new phpmailerException($this->Lang('empty_message'), self::STOP_CRITICAL);
565 // digitally sign with DKIM if enabled
566 if ($this->DKIM_domain && $this->DKIM_private) {
567 $header_dkim = $this->DKIM_Add($header,$this->Subject,$body);
568 $header = str_replace("\r\n","\n",$header_dkim) . $header;
571 // Choose the mailer and send through it
572 switch($this->Mailer) {
574 return $this->SendmailSend($header, $body);
576 return $this->SmtpSend($header, $body);
578 $header .= $this->HeaderLine('Content-Transfer-Encoding', '8bit');
579 return $this->MailSend($header, $body);
582 } catch (phpmailerException $e) {
583 $this->SetError($e->getMessage());
584 if ($this->exceptions) {
587 echo $e->getMessage()."\n";
593 * Sends mail using the $Sendmail program.
594 * @param string $header The message headers
595 * @param string $body The message body
599 protected function SendmailSend($header, $body) {
600 if ($this->Sender != '') {
601 $sendmail = sprintf("%s -oi -f %s -t", escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
603 $sendmail = sprintf("%s -oi -t", escapeshellcmd($this->Sendmail));
605 if ($this->SingleTo === true) {
606 foreach ($this->SingleToArray as $key => $val) {
607 if(!@$mail = popen($sendmail, 'w')) {
608 throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
610 fputs($mail, "To: " . $val . "\n");
611 fputs($mail, $header);
613 $result = pclose($mail);
614 // implement call back function if it exists
615 $isSent = ($result == 0) ? 1 : 0;
616 $this->doCallback($isSent,$val,$this->cc,$this->bcc,$this->Subject,$body);
618 throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
622 if(!@$mail = popen($sendmail, 'w')) {
623 throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
625 fputs($mail, $header);
627 $result = pclose($mail);
628 // implement call back function if it exists
629 $isSent = ($result == 0) ? 1 : 0;
630 $this->doCallback($isSent,$this->to,$this->cc,$this->bcc,$this->Subject,$body);
632 throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
639 * Sends mail using the PHP mail() function.
640 * @param string $header The message headers
641 * @param string $body The message body
645 protected function MailSend($header, $body) {
647 foreach($this->to as $t) {
648 $toArr[] = $this->AddrFormat($t);
650 $to = implode(', ', $toArr);
652 $params = sprintf("-oi -f %s", $this->Sender);
653 if ($this->Sender != '' && strlen(ini_get('safe_mode'))< 1) {
654 $old_from = ini_get('sendmail_from');
655 ini_set('sendmail_from', $this->Sender);
656 if ($this->SingleTo === true && count($toArr) > 1) {
657 foreach ($toArr as $key => $val) {
658 $rt = @mail($val, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
659 // implement call back function if it exists
660 $isSent = ($rt == 1) ? 1 : 0;
661 $this->doCallback($isSent,$val,$this->cc,$this->bcc,$this->Subject,$body);
664 $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
665 // implement call back function if it exists
666 $isSent = ($rt == 1) ? 1 : 0;
667 $this->doCallback($isSent,$to,$this->cc,$this->bcc,$this->Subject,$body);
670 if ($this->SingleTo === true && count($toArr) > 1) {
671 foreach ($toArr as $key => $val) {
672 $rt = @mail($val, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
673 // implement call back function if it exists
674 $isSent = ($rt == 1) ? 1 : 0;
675 $this->doCallback($isSent,$val,$this->cc,$this->bcc,$this->Subject,$body);
678 $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header);
679 // implement call back function if it exists
680 $isSent = ($rt == 1) ? 1 : 0;
681 $this->doCallback($isSent,$to,$this->cc,$this->bcc,$this->Subject,$body);
684 if (isset($old_from)) {
685 ini_set('sendmail_from', $old_from);
688 throw new phpmailerException($this->Lang('instantiate'), self::STOP_CRITICAL);
694 * Sends mail via SMTP using PhpSMTP
695 * Returns false if there is a bad MAIL FROM, RCPT, or DATA input.
696 * @param string $header The message headers
697 * @param string $body The message body
702 protected function SmtpSend($header, $body) {
703 require_once $this->PluginDir . 'class.smtp.php';
706 if(!$this->SmtpConnect()) {
707 throw new phpmailerException($this->Lang('smtp_connect_failed'), self::STOP_CRITICAL);
709 $smtp_from = ($this->Sender == '') ? $this->From : $this->Sender;
710 if(!$this->smtp->Mail($smtp_from)) {
711 throw new phpmailerException($this->Lang('from_failed') . $smtp_from, self::STOP_CRITICAL);
714 // Attempt to send attach all recipients
715 foreach($this->to as $to) {
716 if (!$this->smtp->Recipient($to[0])) {
717 $bad_rcpt[] = $to[0];
718 // implement call back function if it exists
720 $this->doCallback($isSent,$to[0],'','',$this->Subject,$body);
722 // implement call back function if it exists
724 $this->doCallback($isSent,$to[0],'','',$this->Subject,$body);
727 foreach($this->cc as $cc) {
728 if (!$this->smtp->Recipient($cc[0])) {
729 $bad_rcpt[] = $cc[0];
730 // implement call back function if it exists
732 $this->doCallback($isSent,'',$cc[0],'',$this->Subject,$body);
734 // implement call back function if it exists
736 $this->doCallback($isSent,'',$cc[0],'',$this->Subject,$body);
739 foreach($this->bcc as $bcc) {
740 if (!$this->smtp->Recipient($bcc[0])) {
741 $bad_rcpt[] = $bcc[0];
742 // implement call back function if it exists
744 $this->doCallback($isSent,'','',$bcc[0],$this->Subject,$body);
746 // implement call back function if it exists
748 $this->doCallback($isSent,'','',$bcc[0],$this->Subject,$body);
753 if (count($bad_rcpt) > 0 ) { //Create error message for any bad addresses
754 $badaddresses = implode(', ', $bad_rcpt);
755 throw new phpmailerException($this->Lang('recipients_failed') . $badaddresses);
757 if(!$this->smtp->Data($header . $body)) {
758 throw new phpmailerException($this->Lang('data_not_accepted'), self::STOP_CRITICAL);
760 if($this->SMTPKeepAlive == true) {
761 $this->smtp->Reset();
767 * Initiates a connection to an SMTP server.
768 * Returns false if the operation failed.
773 public function SmtpConnect() {
774 if(is_null($this->smtp)) {
775 $this->smtp = new SMTP();
778 $this->smtp->do_debug = $this->SMTPDebug;
779 $hosts = explode(';', $this->Host);
781 $connection = $this->smtp->Connected();
783 // Retry while there is no connection
785 while($index < count($hosts) && !$connection) {
787 if (preg_match('/^(.+):([0-9]+)$/', $hosts[$index], $hostinfo)) {
788 $host = $hostinfo[1];
789 $port = $hostinfo[2];
791 $host = $hosts[$index];
795 $tls = ($this->SMTPSecure == 'tls');
796 $ssl = ($this->SMTPSecure == 'ssl');
798 if ($this->smtp->Connect(($ssl ? 'ssl://':'').$host, $port, $this->Timeout)) {
800 $hello = ($this->Helo != '' ? $this->Helo : $this->ServerHostname());
801 $this->smtp->Hello($hello);
804 if (!$this->smtp->StartTLS()) {
805 throw new phpmailerException($this->Lang('tls'));
808 //We must resend HELO after tls negotiation
809 $this->smtp->Hello($hello);
813 if ($this->SMTPAuth) {
814 if (!$this->smtp->Authenticate($this->Username, $this->Password)) {
815 throw new phpmailerException($this->Lang('authenticate'));
821 throw new phpmailerException($this->Lang('connect_host'));
824 } catch (phpmailerException $e) {
825 $this->smtp->Reset();
832 * Closes the active SMTP session if one exists.
835 public function SmtpClose() {
836 if(!is_null($this->smtp)) {
837 if($this->smtp->Connected()) {
839 $this->smtp->Close();
845 * Sets the language for all class error messages.
846 * Returns false if it cannot load the language file. The default language is English.
847 * @param string $langcode ISO 639-1 2-character language code (e.g. Portuguese: "br")
848 * @param string $lang_path Path to the language file directory
851 function SetLanguage($langcode = 'en', $lang_path = 'language/') {
852 //Define full set of translatable strings
853 $PHPMAILER_LANG = array(
854 'provide_address' => 'You must provide at least one recipient email address.',
855 'mailer_not_supported' => ' mailer is not supported.',
856 'execute' => 'Could not execute: ',
857 'instantiate' => 'Could not instantiate mail function.',
858 'authenticate' => 'SMTP Error: Could not authenticate.',
859 'from_failed' => 'The following From address failed: ',
860 'recipients_failed' => 'SMTP Error: The following recipients failed: ',
861 'data_not_accepted' => 'SMTP Error: Data not accepted.',
862 'connect_host' => 'SMTP Error: Could not connect to SMTP host.',
863 'file_access' => 'Could not access file: ',
864 'file_open' => 'File Error: Could not open file: ',
865 'encoding' => 'Unknown encoding: ',
866 'signing' => 'Signing Error: ',
867 'smtp_error' => 'SMTP server error: ',
868 'empty_message' => 'Message body empty',
869 'invalid_address' => 'Invalid address',
870 'variable_set' => 'Cannot set or reset variable: '
872 //Overwrite language-specific strings. This way we'll never have missing translations - no more "language string failed to load"!
874 if ($langcode != 'en') { //There is no English translation file
875 $l = @include $lang_path.'phpmailer.lang-'.$langcode.'.php';
877 $this->language = $PHPMAILER_LANG;
878 return ($l == true); //Returns false if language not found
882 * Return the current array of language strings
885 public function GetTranslations() {
886 return $this->language;
889 /////////////////////////////////////////////////
890 // METHODS, MESSAGE CREATION
891 /////////////////////////////////////////////////
894 * Creates recipient headers.
898 public function AddrAppend($type, $addr) {
899 $addr_str = $type . ': ';
900 $addresses = array();
901 foreach ($addr as $a) {
902 $addresses[] = $this->AddrFormat($a);
904 $addr_str .= implode(', ', $addresses);
905 $addr_str .= $this->LE;
911 * Formats an address correctly.
915 public function AddrFormat($addr) {
916 if (empty($addr[1])) {
917 return $this->SecureHeader($addr[0]);
919 return $this->EncodeHeader($this->SecureHeader($addr[1]), 'phrase') . " <" . $this->SecureHeader($addr[0]) . ">";
924 * Wraps message for use with mailers that do not
925 * automatically perform wrapping and for quoted-printable.
926 * Original written by philippe.
927 * @param string $message The message to wrap
928 * @param integer $length The line length to wrap to
929 * @param boolean $qp_mode Whether to run in Quoted-Printable mode
933 public function WrapText($message, $length, $qp_mode = false) {
934 $soft_break = ($qp_mode) ? sprintf(" =%s", $this->LE) : $this->LE;
935 // If utf-8 encoding is used, we will need to make sure we don't
936 // split multibyte characters when we wrap
937 $is_utf8 = (strtolower($this->CharSet) == "utf-8");
939 $message = $this->FixEOL($message);
940 if (substr($message, -1) == $this->LE) {
941 $message = substr($message, 0, -1);
944 $line = explode($this->LE, $message);
946 for ($i=0 ;$i < count($line); $i++) {
947 $line_part = explode(' ', $line[$i]);
949 for ($e = 0; $e<count($line_part); $e++) {
950 $word = $line_part[$e];
951 if ($qp_mode and (strlen($word) > $length)) {
952 $space_left = $length - strlen($buf) - 1;
954 if ($space_left > 20) {
957 $len = $this->UTF8CharBoundary($word, $len);
958 } elseif (substr($word, $len - 1, 1) == "=") {
960 } elseif (substr($word, $len - 2, 1) == "=") {
963 $part = substr($word, 0, $len);
964 $word = substr($word, $len);
966 $message .= $buf . sprintf("=%s", $this->LE);
968 $message .= $buf . $soft_break;
972 while (strlen($word) > 0) {
975 $len = $this->UTF8CharBoundary($word, $len);
976 } elseif (substr($word, $len - 1, 1) == "=") {
978 } elseif (substr($word, $len - 2, 1) == "=") {
981 $part = substr($word, 0, $len);
982 $word = substr($word, $len);
984 if (strlen($word) > 0) {
985 $message .= $part . sprintf("=%s", $this->LE);
992 $buf .= ($e == 0) ? $word : (' ' . $word);
994 if (strlen($buf) > $length and $buf_o != '') {
995 $message .= $buf_o . $soft_break;
1000 $message .= $buf . $this->LE;
1007 * Finds last character boundary prior to maxLength in a utf-8
1008 * quoted (printable) encoded string.
1009 * Original written by Colin Brown.
1011 * @param string $encodedText utf-8 QP text
1012 * @param int $maxLength find last character boundary prior to this length
1015 public function UTF8CharBoundary($encodedText, $maxLength) {
1016 $foundSplitPos = false;
1018 while (!$foundSplitPos) {
1019 $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
1020 $encodedCharPos = strpos($lastChunk, "=");
1021 if ($encodedCharPos !== false) {
1022 // Found start of encoded character byte within $lookBack block.
1023 // Check the encoded byte value (the 2 chars after the '=')
1024 $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
1025 $dec = hexdec($hex);
1026 if ($dec < 128) { // Single byte character.
1027 // If the encoded char was found at pos 0, it will fit
1028 // otherwise reduce maxLength to start of the encoded char
1029 $maxLength = ($encodedCharPos == 0) ? $maxLength :
1030 $maxLength - ($lookBack - $encodedCharPos);
1031 $foundSplitPos = true;
1032 } elseif ($dec >= 192) { // First byte of a multi byte character
1033 // Reduce maxLength to split at start of character
1034 $maxLength = $maxLength - ($lookBack - $encodedCharPos);
1035 $foundSplitPos = true;
1036 } elseif ($dec < 192) { // Middle byte of a multi byte character, look further back
1040 // No encoded character found
1041 $foundSplitPos = true;
1049 * Set the body wrapping.
1053 public function SetWordWrap() {
1054 if($this->WordWrap < 1) {
1058 switch($this->message_type) {
1060 case 'alt_attachments':
1061 $this->AltBody = $this->WrapText($this->AltBody, $this->WordWrap);
1064 $this->Body = $this->WrapText($this->Body, $this->WordWrap);
1070 * Assembles message header.
1072 * @return string The assembled header
1074 public function CreateHeader() {
1077 // Set the boundaries
1078 $uniq_id = md5(uniqid(time()));
1079 $this->boundary[1] = 'b1_' . $uniq_id;
1080 $this->boundary[2] = 'b2_' . $uniq_id;
1082 $result .= $this->HeaderLine('Date', self::RFCDate());
1083 if($this->Sender == '') {
1084 $result .= $this->HeaderLine('Return-Path', trim($this->From));
1086 $result .= $this->HeaderLine('Return-Path', trim($this->Sender));
1089 // To be created automatically by mail()
1090 if($this->Mailer != 'mail') {
1091 if ($this->SingleTo === true) {
1092 foreach($this->to as $t) {
1093 $this->SingleToArray[] = $this->AddrFormat($t);
1096 if(count($this->to) > 0) {
1097 $result .= $this->AddrAppend('To', $this->to);
1098 } elseif (count($this->cc) == 0) {
1099 $result .= $this->HeaderLine('To', 'undisclosed-recipients:;');
1105 $from[0][0] = trim($this->From);
1106 $from[0][1] = $this->FromName;
1107 $result .= $this->AddrAppend('From', $from);
1109 // sendmail and mail() extract Cc from the header before sending
1110 if(count($this->cc) > 0) {
1111 $result .= $this->AddrAppend('Cc', $this->cc);
1114 // sendmail and mail() extract Bcc from the header before sending
1115 if((($this->Mailer == 'sendmail') || ($this->Mailer == 'mail')) && (count($this->bcc) > 0)) {
1116 $result .= $this->AddrAppend('Bcc', $this->bcc);
1119 if(count($this->ReplyTo) > 0) {
1120 $result .= $this->AddrAppend('Reply-to', $this->ReplyTo);
1123 // mail() sets the subject itself
1124 if($this->Mailer != 'mail') {
1125 $result .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader($this->Subject)));
1128 if($this->MessageID != '') {
1129 $result .= $this->HeaderLine('Message-ID',$this->MessageID);
1131 $result .= sprintf("Message-ID: <%s@%s>%s", $uniq_id, $this->ServerHostname(), $this->LE);
1133 $result .= $this->HeaderLine('X-Priority', $this->Priority);
1134 $result .= $this->HeaderLine('X-Mailer', 'PHPMailer '.$this->Version.' (phpmailer.sourceforge.net)');
1136 if($this->ConfirmReadingTo != '') {
1137 $result .= $this->HeaderLine('Disposition-Notification-To', '<' . trim($this->ConfirmReadingTo) . '>');
1140 // Add custom headers
1141 for($index = 0; $index < count($this->CustomHeader); $index++) {
1142 $result .= $this->HeaderLine(trim($this->CustomHeader[$index][0]), $this->EncodeHeader(trim($this->CustomHeader[$index][1])));
1144 if (!$this->sign_key_file) {
1145 $result .= $this->HeaderLine('MIME-Version', '1.0');
1146 $result .= $this->GetMailMIME();
1153 * Returns the message MIME.
1157 public function GetMailMIME() {
1159 switch($this->message_type) {
1161 $result .= $this->HeaderLine('Content-Transfer-Encoding', $this->Encoding);
1162 $result .= sprintf("Content-Type: %s; charset=\"%s\"", $this->ContentType, $this->CharSet);
1165 case 'alt_attachments':
1166 if($this->InlineImageExists()){
1167 $result .= sprintf("Content-Type: %s;%s\ttype=\"text/html\";%s\tboundary=\"%s\"%s", 'multipart/related', $this->LE, $this->LE, $this->boundary[1], $this->LE);
1169 $result .= $this->HeaderLine('Content-Type', 'multipart/mixed;');
1170 $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
1174 $result .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
1175 $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
1179 if($this->Mailer != 'mail') {
1180 $result .= $this->LE.$this->LE;
1187 * Assembles the message body. Returns an empty string on failure.
1189 * @return string The assembled message body
1191 public function CreateBody() {
1194 if ($this->sign_key_file) {
1195 $body .= $this->GetMailMIME();
1198 $this->SetWordWrap();
1200 switch($this->message_type) {
1202 $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', '');
1203 $body .= $this->EncodeString($this->AltBody, $this->Encoding);
1204 $body .= $this->LE.$this->LE;
1205 $body .= $this->GetBoundary($this->boundary[1], '', 'text/html', '');
1206 $body .= $this->EncodeString($this->Body, $this->Encoding);
1207 $body .= $this->LE.$this->LE;
1208 $body .= $this->EndBoundary($this->boundary[1]);
1211 $body .= $this->EncodeString($this->Body, $this->Encoding);
1214 $body .= $this->GetBoundary($this->boundary[1], '', '', '');
1215 $body .= $this->EncodeString($this->Body, $this->Encoding);
1217 $body .= $this->AttachAll();
1219 case 'alt_attachments':
1220 $body .= sprintf("--%s%s", $this->boundary[1], $this->LE);
1221 $body .= sprintf("Content-Type: %s;%s" . "\tboundary=\"%s\"%s", 'multipart/alternative', $this->LE, $this->boundary[2], $this->LE.$this->LE);
1222 $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', '') . $this->LE; // Create text body
1223 $body .= $this->EncodeString($this->AltBody, $this->Encoding);
1224 $body .= $this->LE.$this->LE;
1225 $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', '') . $this->LE; // Create the HTML body
1226 $body .= $this->EncodeString($this->Body, $this->Encoding);
1227 $body .= $this->LE.$this->LE;
1228 $body .= $this->EndBoundary($this->boundary[2]);
1229 $body .= $this->AttachAll();
1233 if ($this->IsError()) {
1235 } elseif ($this->sign_key_file) {
1237 $file = tempnam('', 'mail');
1238 file_put_contents($file, $body); //TODO check this worked
1239 $signed = tempnam("", "signed");
1240 if (@openssl_pkcs7_sign($file, $signed, "file://".$this->sign_cert_file, array("file://".$this->sign_key_file, $this->sign_key_pass), NULL)) {
1243 $body = file_get_contents($signed);
1247 throw new phpmailerException($this->Lang("signing").openssl_error_string());
1249 } catch (phpmailerException $e) {
1251 if ($this->exceptions) {
1261 * Returns the start of a message boundary.
1264 private function GetBoundary($boundary, $charSet, $contentType, $encoding) {
1266 if($charSet == '') {
1267 $charSet = $this->CharSet;
1269 if($contentType == '') {
1270 $contentType = $this->ContentType;
1272 if($encoding == '') {
1273 $encoding = $this->Encoding;
1275 $result .= $this->TextLine('--' . $boundary);
1276 $result .= sprintf("Content-Type: %s; charset = \"%s\"", $contentType, $charSet);
1277 $result .= $this->LE;
1278 $result .= $this->HeaderLine('Content-Transfer-Encoding', $encoding);
1279 $result .= $this->LE;
1285 * Returns the end of a message boundary.
1288 private function EndBoundary($boundary) {
1289 return $this->LE . '--' . $boundary . '--' . $this->LE;
1293 * Sets the message type.
1297 private function SetMessageType() {
1298 if(count($this->attachment) < 1 && strlen($this->AltBody) < 1) {
1299 $this->message_type = 'plain';
1301 if(count($this->attachment) > 0) {
1302 $this->message_type = 'attachments';
1304 if(strlen($this->AltBody) > 0 && count($this->attachment) < 1) {
1305 $this->message_type = 'alt';
1307 if(strlen($this->AltBody) > 0 && count($this->attachment) > 0) {
1308 $this->message_type = 'alt_attachments';
1314 * Returns a formatted header line.
1318 public function HeaderLine($name, $value) {
1319 return $name . ': ' . $value . $this->LE;
1323 * Returns a formatted mail line.
1327 public function TextLine($value) {
1328 return $value . $this->LE;
1331 /////////////////////////////////////////////////
1332 // CLASS METHODS, ATTACHMENTS
1333 /////////////////////////////////////////////////
1336 * Adds an attachment from a path on the filesystem.
1337 * Returns false if the file could not be found
1339 * @param string $path Path to the attachment.
1340 * @param string $name Overrides the attachment name.
1341 * @param string $encoding File encoding (see $Encoding).
1342 * @param string $type File extension (MIME) type.
1345 public function AddAttachment($path, $name = '', $encoding = 'base64', $type = 'application/octet-stream') {
1347 if ( !@is_file($path) ) {
1348 throw new phpmailerException($this->Lang('file_access') . $path, self::STOP_CONTINUE);
1350 $filename = basename($path);
1351 if ( $name == '' ) {
1355 $this->attachment[] = array(
1361 5 => false, // isStringAttachment
1366 } catch (phpmailerException $e) {
1367 $this->SetError($e->getMessage());
1368 if ($this->exceptions) {
1371 echo $e->getMessage()."\n";
1372 if ( $e->getCode() == self::STOP_CRITICAL ) {
1380 * Return the current array of attachments
1383 public function GetAttachments() {
1384 return $this->attachment;
1388 * Attaches all fs, string, and binary attachments to the message.
1389 * Returns an empty string on failure.
1393 private function AttachAll() {
1394 // Return text of body
1399 // Add all attachments
1400 foreach ($this->attachment as $attachment) {
1401 // Check for string attachment
1402 $bString = $attachment[5];
1404 $string = $attachment[0];
1406 $path = $attachment[0];
1409 if (in_array($attachment[0], $incl)) { continue; }
1410 $filename = $attachment[1];
1411 $name = $attachment[2];
1412 $encoding = $attachment[3];
1413 $type = $attachment[4];
1414 $disposition = $attachment[6];
1415 $cid = $attachment[7];
1416 $incl[] = $attachment[0];
1417 if ( $disposition == 'inline' && isset($cidUniq[$cid]) ) { continue; }
1418 $cidUniq[$cid] = true;
1420 $mime[] = sprintf("--%s%s", $this->boundary[1], $this->LE);
1421 $mime[] = sprintf("Content-Type: %s; name=\"%s\"%s", $type, $this->EncodeHeader($this->SecureHeader($name)), $this->LE);
1422 $mime[] = sprintf("Content-Transfer-Encoding: %s%s", $encoding, $this->LE);
1424 if($disposition == 'inline') {
1425 $mime[] = sprintf("Content-ID: <%s>%s", $cid, $this->LE);
1428 $mime[] = sprintf("Content-Disposition: %s; filename=\"%s\"%s", $disposition, $this->EncodeHeader($this->SecureHeader($name)), $this->LE.$this->LE);
1430 // Encode as string attachment
1432 $mime[] = $this->EncodeString($string, $encoding);
1433 if($this->IsError()) {
1436 $mime[] = $this->LE.$this->LE;
1438 $mime[] = $this->EncodeFile($path, $encoding);
1439 if($this->IsError()) {
1442 $mime[] = $this->LE.$this->LE;
1446 $mime[] = sprintf("--%s--%s", $this->boundary[1], $this->LE);
1448 return join('', $mime);
1452 * Encodes attachment in requested format.
1453 * Returns an empty string on failure.
1454 * @param string $path The full path to the file
1455 * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
1460 private function EncodeFile($path, $encoding = 'base64') {
1462 if (!is_readable($path)) {
1463 throw new phpmailerException($this->Lang('file_open') . $path, self::STOP_CONTINUE);
1465 if (function_exists('get_magic_quotes')) {
1466 function get_magic_quotes() {
1470 if (PHP_VERSION < 6) {
1471 $magic_quotes = get_magic_quotes_runtime();
1472 set_magic_quotes_runtime(0);
1474 $file_buffer = file_get_contents($path);
1475 $file_buffer = $this->EncodeString($file_buffer, $encoding);
1476 if (PHP_VERSION < 6) { set_magic_quotes_runtime($magic_quotes); }
1477 return $file_buffer;
1478 } catch (Exception $e) {
1479 $this->SetError($e->getMessage());
1485 * Encodes string to requested format.
1486 * Returns an empty string on failure.
1487 * @param string $str The text to encode
1488 * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
1492 public function EncodeString ($str, $encoding = 'base64') {
1494 switch(strtolower($encoding)) {
1496 $encoded = chunk_split(base64_encode($str), 76, $this->LE);
1500 $encoded = $this->FixEOL($str);
1501 //Make sure it ends with a line break
1502 if (substr($encoded, -(strlen($this->LE))) != $this->LE)
1503 $encoded .= $this->LE;
1508 case 'quoted-printable':
1509 $encoded = $this->EncodeQP($str);
1512 $this->SetError($this->Lang('encoding') . $encoding);
1519 * Encode a header string to best (shortest) of Q, B, quoted or none.
1523 public function EncodeHeader($str, $position = 'text') {
1526 switch (strtolower($position)) {
1528 if (!preg_match('/[\200-\377]/', $str)) {
1529 // Can't use addslashes as we don't know what value has magic_quotes_sybase
1530 $encoded = addcslashes($str, "\0..\37\177\\\"");
1531 if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
1534 return ("\"$encoded\"");
1537 $x = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
1540 $x = preg_match_all('/[()"]/', $str, $matches);
1544 $x += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
1552 $maxlen = 75 - 7 - strlen($this->CharSet);
1553 // Try to select the encoding which should produce the shortest output
1554 if (strlen($str)/3 < $x) {
1556 if (function_exists('mb_strlen') && $this->HasMultiBytes($str)) {
1557 // Use a custom function which correctly encodes and wraps long
1558 // multibyte strings without breaking lines within a character
1559 $encoded = $this->Base64EncodeWrapMB($str);
1561 $encoded = base64_encode($str);
1562 $maxlen -= $maxlen % 4;
1563 $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
1567 $encoded = $this->EncodeQ($str, $position);
1568 $encoded = $this->WrapText($encoded, $maxlen, true);
1569 $encoded = str_replace('='.$this->LE, "\n", trim($encoded));
1572 $encoded = preg_replace('/^(.*)$/m', " =?".$this->CharSet."?$encoding?\\1?=", $encoded);
1573 $encoded = trim(str_replace("\n", $this->LE, $encoded));
1579 * Checks if a string contains multibyte characters.
1581 * @param string $str multi-byte text to wrap encode
1584 public function HasMultiBytes($str) {
1585 if (function_exists('mb_strlen')) {
1586 return (strlen($str) > mb_strlen($str, $this->CharSet));
1587 } else { // Assume no multibytes (we can't handle without mbstring functions anyway)
1593 * Correctly encodes and wraps long multibyte strings for mail headers
1594 * without breaking lines within a character.
1595 * Adapted from a function by paravoid at http://uk.php.net/manual/en/function.mb-encode-mimeheader.php
1597 * @param string $str multi-byte text to wrap encode
1600 public function Base64EncodeWrapMB($str) {
1601 $start = "=?".$this->CharSet."?B?";
1605 $mb_length = mb_strlen($str, $this->CharSet);
1606 // Each line must have length <= 75, including $start and $end
1607 $length = 75 - strlen($start) - strlen($end);
1608 // Average multi-byte ratio
1609 $ratio = $mb_length / strlen($str);
1610 // Base64 has a 4:3 ratio
1611 $offset = $avgLength = floor($length * $ratio * .75);
1613 for ($i = 0; $i < $mb_length; $i += $offset) {
1617 $offset = $avgLength - $lookBack;
1618 $chunk = mb_substr($str, $i, $offset, $this->CharSet);
1619 $chunk = base64_encode($chunk);
1622 while (strlen($chunk) > $length);
1624 $encoded .= $chunk . $this->LE;
1627 // Chomp the last linefeed
1628 $encoded = substr($encoded, 0, -strlen($this->LE));
1633 * Encode string to quoted-printable.
1634 * Only uses standard PHP, slow, but will always work
1636 * @param string $string the text to encode
1637 * @param integer $line_max Number of chars allowed on a line before wrapping
1640 public function EncodeQPphp( $input = '', $line_max = 76, $space_conv = false) {
1641 $hex = array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');
1642 $lines = preg_split('/(?:\r\n|\r|\n)/', $input);
1646 while( list(, $line) = each($lines) ) {
1647 $linlen = strlen($line);
1649 for($i = 0; $i < $linlen; $i++) {
1650 $c = substr( $line, $i, 1 );
1652 if ( ( $i == 0 ) && ( $dec == 46 ) ) { // convert first point in the line into =2E
1656 if ( $i == ( $linlen - 1 ) ) { // convert space at eol only
1658 } else if ( $space_conv ) {
1661 } elseif ( ($dec == 61) || ($dec < 32 ) || ($dec > 126) ) { // always encode "\t", which is *not* required
1662 $h2 = floor($dec/16);
1663 $h1 = floor($dec%16);
1664 $c = $escape.$hex[$h2].$hex[$h1];
1666 if ( (strlen($newline) + strlen($c)) >= $line_max ) { // CRLF is not counted
1667 $output .= $newline.$escape.$eol; // soft line break; " =\r\n" is okay
1669 // check if newline first character will be point or not
1676 $output .= $newline.$eol;
1682 * Encode string to RFC2045 (6.7) quoted-printable format
1683 * Uses a PHP5 stream filter to do the encoding about 64x faster than the old version
1684 * Also results in same content as you started with after decoding
1685 * @see EncodeQPphp()
1687 * @param string $string the text to encode
1688 * @param integer $line_max Number of chars allowed on a line before wrapping
1689 * @param boolean $space_conv Dummy param for compatibility with existing EncodeQP function
1691 * @author Marcus Bointon
1693 public function EncodeQP($string, $line_max = 76, $space_conv = false) {
1694 if (function_exists('quoted_printable_encode')) { //Use native function if it's available (>= PHP5.3)
1695 return quoted_printable_encode($string);
1697 $filters = stream_get_filters();
1698 if (!in_array('convert.*', $filters)) { //Got convert stream filter?
1699 return $this->EncodeQPphp($string, $line_max, $space_conv); //Fall back to old implementation
1701 $fp = fopen('php://temp/', 'r+');
1702 $string = preg_replace('/\r\n?/', $this->LE, $string); //Normalise line breaks
1703 $params = array('line-length' => $line_max, 'line-break-chars' => $this->LE);
1704 $s = stream_filter_append($fp, 'convert.quoted-printable-encode', STREAM_FILTER_READ, $params);
1705 fputs($fp, $string);
1707 $out = stream_get_contents($fp);
1708 stream_filter_remove($s);
1709 $out = preg_replace('/^\./m', '=2E', $out); //Encode . if it is first char on a line, workaround for bug in Exchange
1715 * Encode string to q encoding.
1716 * @link http://tools.ietf.org/html/rfc2047
1717 * @param string $str the text to encode
1718 * @param string $position Where the text is going to be used, see the RFC for what that means
1722 public function EncodeQ ($str, $position = 'text') {
1723 // There should not be any EOL in the string
1724 $encoded = preg_replace('/[\r\n]*/', '', $str);
1726 switch (strtolower($position)) {
1728 $encoded = preg_replace("/([^A-Za-z0-9!*+\/ -])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded);
1731 $encoded = preg_replace("/([\(\)\"])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded);
1734 // Replace every high ascii, control =, ? and _ characters
1735 //TODO using /e (equivalent to eval()) is probably not a good idea
1736 $encoded = preg_replace('/([\000-\011\013\014\016-\037\075\077\137\177-\377])/e',
1737 "'='.sprintf('%02X', ord('\\1'))", $encoded);
1741 // Replace every spaces to _ (more readable than =20)
1742 $encoded = str_replace(' ', '_', $encoded);
1748 * Adds a string or binary attachment (non-filesystem) to the list.
1749 * This method can be used to attach ascii or binary data,
1750 * such as a BLOB record from a database.
1751 * @param string $string String attachment data.
1752 * @param string $filename Name of the attachment.
1753 * @param string $encoding File encoding (see $Encoding).
1754 * @param string $type File extension (MIME) type.
1757 public function AddStringAttachment($string, $filename, $encoding = 'base64', $type = 'application/octet-stream') {
1758 // Append to $attachment array
1759 $this->attachment[] = array(
1762 2 => basename($filename),
1765 5 => true, // isStringAttachment
1772 * Adds an embedded attachment. This can include images, sounds, and
1773 * just about any other document. Make sure to set the $type to an
1774 * image type. For JPEG images use "image/jpeg" and for GIF images
1776 * @param string $path Path to the attachment.
1777 * @param string $cid Content ID of the attachment. Use this to identify
1778 * the Id for accessing the image in an HTML form.
1779 * @param string $name Overrides the attachment name.
1780 * @param string $encoding File encoding (see $Encoding).
1781 * @param string $type File extension (MIME) type.
1784 public function AddEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = 'application/octet-stream') {
1786 if ( !@is_file($path) ) {
1787 $this->SetError($this->Lang('file_access') . $path);
1791 $filename = basename($path);
1792 if ( $name == '' ) {
1796 // Append to $attachment array
1797 $this->attachment[] = array(
1803 5 => false, // isStringAttachment
1812 * Returns true if an inline attachment is present.
1816 public function InlineImageExists() {
1817 foreach($this->attachment as $attachment) {
1818 if ($attachment[6] == 'inline') {
1825 /////////////////////////////////////////////////
1826 // CLASS METHODS, MESSAGE RESET
1827 /////////////////////////////////////////////////
1830 * Clears all recipients assigned in the TO array. Returns void.
1833 public function ClearAddresses() {
1834 foreach($this->to as $to) {
1835 unset($this->all_recipients[strtolower($to[0])]);
1837 $this->to = array();
1841 * Clears all recipients assigned in the CC array. Returns void.
1844 public function ClearCCs() {
1845 foreach($this->cc as $cc) {
1846 unset($this->all_recipients[strtolower($cc[0])]);
1848 $this->cc = array();
1852 * Clears all recipients assigned in the BCC array. Returns void.
1855 public function ClearBCCs() {
1856 foreach($this->bcc as $bcc) {
1857 unset($this->all_recipients[strtolower($bcc[0])]);
1859 $this->bcc = array();
1863 * Clears all recipients assigned in the ReplyTo array. Returns void.
1866 public function ClearReplyTos() {
1867 $this->ReplyTo = array();
1871 * Clears all recipients assigned in the TO, CC and BCC
1872 * array. Returns void.
1875 public function ClearAllRecipients() {
1876 $this->to = array();
1877 $this->cc = array();
1878 $this->bcc = array();
1879 $this->all_recipients = array();
1883 * Clears all previously set filesystem, string, and binary
1884 * attachments. Returns void.
1887 public function ClearAttachments() {
1888 $this->attachment = array();
1892 * Clears all custom headers. Returns void.
1895 public function ClearCustomHeaders() {
1896 $this->CustomHeader = array();
1899 /////////////////////////////////////////////////
1900 // CLASS METHODS, MISCELLANEOUS
1901 /////////////////////////////////////////////////
1904 * Adds the error message to the error container.
1908 protected function SetError($msg) {
1909 $this->error_count++;
1910 if ($this->Mailer == 'smtp' and !is_null($this->smtp)) {
1911 $lasterror = $this->smtp->getError();
1912 if (!empty($lasterror) and array_key_exists('smtp_msg', $lasterror)) {
1913 $msg .= '<p>' . $this->Lang('smtp_error') . $lasterror['smtp_msg'] . "</p>\n";
1916 $this->ErrorInfo = $msg;
1920 * Returns the proper RFC 822 formatted date.
1925 public static function RFCDate() {
1927 $tzs = ($tz < 0) ? '-' : '+';
1929 $tz = (int)($tz/3600)*100 + ($tz%3600)/60;
1930 $result = sprintf("%s %s%04d", date('D, j M Y H:i:s'), $tzs, $tz);
1936 * Returns the server hostname or 'localhost.localdomain' if unknown.
1940 private function ServerHostname() {
1941 if (!empty($this->Hostname)) {
1942 $result = $this->Hostname;
1943 } elseif (isset($_SERVER['SERVER_NAME'])) {
1944 $result = $_SERVER['SERVER_NAME'];
1946 $result = 'localhost.localdomain';
1953 * Returns a message in the appropriate language.
1957 private function Lang($key) {
1958 if(count($this->language) < 1) {
1959 $this->SetLanguage('en'); // set the default language
1962 if(isset($this->language[$key])) {
1963 return $this->language[$key];
1965 return 'Language string failed to load: ' . $key;
1970 * Returns true if an error occurred.
1974 public function IsError() {
1975 return ($this->error_count > 0);
1979 * Changes every end of line from CR or LF to CRLF.
1983 private function FixEOL($str) {
1984 $str = str_replace("\r\n", "\n", $str);
1985 $str = str_replace("\r", "\n", $str);
1986 $str = str_replace("\n", $this->LE, $str);
1991 * Adds a custom header.
1995 public function AddCustomHeader($custom_header) {
1996 $this->CustomHeader[] = explode(':', $custom_header, 2);
2000 * Evaluates the message and returns modifications for inline images and backgrounds
2004 public function MsgHTML($message, $basedir = '') {
2005 preg_match_all("/(src|background)=\"(.*)\"/Ui", $message, $images);
2006 if(isset($images[2])) {
2007 foreach($images[2] as $i => $url) {
2008 // do not change urls for absolute images (thanks to corvuscorax)
2009 if (!preg_match('#^[A-z]+://#',$url)) {
2010 $filename = basename($url);
2011 $directory = dirname($url);
2012 ($directory == '.')?$directory='':'';
2013 $cid = 'cid:' . md5($filename);
2014 $ext = pathinfo($filename, PATHINFO_EXTENSION);
2015 $mimeType = self::_mime_types($ext);
2016 if ( strlen($basedir) > 1 && substr($basedir,-1) != '/') { $basedir .= '/'; }
2017 if ( strlen($directory) > 1 && substr($directory,-1) != '/') { $directory .= '/'; }
2018 if ( $this->AddEmbeddedImage($basedir.$directory.$filename, md5($filename), $filename, 'base64',$mimeType) ) {
2019 $message = preg_replace("/".$images[1][$i]."=\"".preg_quote($url, '/')."\"/Ui", $images[1][$i]."=\"".$cid."\"", $message);
2024 $this->IsHTML(true);
2025 $this->Body = $message;
2026 $textMsg = trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/s','',$message)));
2027 if (!empty($textMsg) && empty($this->AltBody)) {
2028 $this->AltBody = html_entity_decode($textMsg);
2030 if (empty($this->AltBody)) {
2031 $this->AltBody = 'To view this email message, open it in a program that understands HTML!' . "\n\n";
2036 * Gets the MIME type of the embedded or inline image
2037 * @param string File extension
2039 * @return string MIME type of ext
2042 public static function _mime_types($ext = '') {
2044 'hqx' => 'application/mac-binhex40',
2045 'cpt' => 'application/mac-compactpro',
2046 'doc' => 'application/msword',
2047 'bin' => 'application/macbinary',
2048 'dms' => 'application/octet-stream',
2049 'lha' => 'application/octet-stream',
2050 'lzh' => 'application/octet-stream',
2051 'exe' => 'application/octet-stream',
2052 'class' => 'application/octet-stream',
2053 'psd' => 'application/octet-stream',
2054 'so' => 'application/octet-stream',
2055 'sea' => 'application/octet-stream',
2056 'dll' => 'application/octet-stream',
2057 'oda' => 'application/oda',
2058 'pdf' => 'application/pdf',
2059 'ai' => 'application/postscript',
2060 'eps' => 'application/postscript',
2061 'ps' => 'application/postscript',
2062 'smi' => 'application/smil',
2063 'smil' => 'application/smil',
2064 'mif' => 'application/vnd.mif',
2065 'xls' => 'application/vnd.ms-excel',
2066 'ppt' => 'application/vnd.ms-powerpoint',
2067 'wbxml' => 'application/vnd.wap.wbxml',
2068 'wmlc' => 'application/vnd.wap.wmlc',
2069 'dcr' => 'application/x-director',
2070 'dir' => 'application/x-director',
2071 'dxr' => 'application/x-director',
2072 'dvi' => 'application/x-dvi',
2073 'gtar' => 'application/x-gtar',
2074 'php' => 'application/x-httpd-php',
2075 'php4' => 'application/x-httpd-php',
2076 'php3' => 'application/x-httpd-php',
2077 'phtml' => 'application/x-httpd-php',
2078 'phps' => 'application/x-httpd-php-source',
2079 'js' => 'application/x-javascript',
2080 'swf' => 'application/x-shockwave-flash',
2081 'sit' => 'application/x-stuffit',
2082 'tar' => 'application/x-tar',
2083 'tgz' => 'application/x-tar',
2084 'xhtml' => 'application/xhtml+xml',
2085 'xht' => 'application/xhtml+xml',
2086 'zip' => 'application/zip',
2087 'mid' => 'audio/midi',
2088 'midi' => 'audio/midi',
2089 'mpga' => 'audio/mpeg',
2090 'mp2' => 'audio/mpeg',
2091 'mp3' => 'audio/mpeg',
2092 'aif' => 'audio/x-aiff',
2093 'aiff' => 'audio/x-aiff',
2094 'aifc' => 'audio/x-aiff',
2095 'ram' => 'audio/x-pn-realaudio',
2096 'rm' => 'audio/x-pn-realaudio',
2097 'rpm' => 'audio/x-pn-realaudio-plugin',
2098 'ra' => 'audio/x-realaudio',
2099 'rv' => 'video/vnd.rn-realvideo',
2100 'wav' => 'audio/x-wav',
2101 'bmp' => 'image/bmp',
2102 'gif' => 'image/gif',
2103 'jpeg' => 'image/jpeg',
2104 'jpg' => 'image/jpeg',
2105 'jpe' => 'image/jpeg',
2106 'png' => 'image/png',
2107 'tiff' => 'image/tiff',
2108 'tif' => 'image/tiff',
2109 'css' => 'text/css',
2110 'html' => 'text/html',
2111 'htm' => 'text/html',
2112 'shtml' => 'text/html',
2113 'txt' => 'text/plain',
2114 'text' => 'text/plain',
2115 'log' => 'text/plain',
2116 'rtx' => 'text/richtext',
2117 'rtf' => 'text/rtf',
2118 'xml' => 'text/xml',
2119 'xsl' => 'text/xml',
2120 'mpeg' => 'video/mpeg',
2121 'mpg' => 'video/mpeg',
2122 'mpe' => 'video/mpeg',
2123 'qt' => 'video/quicktime',
2124 'mov' => 'video/quicktime',
2125 'avi' => 'video/x-msvideo',
2126 'movie' => 'video/x-sgi-movie',
2127 'doc' => 'application/msword',
2128 'word' => 'application/msword',
2129 'xl' => 'application/excel',
2130 'eml' => 'message/rfc822'
2132 return (!isset($mimes[strtolower($ext)])) ? 'application/octet-stream' : $mimes[strtolower($ext)];
2136 * Set (or reset) Class Objects (variables)
2139 * $page->set('X-Priority', '3');
2142 * @param string $name Parameter Name
2143 * @param mixed $value Parameter Value
2144 * NOTE: will not work with arrays, there are no arrays to set/reset
2145 * @todo Should this not be using __set() magic function?
2147 public function set($name, $value = '') {
2149 if (isset($this->$name) ) {
2150 $this->$name = $value;
2152 throw new phpmailerException($this->Lang('variable_set') . $name, self::STOP_CRITICAL);
2154 } catch (Exception $e) {
2155 $this->SetError($e->getMessage());
2156 if ($e->getCode() == self::STOP_CRITICAL) {
2164 * Strips newlines to prevent header injection.
2166 * @param string $str String
2169 public function SecureHeader($str) {
2170 $str = str_replace("\r", '', $str);
2171 $str = str_replace("\n", '', $str);
2176 * Set the private key file and password to sign the message.
2179 * @param string $key_filename Parameter File Name
2180 * @param string $key_pass Password for private key
2182 public function Sign($cert_filename, $key_filename, $key_pass) {
2183 $this->sign_cert_file = $cert_filename;
2184 $this->sign_key_file = $key_filename;
2185 $this->sign_key_pass = $key_pass;
2189 * Set the private key file and password to sign the message.
2192 * @param string $key_filename Parameter File Name
2193 * @param string $key_pass Password for private key
2195 public function DKIM_QP($txt) {
2198 for ($i=0;$i<strlen($txt);$i++) {
2200 if ( ((0x21 <= $ord) && ($ord <= 0x3A)) || $ord == 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E)) ) {
2203 $line.="=".sprintf("%02X",$ord);
2210 * Generate DKIM signature
2213 * @param string $s Header
2215 public function DKIM_Sign($s) {
2216 $privKeyStr = file_get_contents($this->DKIM_private);
2217 if ($this->DKIM_passphrase!='') {
2218 $privKey = openssl_pkey_get_private($privKeyStr,$this->DKIM_passphrase);
2220 $privKey = $privKeyStr;
2222 if (openssl_sign($s, $signature, $privKey)) {
2223 return base64_encode($signature);
2228 * Generate DKIM Canonicalization Header
2231 * @param string $s Header
2233 public function DKIM_HeaderC($s) {
2234 $s=preg_replace("/\r\n\s+/"," ",$s);
2235 $lines=explode("\r\n",$s);
2236 foreach ($lines as $key=>$line) {
2237 list($heading,$value)=explode(":",$line,2);
2238 $heading=strtolower($heading);
2239 $value=preg_replace("/\s+/"," ",$value) ; // Compress useless spaces
2240 $lines[$key]=$heading.":".trim($value) ; // Don't forget to remove WSP around the value
2242 $s=implode("\r\n",$lines);
2247 * Generate DKIM Canonicalization Body
2250 * @param string $body Message Body
2252 public function DKIM_BodyC($body) {
2253 if ($body == '') return "\r\n";
2254 // stabilize line endings
2255 $body=str_replace("\r\n","\n",$body);
2256 $body=str_replace("\n","\r\n",$body);
2257 // END stabilize line endings
2258 while (substr($body,strlen($body)-4,4) == "\r\n\r\n") {
2259 $body=substr($body,0,strlen($body)-2);
2265 * Create the DKIM header, body, as new header
2268 * @param string $headers_line Header lines
2269 * @param string $subject Subject
2270 * @param string $body Body
2272 public function DKIM_Add($headers_line,$subject,$body) {
2273 $DKIMsignatureType = 'rsa-sha1'; // Signature & hash algorithms
2274 $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body
2275 $DKIMquery = 'dns/txt'; // Query method
2276 $DKIMtime = time() ; // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone)
2277 $subject_header = "Subject: $subject";
2278 $headers = explode("\r\n",$headers_line);
2279 foreach($headers as $header) {
2280 if (strpos($header,'From:') === 0) {
2281 $from_header=$header;
2282 } elseif (strpos($header,'To:') === 0) {
2286 $from = str_replace('|','=7C',$this->DKIM_QP($from_header));
2287 $to = str_replace('|','=7C',$this->DKIM_QP($to_header));
2288 $subject = str_replace('|','=7C',$this->DKIM_QP($subject_header)) ; // Copied header fields (dkim-quoted-printable
2289 $body = $this->DKIM_BodyC($body);
2290 $DKIMlen = strlen($body) ; // Length of body
2291 $DKIMb64 = base64_encode(pack("H*", sha1($body))) ; // Base64 of packed binary SHA-1 hash of body
2292 $ident = ($this->DKIM_identity == '')? '' : " i=" . $this->DKIM_identity . ";";
2293 $dkimhdrs = "DKIM-Signature: v=1; a=" . $DKIMsignatureType . "; q=" . $DKIMquery . "; l=" . $DKIMlen . "; s=" . $this->DKIM_selector . ";\r\n".
2294 "\tt=" . $DKIMtime . "; c=" . $DKIMcanonicalization . ";\r\n".
2295 "\th=From:To:Subject;\r\n".
2296 "\td=" . $this->DKIM_domain . ";" . $ident . "\r\n".
2300 "\tbh=" . $DKIMb64 . ";\r\n".
2302 $toSign = $this->DKIM_HeaderC($from_header . "\r\n" . $to_header . "\r\n" . $subject_header . "\r\n" . $dkimhdrs);
2303 $signed = $this->DKIM_Sign($toSign);
2304 return "X-PHPMAILER-DKIM: phpmailer.worxware.com\r\n".$dkimhdrs.$signed."\r\n";
2307 protected function doCallback($isSent,$to,$cc,$bcc,$subject,$body) {
2308 if (!empty($this->action_function) && function_exists($this->action_function)) {
2309 $params = array($isSent,$to,$cc,$bcc,$subject,$body);
2310 call_user_func_array($this->action_function,$params);
2315 class phpmailerException extends Exception {
2316 public function errorMessage() {
2317 $errorMsg = '<strong>' . $this->getMessage() . "</strong><br />\n";