diff --git a/LICENSE b/LICENSE index f3f1b3b65..8e0763d1c 100644 --- a/LICENSE +++ b/LICENSE @@ -312,7 +312,7 @@ of these things: from a designated place, offer equivalent access to copy the above specified materials from the same place. - e) Verify that the user has already received a copy of these + e) verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the diff --git a/PHPMailerAutoload.php b/PHPMailerAutoload.php new file mode 100644 index 000000000..46db5bd0b --- /dev/null +++ b/PHPMailerAutoload.php @@ -0,0 +1,33 @@ + + * @author Jim Jagielski (jimjag) + * @author Andy Prevost (codeworxtech) + * @author Brent R. Matzelle (original founder) + * @copyright 2013 Marcus Bointon + * @copyright 2010 - 2012 Jim Jagielski + * @copyright 2004 - 2009 Andy Prevost + * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License + * @note This program is distributed in the hope that it will be useful - WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. + */ + +/** + * PHPMailer SPL autoloader. + * @param string $classname The name of the class to load + */ +function PHPMailerAutoload($classname) +{ + //Can't use __DIR__ as it's only in PHP 5.3+ + $filename = dirname(__FILE__).DIRECTORY_SEPARATOR.'class.'.strtolower($classname).'.php'; + if (is_readable($filename)) { + require $filename; + } +} + +spl_autoload_register('PHPMailerAutoload'); diff --git a/README.md b/README.md index 671141da7..e14d5a960 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ Build status: [![Build Status](https://travis-ci.org/Synchro/PHPMailer.png)](htt - Probably the world's most popular code for sending email from PHP! - Used by many open-source projects: Drupal, SugarCRM, Yii, Joomla! and many more - Integrated SMTP support - send without a local mail server -- Send emails with multiple TOs, CCs, BCCs and REPLY-TOs +- send emails with multiple TOs, CCs, BCCs and REPLY-TOs - Multipart/alternative emails for mail clients that do not read HTML email - Support for 8bit, base64, binary, and quoted-printable encoding - SMTP authentication with LOGIN, PLAIN, NTLM and CRAM-MD5 mechanisms @@ -42,7 +42,7 @@ require 'class.phpmailer.php'; $mail = new PHPMailer; -$mail->IsSMTP(); // Set mailer to use SMTP +$mail->isSMTP(); // Set mailer to use SMTP $mail->Host = 'smtp1.example.com;smtp2.example.com'; // Specify main and backup server $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = 'jswan'; // SMTP username @@ -51,22 +51,22 @@ $mail->SMTPSecure = 'tls'; // Enable encryption, 'ssl $mail->From = 'from@example.com'; $mail->FromName = 'Mailer'; -$mail->AddAddress('josh@example.net', 'Josh Adams'); // Add a recipient -$mail->AddAddress('ellen@example.com'); // Name is optional -$mail->AddReplyTo('info@example.com', 'Information'); -$mail->AddCC('cc@example.com'); -$mail->AddBCC('bcc@example.com'); +$mail->addAddress('josh@example.net', 'Josh Adams'); // Add a recipient +$mail->addAddress('ellen@example.com'); // Name is optional +$mail->addReplyTo('info@example.com', 'Information'); +$mail->addCC('cc@example.com'); +$mail->addBCC('bcc@example.com'); $mail->WordWrap = 50; // Set word wrap to 50 characters -$mail->AddAttachment('/var/tmp/file.tar.gz'); // Add attachments -$mail->AddAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name -$mail->IsHTML(true); // Set email format to HTML +$mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments +$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name +$mail->isHTML(true); // Set email format to HTML $mail->Subject = 'Here is the subject'; $mail->Body = 'This is the HTML message body in bold!'; $mail->AltBody = 'This is the body in plain text for non-HTML mail clients'; -if(!$mail->Send()) { +if(!$mail->send()) { echo 'Message could not be sent.'; echo 'Mailer Error: ' . $mail->ErrorInfo; exit; @@ -84,7 +84,7 @@ PHPMailer defaults to English, but in the `languages` folder you'll find numerou ```php // To load the French version -$mail->SetLanguage('fr', '/optional/path/to/language/directory/'); +$mail->setLanguage('fr', '/optional/path/to/language/directory/'); ``` ## Documentation diff --git a/changelog.md b/changelog.md index 03d66e7af..33cbaf663 100644 --- a/changelog.md +++ b/changelog.md @@ -1,5 +1,6 @@ # ChangeLog +## Version 5.2.7 () * Add Ukranian translation from @Krezalis * Support for do_verp * Fix bug in CRAM-MD5 AUTH @@ -14,19 +15,26 @@ * Update SyntaxHighlighter * Major overhaul and cleanup of example code * New PHPMailer graphic -* MsgHTML now uses RFC2392-compliant content ids -* Add line break normalization function and use it in MsgHTML +* msgHTML now uses RFC2392-compliant content ids +* Add line break normalization function and use it in msgHTML * Don't set unnecessary reply-to addresses * Make fakesendmail.sh a bit cleaner and safer * Set a content-transfer-encoding on multiparts (fixes msglint error) -* Fix cid generation in MsgHTML (Thanks to @digitalthought) +* Fix cid generation in msgHTML (Thanks to @digitalthought) * Fix handling of multiple SMTP servers (Thanks to @NanoCaiordo) -* SMTP->Connect() now supports stream context options (Thanks to @stanislavdavid) +* SMTP->connect() now supports stream context options (Thanks to @stanislavdavid) * Add support for iCal event alternatives (Thanks to @reblutus) * Update to Polish language file (Thanks to Krzysztof Kowalewski) * Update to Norwegian language file (Thanks to @datagutten) * Update to Hungarian language file (Thanks to @dominicus-75) * Add Persian/Farsi translation from @jaii +* Make SMTPDebug property type match type in SMTP class +* Add unit tests for DKIM +* Major refactor of SMTP class +* Reformat to PSR-2 coding standard +* Introduce autoloader +* Allow overriding of SMTP class +* Overhaul of PHPDocs ## Version 5.2.6 (April 11th 2013) * Reflect move to PHPMailer GitHub organisation at https://github.com/PHPMailer/PHPMailer diff --git a/class.phpmailer.php b/class.phpmailer.php index d5b29fc57..b349eafb4 100644 --- a/class.phpmailer.php +++ b/class.phpmailer.php @@ -1,2959 +1,3239 @@ + * @author Jim Jagielski (jimjag) + * @author Andy Prevost (codeworxtech) + * @author Brent R. Matzelle (original founder) + * @copyright 2013 Marcus Bointon + * @copyright 2010 - 2012 Jim Jagielski + * @copyright 2004 - 2009 Andy Prevost + * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License + * @note This program is distributed in the hope that it will be useful - WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. + */ + +if (version_compare(PHP_VERSION, '5.0.0', '<')) { + exit("Sorry, PHPMailer will only run on PHP version 5 or greater!\n"); +} + +/** + * PHPMailer - PHP email creation and transport class. + * PHP Version 5.0.0 + * @package PHPMailer + * @author Marcus Bointon (coolbru) + * @author Jim Jagielski (jimjag) + * @author Andy Prevost (codeworxtech) + * @author Brent R. Matzelle (original founder) + * @copyright 2013 Marcus Bointon + * @copyright 2010 - 2012 Jim Jagielski + * @copyright 2004 - 2009 Andy Prevost + */ +class PHPMailer +{ + /** + * The PHPMailer Version number. + * @type string + */ + public $Version = '5.2.7'; + + /** + * Email priority. + * Options: 1 = High, 3 = Normal, 5 = low. + * @type int + */ + public $Priority = 3; + + /** + * The character set of the message. + * @type string + */ + public $CharSet = 'iso-8859-1'; + + /** + * The MIME Content-type of the message. + * @type string + */ + public $ContentType = 'text/plain'; + + /** + * The message encoding. + * Options: "8bit", "7bit", "binary", "base64", and "quoted-printable". + * @type string + */ + public $Encoding = '8bit'; + + /** + * Holds the most recent mailer error message. + * @type string + */ + public $ErrorInfo = ''; + + /** + * The From email address for the message. + * @type string + */ + public $From = 'root@localhost'; + + /** + * The From name of the message. + * @type string + */ + public $FromName = 'Root User'; + + /** + * The Sender email (Return-Path) of the message. + * If not empty, will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode. + * @type string + */ + public $Sender = ''; + + /** + * The Return-Path of the message. + * If empty, it will be set to either From or Sender. + * @type string + */ + public $ReturnPath = ''; + + /** + * The Subject of the message. + * @type string + */ + public $Subject = ''; + + /** + * An HTML or plain text message body. + * If HTML then call isHTML(true). + * @type string + */ + public $Body = ''; + + /** + * The plain-text message body. + * This body can be read by mail clients that do not have HTML email + * capability such as mutt & Eudora. + * Clients that can read HTML will view the normal Body. + * @type string + */ + public $AltBody = ''; + + /** + * An iCal message part body. + * Only supported in simple alt or alt_inline message types + * To generate iCal events, use the bundled extras/EasyPeasyICS.php class or iCalcreator + * @link http://sprain.ch/blog/downloads/php-class-easypeasyics-create-ical-files-with-php/ + * @link http://kigkonsult.se/iCalcreator/ + * @type string + */ + public $Ical = ''; + + /** + * The complete compiled MIME message body. + * @access protected + * @type string + */ + protected $MIMEBody = ''; + + /** + * The complete compiled MIME message headers. + * @type string + * @access protected + */ + protected $MIMEHeader = ''; + + /** + * Extra headers that createHeader() doesn't fold in. + * @type string + * @access protected + */ + protected $mailHeader = ''; + + /** + * Word-wrap the message body to this number of chars. + * @type int + */ + public $WordWrap = 0; + + /** + * Which method to use to send mail. + * Options: "mail", "sendmail", or "smtp". + * @type string + */ + public $Mailer = 'mail'; + + /** + * The path to the sendmail program. + * @type string + */ + public $Sendmail = '/usr/sbin/sendmail'; + + /** + * Whether mail() uses a fully sendmail-compatible MTA. + * One which supports sendmail's "-oi -f" options. + * @type bool + */ + public $UseSendmailOptions = true; + + /** + * Path to PHPMailer plugins. + * Useful if the SMTP class is not in the PHP include path. + * @type string + * @deprecated Should not be needed now there is an autoloader. + */ + public $PluginDir = ''; + + /** + * The email address that a reading confirmation should be sent to. + * @type string + */ + public $ConfirmReadingTo = ''; + + /** + * The hostname to use in Message-Id and Received headers + * and as default HELO string. + * If empty, the value returned + * by SERVER_NAME is used or 'localhost.localdomain'. + * @type string + */ + public $Hostname = ''; + + /** + * An ID to be used in the Message-Id header. + * If empty, a unique id will be generated. + * @type string + */ + public $MessageID = ''; + + /** + * The message Date to be used in the Date header. + * If empty, the current date will be added. + * @type string + */ + public $MessageDate = ''; + + /** + * SMTP hosts. + * Either a single hostname or multiple semicolon-delimited hostnames. + * You can also specify a different port + * for each host by using this format: [hostname:port] + * (e.g. "smtp1.example.com:25;smtp2.example.com"). + * Hosts will be tried in order. + * @type string + */ + public $Host = 'localhost'; + + /** + * The default SMTP server port. + * @type int + * @Todo Why is this needed when the SMTP class takes care of it? + */ + public $Port = 25; + + /** + * The SMTP HELO of the message. + * Default is $Hostname. + * @type string + * @see PHPMailer::$Hostname + */ + public $Helo = ''; + + /** + * The secure connection prefix. + * Options: "", "ssl" or "tls" + * @type string + */ + public $SMTPSecure = ''; + + /** + * Whether to use SMTP authentication. + * Uses the Username and Password properties. + * @type bool + * @see PHPMailer::$Username + * @see PHPMailer::$Password + */ + public $SMTPAuth = false; + + /** + * SMTP username. + * @type string + */ + public $Username = ''; + + /** + * SMTP password. + * @type string + */ + public $Password = ''; + + /** + * SMTP auth type. + * Options are LOGIN (default), PLAIN, NTLM, CRAM-MD5 + * @type string + */ + public $AuthType = ''; + + /** + * SMTP realm. + * Used for NTLM auth + * @type string + */ + public $Realm = ''; + + /** + * SMTP workstation. + * Used for NTLM auth + * @type string + */ + public $Workstation = ''; + + /** + * The SMTP server timeout in seconds. + * @type int + */ + public $Timeout = 10; + + /** + * SMTP class debug output mode. + * Options: 0 = off, 1 = commands, 2 = commands and data + * @type int + * @see SMTP::$do_debug + */ + public $SMTPDebug = 0; + + /** + * The function/method to use for debugging output. + * Options: "echo" or "error_log" + * @type string + * @see SMTP::$Debugoutput + */ + public $Debugoutput = "echo"; + + /** + * Whether to keep SMTP connection open after each message. + * If this is set to true then to close the connection + * requires an explicit call to smtpClose(). + * @type bool + */ + public $SMTPKeepAlive = false; + + /** + * Whether to split multiple to addresses into multiple messages + * or send them all in one message. + * @type bool + */ + public $SingleTo = false; + + /** + * Storage for addresses when SingleTo is enabled. + * @type array + * @todo This should really not be public + */ + public $SingleToArray = array(); + + /** + * Whether to generate VERP addresses on send. + * Only applicable when sending via SMTP. + * @link http://en.wikipedia.org/wiki/Variable_envelope_return_path + * @type bool + */ + public $do_verp = false; + + /** + * Whether to allow sending messages with an empty body. + * @type bool + */ + public $AllowEmpty = false; + + /** + * The default line ending. + * @note The default remains "\n". We force CRLF where we know + * it must be used via self::CRLF. + * @type string + */ + public $LE = "\n"; + + /** + * DKIM selector. + * @type string + */ + public $DKIM_selector = ''; + + /** + * DKIM Identity. + * Usually the email address used as the source of the email + * @type string + */ + public $DKIM_identity = ''; + + /** + * DKIM passphrase. + * Used if your key is encrypted. + * @type string + */ + public $DKIM_passphrase = ''; + + /** + * DKIM signing domain name. + * @example 'example.com' + * @type string + */ + public $DKIM_domain = ''; + + /** + * DKIM private key file path. + * @type string + */ + public $DKIM_private = ''; + + /** + * Callback Action function name. + * + * The function that handles the result of the send email action. + * It is called out by send() for each email sent. + * + * Value can be: + * - 'function_name' for function names + * - 'Class::Method' for static method calls + * - array($object, 'Method') for calling methods on $object + * See http://php.net/is_callable manual page for more details. + * + * Parameters: + * bool $result result of the send action + * string $to email address of the recipient + * string $cc cc email addresses + * string $bcc bcc email addresses + * string $subject the subject + * string $body the email body + * string $from email address of sender + * + * @type string + */ + public $action_function = ''; + + /** + * What to use in the X-Mailer header. + * Options: null for default, whitespace for none, or a string to use + * @type string + */ + public $XMailer = ''; + + /** + * An instance of the SMTP sender class. + * @type SMTP + * @access protected + */ + protected $smtp = null; + + /** + * The array of 'to' addresses. + * @type array + * @access protected + */ + protected $to = array(); + + /** + * The array of 'cc' addresses. + * @type array + * @access protected + */ + protected $cc = array(); + + /** + * The array of 'bcc' addresses. + * @type array + * @access protected + */ + protected $bcc = array(); + + /** + * The array of reply-to names and addresses. + * @type array + * @access protected + */ + protected $ReplyTo = array(); + + /** + * An array of all kinds of addresses. + * Includes all of $to, $cc, $bcc, $replyto + * @type array + * @access protected + */ + protected $all_recipients = array(); + + /** + * The array of attachments. + * @type array + * @access protected + */ + protected $attachment = array(); + + /** + * The array of custom headers. + * @type array + * @access protected + */ + protected $CustomHeader = array(); + + /** + * The message's MIME type. + * @type string + * @access protected + */ + protected $message_type = ''; + + /** + * The array of MIME boundary strings. + * @type array + * @access protected + */ + protected $boundary = array(); + + /** + * The array of available languages. + * @type array + * @access protected + */ + protected $language = array(); + + /** + * The number of errors encountered. + * @type integer + * @access protected + */ + protected $error_count = 0; + + /** + * The S/MIME certificate file path. + * @type string + * @access protected + */ + protected $sign_cert_file = ''; + + /** + * The S/MIME key file path. + * @type string + * @access protected + */ + protected $sign_key_file = ''; + + /** + * The S/MIME password for the key. + * Used only if the key is encrypted. + * @type string + * @access protected + */ + protected $sign_key_pass = ''; + + /** + * Whether to throw exceptions for errors. + * @type bool + * @access protected + */ + protected $exceptions = false; + + /** + * Error severity: message only, continue processing + */ + const STOP_MESSAGE = 0; + + /** + * Error severity: message, likely ok to continue processing + */ + const STOP_CONTINUE = 1; + + /** + * Error severity: message, plus full stop, critical error reached + */ + const STOP_CRITICAL = 2; + + /** + * SMTP RFC standard line ending + */ + const CRLF = "\r\n"; + + /** + * Constructor + * @param bool $exceptions Should we throw external exceptions? + */ + public function __construct($exceptions = false) + { + $this->exceptions = ($exceptions == true); + //Make sure our autoloader is loaded + if (!in_array('PHPMailerAutoload', spl_autoload_functions())) { + require 'PHPMailerAutoload.php'; + } + } + + /** + * Destructor. + */ + public function __destruct() + { + if ($this->Mailer == 'smtp') { //close any open SMTP connection nicely + $this->smtpClose(); + } + } + + /** + * Call mail() in a safe_mode-aware fashion. + * Also, unless sendmail_path points to sendmail (or something that + * claims to be sendmail), don't pass params (not a perfect fix, + * but it will do) + * @param string $to To + * @param string $subject Subject + * @param string $body Message Body + * @param string $header Additional Header(s) + * @param string $params Params + * @access private + * @return bool + */ + private function mailPassthru($to, $subject, $body, $header, $params) + { + if (ini_get('safe_mode') || !($this->UseSendmailOptions)) { + $rt = @mail($to, $this->encodeHeader($this->secureHeader($subject)), $body, $header); + } else { + $rt = @mail($to, $this->encodeHeader($this->secureHeader($subject)), $body, $header, $params); + } + return $rt; + } + + /** + * Output debugging info via user-defined method. + * Only if debug output is enabled. + * @see PHPMailer::$Debugoutput + * @see PHPMailer::$SMTPDebug + * @param string $str + */ + protected function edebug($str) + { + if (!$this->SMTPDebug) { + return; + } + switch ($this->Debugoutput) { + case 'error_log': + error_log($str); + break; + case 'html': + //Cleans up output a bit for a better looking display that's HTML-safe + echo htmlentities(preg_replace('/[\r\n]+/', '', $str), ENT_QUOTES, $this->CharSet) . "
\n"; + break; + case 'echo': + default: + //Just echoes exactly what was received + echo $str; + } + } + + /** + * Sets message type to HTML or plain. + * @param bool $ishtml True for HTML mode. + * @return void + */ + public function isHTML($ishtml = true) + { + if ($ishtml) { + $this->ContentType = 'text/html'; + } else { + $this->ContentType = 'text/plain'; + } + } + + /** + * Send messages using SMTP. + * @return void + */ + public function isSMTP() + { + $this->Mailer = 'smtp'; + } + + /** + * Send messages using PHP's mail() function. + * @return void + */ + public function isMail() + { + $this->Mailer = 'mail'; + } + + /** + * Send messages using $Sendmail. + * @return void + */ + public function isSendmail() + { + if (!stristr(ini_get('sendmail_path'), 'sendmail')) { + $this->Sendmail = '/var/qmail/bin/sendmail'; + } + $this->Mailer = 'sendmail'; + } + + /** + * Send messages using qmail. + * @return void + */ + public function isQmail() + { + if (stristr(ini_get('sendmail_path'), 'qmail')) { + $this->Sendmail = '/var/qmail/bin/sendmail'; + } + $this->Mailer = 'sendmail'; + } + + /** + * Add a "To" address. + * @param string $address + * @param string $name + * @return bool true on success, false if address already used + */ + public function addAddress($address, $name = '') + { + return $this->addAnAddress('to', $address, $name); + } + + /** + * Add a "CC" address. + * @note: This function works with the SMTP mailer on win32, not with the "mail" mailer. + * @param string $address + * @param string $name + * @return bool true on success, false if address already used + */ + public function addCC($address, $name = '') + { + return $this->addAnAddress('cc', $address, $name); + } + + /** + * Add a "BCC" address. + * @note: This function works with the SMTP mailer on win32, not with the "mail" mailer. + * @param string $address + * @param string $name + * @return bool true on success, false if address already used + */ + public function addBCC($address, $name = '') + { + return $this->addAnAddress('bcc', $address, $name); + } + + /** + * Add a "Reply-to" address. + * @param string $address + * @param string $name + * @return bool + */ + public function addReplyTo($address, $name = '') + { + return $this->addAnAddress('Reply-To', $address, $name); + } + + /** + * Add an address to one of the recipient arrays. + * Addresses that have been added already return false, but do not throw exceptions + * @param string $kind One of 'to', 'cc', 'bcc', 'ReplyTo' + * @param string $address The email address to send to + * @param string $name + * @throws phpmailerException + * @return bool true on success, false if address already used or invalid in some way + * @access protected + */ + protected function addAnAddress($kind, $address, $name = '') + { + if (!preg_match('/^(to|cc|bcc|Reply-To)$/', $kind)) { + $this->setError($this->lang('Invalid recipient array') . ': ' . $kind); + if ($this->exceptions) { + throw new phpmailerException('Invalid recipient array: ' . $kind); + } + $this->edebug($this->lang('Invalid recipient array') . ': ' . $kind); + return false; + } + $address = trim($address); + $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim + if (!$this->validateAddress($address)) { + $this->setError($this->lang('invalid_address') . ': ' . $address); + if ($this->exceptions) { + throw new phpmailerException($this->lang('invalid_address') . ': ' . $address); + } + $this->edebug($this->lang('invalid_address') . ': ' . $address); + return false; + } + if ($kind != 'Reply-To') { + if (!isset($this->all_recipients[strtolower($address)])) { + array_push($this->$kind, array($address, $name)); + $this->all_recipients[strtolower($address)] = true; + return true; + } + } else { + if (!array_key_exists(strtolower($address), $this->ReplyTo)) { + $this->ReplyTo[strtolower($address)] = array($address, $name); + return true; + } + } + return false; + } + + /** + * Set the From and FromName properties. + * @param string $address + * @param string $name + * @param bool $auto Whether to also set the Sender address, defaults to true + * @throws phpmailerException + * @return bool + */ + public function setFrom($address, $name = '', $auto = true) + { + $address = trim($address); + $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim + if (!$this->validateAddress($address)) { + $this->setError($this->lang('invalid_address') . ': ' . $address); + if ($this->exceptions) { + throw new phpmailerException($this->lang('invalid_address') . ': ' . $address); + } + $this->edebug($this->lang('invalid_address') . ': ' . $address); + return false; + } + $this->From = $address; + $this->FromName = $name; + if ($auto) { + if (empty($this->Sender)) { + $this->Sender = $address; + } + } + return true; + } + + /** + * Check that a string looks like an email address. + * @param string $address The email address to check + * @param string $patternselect A selector for the validation pattern to use : + * 'auto' - pick best one automatically; + * 'pcre8' - use the squiloople.com pattern, requires PCRE > 8.0, PHP >= 5.3.2, 5.2.14; + * 'pcre' - use old PCRE implementation; + * 'php' - use PHP built-in FILTER_VALIDATE_EMAIL; faster, less thorough; + * 'noregex' - super fast, really dumb. + * @return bool + * @static + * @access public + */ + public static function validateAddress($address, $patternselect = 'auto') + { + if ($patternselect == 'auto') { + if (defined( + 'PCRE_VERSION' + ) + ) { //Check this instead of extension_loaded so it works when that function is disabled + if (version_compare(PCRE_VERSION, '8.0') >= 0) { + $patternselect = 'pcre8'; + } else { + $patternselect = 'pcre'; + } + } else { + //Filter_var appeared in PHP 5.2.0 and does not require the PCRE extension + if (version_compare(PHP_VERSION, '5.2.0') >= 0) { + $patternselect = 'php'; + } else { + $patternselect = 'noregex'; + } + } + } + switch ($patternselect) { + case 'pcre8': + /** + * Conforms to RFC5322: Uses *correct* regex on which FILTER_VALIDATE_EMAIL is + * based; So why not use FILTER_VALIDATE_EMAIL? Because it was broken to + * not allow a@b type valid addresses :( + * @link http://squiloople.com/2009/12/20/email-address-validation/ + * @copyright 2009-2010 Michael Rushton + * Feel free to use and redistribute this code. But please keep this copyright notice. + */ + return (bool)preg_match( + '/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)' . + '((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)' . + '(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)' . + '([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*' . + '(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)' . + '(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}' . + '|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:' . + '|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}' . + '|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD', + $address + ); + break; + case 'pcre': + //An older regex that doesn't need a recent PCRE + return (bool)preg_match( + '/^(?!(?>"?(?>\\\[ -~]|[^"])"?){255,})(?!(?>"?(?>\\\[ -~]|[^"])"?){65,}@)(?>' . + '[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*")' . + '(?>\.(?>[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*"))*' . + '@(?>(?![a-z0-9-]{64,})(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>\.(?![a-z0-9-]{64,})' . + '(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)){0,126}|\[(?:(?>IPv6:(?>(?>[a-f0-9]{1,4})(?>:' . + '[a-f0-9]{1,4}){7}|(?!(?:.*[a-f0-9][:\]]){8,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?' . + '::(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?))|(?>(?>IPv6:(?>[a-f0-9]{1,4}(?>:' . + '[a-f0-9]{1,4}){5}:|(?!(?:.*[a-f0-9]:){6,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4})?' . + '::(?>(?:[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4}):)?))?(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}' . + '|[1-9]?[0-9])(?>\.(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}))\])$/isD', + $address + ); + break; + case 'php': + default: + return (bool)filter_var($address, FILTER_VALIDATE_EMAIL); + break; + case 'noregex': + //No PCRE! Do something _very_ approximate! + //Check the address is 3 chars or longer and contains an @ that's not the first or last char + return (strlen($address) >= 3 + and strpos($address, '@') >= 1 + and strpos($address, '@') != strlen($address) - 1); + break; + } + } + + /** + * Create a message and send it. + * Uses the sending method specified by $Mailer. + * Returns false on error - Use the ErrorInfo variable to view description of the error. + * @throws phpmailerException + * @return bool + */ + public function send() + { + try { + if (!$this->preSend()) { + return false; + } + return $this->postSend(); + } catch (phpmailerException $e) { + $this->mailHeader = ''; + $this->setError($e->getMessage()); + if ($this->exceptions) { + throw $e; + } + return false; + } + } + + /** + * Prepare a message for sending. + * @throws phpmailerException + * @return bool + */ + public function preSend() + { + try { + $this->mailHeader = ""; + if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) { + throw new phpmailerException($this->lang('provide_address'), self::STOP_CRITICAL); + } + + // Set whether the message is multipart/alternative + if (!empty($this->AltBody)) { + $this->ContentType = 'multipart/alternative'; + } + + $this->error_count = 0; // reset errors + $this->setMessageType(); + // Refuse to send an empty message unless we are specifically allowing it + if (!$this->AllowEmpty and empty($this->Body)) { + throw new phpmailerException($this->lang('empty_message'), self::STOP_CRITICAL); + } + + $this->MIMEHeader = $this->createHeader(); + $this->MIMEBody = $this->createBody(); + + // To capture the complete message when using mail(), create + // an extra header list which createHeader() doesn't fold in + if ($this->Mailer == 'mail') { + if (count($this->to) > 0) { + $this->mailHeader .= $this->addrAppend("To", $this->to); + } else { + $this->mailHeader .= $this->headerLine("To", "undisclosed-recipients:;"); + } + $this->mailHeader .= $this->headerLine( + 'Subject', + $this->encodeHeader($this->secureHeader(trim($this->Subject))) + ); + } + + // Sign with DKIM if enabled + if (!empty($this->DKIM_domain) + && !empty($this->DKIM_private) + && !empty($this->DKIM_selector) + && !empty($this->DKIM_domain) + && file_exists($this->DKIM_private)) { + $header_dkim = $this->DKIM_Add( + $this->MIMEHeader . $this->mailHeader, + $this->encodeHeader($this->secureHeader($this->Subject)), + $this->MIMEBody + ); + $this->MIMEHeader = rtrim($this->MIMEHeader, "\r\n ") . self::CRLF . + str_replace("\r\n", "\n", $header_dkim) . self::CRLF; + } + return true; + + } catch (phpmailerException $e) { + $this->setError($e->getMessage()); + if ($this->exceptions) { + throw $e; + } + return false; + } + } + + /** + * Actually send a message. + * Send the email via the selected mechanism + * @throws phpmailerException + * @return bool + */ + public function postSend() + { + try { + // Choose the mailer and send through it + switch ($this->Mailer) { + case 'sendmail': + return $this->sendmailSend($this->MIMEHeader, $this->MIMEBody); + case 'smtp': + return $this->smtpSend($this->MIMEHeader, $this->MIMEBody); + case 'mail': + return $this->mailSend($this->MIMEHeader, $this->MIMEBody); + default: + return $this->mailSend($this->MIMEHeader, $this->MIMEBody); + } + } catch (phpmailerException $e) { + $this->setError($e->getMessage()); + if ($this->exceptions) { + throw $e; + } + $this->edebug($e->getMessage() . "\n"); + } + return false; + } + + /** + * Send mail using the $Sendmail program. + * @param string $header The message headers + * @param string $body The message body + * @see PHPMailer::$Sendmail + * @throws phpmailerException + * @access protected + * @return bool + */ + protected function sendmailSend($header, $body) + { + if ($this->Sender != '') { + $sendmail = sprintf("%s -oi -f%s -t", escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender)); + } else { + $sendmail = sprintf("%s -oi -t", escapeshellcmd($this->Sendmail)); + } + if ($this->SingleTo === true) { + foreach ($this->SingleToArray as $val) { + if (!@$mail = popen($sendmail, 'w')) { + throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); + } + fputs($mail, "To: " . $val . "\n"); + fputs($mail, $header); + fputs($mail, $body); + $result = pclose($mail); + // implement call back function if it exists + $isSent = ($result == 0) ? 1 : 0; + $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body, $this->From); + if ($result != 0) { + throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); + } + } + } else { + if (!@$mail = popen($sendmail, 'w')) { + throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); + } + fputs($mail, $header); + fputs($mail, $body); + $result = pclose($mail); + // implement call back function if it exists + $isSent = ($result == 0) ? 1 : 0; + $this->doCallback($isSent, $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From); + if ($result != 0) { + throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); + } + } + return true; + } + + /** + * Send mail using the PHP mail() function. + * @param string $header The message headers + * @param string $body The message body + * @link http://www.php.net/manual/en/book.mail.php + * @throws phpmailerException + * @access protected + * @return bool + */ + protected function mailSend($header, $body) + { + $toArr = array(); + foreach ($this->to as $t) { + $toArr[] = $this->addrFormat($t); + } + $to = implode(', ', $toArr); + + if (empty($this->Sender)) { + $params = " "; + } else { + $params = sprintf("-f%s", $this->Sender); + } + if ($this->Sender != '' and !ini_get('safe_mode')) { + $old_from = ini_get('sendmail_from'); + ini_set('sendmail_from', $this->Sender); + } + $rt = false; + if ($this->SingleTo === true && count($toArr) > 1) { + foreach ($toArr as $val) { + $rt = $this->mailPassthru($val, $this->Subject, $body, $header, $params); + // implement call back function if it exists + $isSent = ($rt == 1) ? 1 : 0; + $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body, $this->From); + } + } else { + $rt = $this->mailPassthru($to, $this->Subject, $body, $header, $params); + // implement call back function if it exists + $isSent = ($rt == 1) ? 1 : 0; + $this->doCallback($isSent, $to, $this->cc, $this->bcc, $this->Subject, $body, $this->From); + } + if (isset($old_from)) { + ini_set('sendmail_from', $old_from); + } + if (!$rt) { + throw new phpmailerException($this->lang('instantiate'), self::STOP_CRITICAL); + } + return true; + } + + /** + * Get an instance to use for SMTP operations. + * Override this function to load your own SMTP implementation + * @return SMTP + */ + public function getSMTPInstance() + { + if (!is_object($this->smtp)) { + $this->smtp = new SMTP; + } + return $this->smtp; + } + + /** + * Send mail via SMTP. + * Returns false if there is a bad MAIL FROM, RCPT, or DATA input. + * Uses the PHPMailerSMTP class by default. + * @see PHPMailer::getSMTPInstance() to use a different class. + * @param string $header The message headers + * @param string $body The message body + * @throws phpmailerException + * @uses SMTP + * @access protected + * @return bool + */ + protected function smtpSend($header, $body) + { + $bad_rcpt = array(); + + if (!$this->smtpConnect()) { + throw new phpmailerException($this->lang('smtp_connect_failed'), self::STOP_CRITICAL); + } + $smtp_from = ($this->Sender == '') ? $this->From : $this->Sender; + if (!$this->smtp->mail($smtp_from)) { + $this->setError($this->lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp->getError())); + throw new phpmailerException($this->ErrorInfo, self::STOP_CRITICAL); + } + + // Attempt to send attach all recipients + foreach ($this->to as $to) { + if (!$this->smtp->recipient($to[0])) { + $bad_rcpt[] = $to[0]; + $isSent = 0; + } else { + $isSent = 1; + } + $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body, $this->From); + } + foreach ($this->cc as $cc) { + if (!$this->smtp->recipient($cc[0])) { + $bad_rcpt[] = $cc[0]; + $isSent = 0; + } else { + $isSent = 1; + } + $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body, $this->From); + } + foreach ($this->bcc as $bcc) { + if (!$this->smtp->recipient($bcc[0])) { + $bad_rcpt[] = $bcc[0]; + $isSent = 0; + } else { + $isSent = 1; + } + $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body, $this->From); + } + + if (count($bad_rcpt) > 0) { //Create error message for any bad addresses + throw new phpmailerException($this->lang('recipients_failed') . implode(', ', $bad_rcpt)); + } + if (!$this->smtp->data($header . $body)) { + throw new phpmailerException($this->lang('data_not_accepted'), self::STOP_CRITICAL); + } + if ($this->SMTPKeepAlive == true) { + $this->smtp->reset(); + } else { + $this->smtp->quit(); + $this->smtp->close(); + } + return true; + } + + /** + * Initiate a connection to an SMTP server. + * Returns false if the operation failed. + * @param array $options An array of options compatible with stream_context_create() + * @uses SMTP + * @access public + * @throws phpmailerException + * @return bool + */ + public function smtpConnect($options = array()) + { + if (is_null($this->smtp)) { + $this->smtp = $this->getSMTPInstance(); + } + + //Already connected? + if ($this->smtp->connected()) { + return true; + } + + $this->smtp->setTimeout($this->Timeout); + $this->smtp->setDebugLevel($this->SMTPDebug); + $this->smtp->setDebugOutput($this->Debugoutput); + $this->smtp->setVerp($this->do_verp); + $tls = ($this->SMTPSecure == 'tls'); + $ssl = ($this->SMTPSecure == 'ssl'); + $hosts = explode(';', $this->Host); + $lastexception = null; + + foreach ($hosts as $hostentry) { + $hostinfo = array(); + $host = $hostentry; + $port = $this->Port; + if (preg_match( + '/^(.+):([0-9]+)$/', + $hostentry, + $hostinfo + ) + ) { //If $hostentry contains 'address:port', override default + $host = $hostinfo[1]; + $port = $hostinfo[2]; + } + if ($this->smtp->connect(($ssl ? 'ssl://' : '') . $host, $port, $this->Timeout, $options)) { + try { + if ($this->Helo) { + $hello = $this->Helo; + } else { + $hello = $this->serverHostname(); + } + $this->smtp->hello($hello); + + if ($tls) { + if (!$this->smtp->startTLS()) { + throw new phpmailerException($this->lang('connect_host')); + } + //We must resend HELO after tls negotiation + $this->smtp->hello($hello); + } + if ($this->SMTPAuth) { + if (!$this->smtp->authenticate( + $this->Username, + $this->Password, + $this->AuthType, + $this->Realm, + $this->Workstation + ) + ) { + throw new phpmailerException($this->lang('authenticate')); + } + } + return true; + } catch (phpmailerException $e) { + $lastexception = $e; + //We must have connected, but then failed TLS or Auth, so close connection nicely + $this->smtp->quit(); + } + } + } + //If we get here, all connection attempts have failed, so close connection hard + $this->smtp->close(); + //As we've caught all exceptions, just report whatever the last one was + if ($this->exceptions and !is_null($lastexception)) { + throw $lastexception; + } + return false; + } + + /** + * Close the active SMTP session if one exists. + * @return void + */ + public function smtpClose() + { + if ($this->smtp !== null) { + if ($this->smtp->connected()) { + $this->smtp->quit(); + $this->smtp->close(); + } + } + } + + /** + * Set the language for error messages. + * Returns false if it cannot load the language file. + * The default language is English. + * @param string $langcode ISO 639-1 2-character language code (e.g. French is "fr") + * @param string $lang_path Path to the language file directory, with trailing separator (slash) + * @return bool + * @access public + */ + public function setLanguage($langcode = 'en', $lang_path = 'language/') + { + //Define full set of translatable strings + $PHPMAILER_LANG = array( + 'authenticate' => 'SMTP Error: Could not authenticate.', + 'connect_host' => 'SMTP Error: Could not connect to SMTP host.', + 'data_not_accepted' => 'SMTP Error: data not accepted.', + 'empty_message' => 'Message body empty', + 'encoding' => 'Unknown encoding: ', + 'execute' => 'Could not execute: ', + 'file_access' => 'Could not access file: ', + 'file_open' => 'File Error: Could not open file: ', + 'from_failed' => 'The following From address failed: ', + 'instantiate' => 'Could not instantiate mail function.', + 'invalid_address' => 'Invalid address', + 'mailer_not_supported' => ' mailer is not supported.', + 'provide_address' => 'You must provide at least one recipient email address.', + 'recipients_failed' => 'SMTP Error: The following recipients failed: ', + 'signing' => 'Signing Error: ', + 'smtp_connect_failed' => 'SMTP connect() failed.', + 'smtp_error' => 'SMTP server error: ', + 'variable_set' => 'Cannot set or reset variable: ' + ); + //Overwrite language-specific strings. + //This way we'll never have missing translations - no more "language string failed to load"! + $l = true; + if ($langcode != 'en') { //There is no English translation file + $l = @include $lang_path . 'phpmailer.lang-' . $langcode . '.php'; + } + $this->language = $PHPMAILER_LANG; + return ($l == true); //Returns false if language not found + } + + /** + * Get the array of strings for the current language. + * @return array + */ + public function getTranslations() + { + return $this->language; + } + + /** + * Create recipient headers. + * @access public + * @param string $type + * @param array $addr An array of recipient, + * where each recipient is a 2-element indexed array with element 0 containing an address + * and element 1 containing a name, like: + * array(array('joe@example.com', 'Joe User'), array('zoe@example.com', 'Zoe User')) + * @return string + */ + public function addrAppend($type, $addr) + { + $addresses = array(); + foreach ($addr as $a) { + $addresses[] = $this->addrFormat($a); + } + return $type . ': ' . implode(', ', $addresses) . $this->LE; + } + + /** + * Format an address for use in a message header. + * @access public + * @param array $addr A 2-element indexed array, element 0 containing an address, element 1 containing a name + * like array('joe@example.com', 'Joe User') + * @return string + */ + public function addrFormat($addr) + { + if (empty($addr[1])) { // No name provided + return $this->secureHeader($addr[0]); + } else { + return $this->encodeHeader($this->secureHeader($addr[1]), 'phrase') . " <" . $this->secureHeader( + $addr[0] + ) . ">"; + } + } + + /** + * Word-wrap message. + * For use with mailers that do not automatically perform wrapping + * and for quoted-printable encoded messages. + * Original written by philippe. + * @param string $message The message to wrap + * @param integer $length The line length to wrap to + * @param bool $qp_mode Whether to run in Quoted-Printable mode + * @access public + * @return string + */ + public function wrapText($message, $length, $qp_mode = false) + { + $soft_break = ($qp_mode) ? sprintf(" =%s", $this->LE) : $this->LE; + // If utf-8 encoding is used, we will need to make sure we don't + // split multibyte characters when we wrap + $is_utf8 = (strtolower($this->CharSet) == "utf-8"); + $lelen = strlen($this->LE); + $crlflen = strlen(self::CRLF); + + $message = $this->fixEOL($message); + if (substr($message, -$lelen) == $this->LE) { + $message = substr($message, 0, -$lelen); + } + + $line = explode($this->LE, $message); // Magic. We know fixEOL uses $LE + $message = ''; + for ($i = 0; $i < count($line); $i++) { + $line_part = explode(' ', $line[$i]); + $buf = ''; + for ($e = 0; $e < count($line_part); $e++) { + $word = $line_part[$e]; + if ($qp_mode and (strlen($word) > $length)) { + $space_left = $length - strlen($buf) - $crlflen; + if ($e != 0) { + if ($space_left > 20) { + $len = $space_left; + if ($is_utf8) { + $len = $this->utf8CharBoundary($word, $len); + } elseif (substr($word, $len - 1, 1) == "=") { + $len--; + } elseif (substr($word, $len - 2, 1) == "=") { + $len -= 2; + } + $part = substr($word, 0, $len); + $word = substr($word, $len); + $buf .= ' ' . $part; + $message .= $buf . sprintf("=%s", self::CRLF); + } else { + $message .= $buf . $soft_break; + } + $buf = ''; + } + while (strlen($word) > 0) { + if ($length <= 0) { + break; + } + $len = $length; + if ($is_utf8) { + $len = $this->utf8CharBoundary($word, $len); + } elseif (substr($word, $len - 1, 1) == "=") { + $len--; + } elseif (substr($word, $len - 2, 1) == "=") { + $len -= 2; + } + $part = substr($word, 0, $len); + $word = substr($word, $len); + + if (strlen($word) > 0) { + $message .= $part . sprintf("=%s", self::CRLF); + } else { + $buf = $part; + } + } + } else { + $buf_o = $buf; + $buf .= ($e == 0) ? $word : (' ' . $word); + + if (strlen($buf) > $length and $buf_o != '') { + $message .= $buf_o . $soft_break; + $buf = $word; + } + } + } + $message .= $buf . self::CRLF; + } + + return $message; + } + + /** + * Find the last character boundary prior to $maxLength in a utf-8 + * quoted (printable) encoded string. + * Original written by Colin Brown. + * @access public + * @param string $encodedText utf-8 QP text + * @param int $maxLength find last character boundary prior to this length + * @return int + */ + public function utf8CharBoundary($encodedText, $maxLength) + { + $foundSplitPos = false; + $lookBack = 3; + while (!$foundSplitPos) { + $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack); + $encodedCharPos = strpos($lastChunk, "="); + if ($encodedCharPos !== false) { + // Found start of encoded character byte within $lookBack block. + // Check the encoded byte value (the 2 chars after the '=') + $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2); + $dec = hexdec($hex); + if ($dec < 128) { // Single byte character. + // If the encoded char was found at pos 0, it will fit + // otherwise reduce maxLength to start of the encoded char + $maxLength = ($encodedCharPos == 0) ? $maxLength : + $maxLength - ($lookBack - $encodedCharPos); + $foundSplitPos = true; + } elseif ($dec >= 192) { // First byte of a multi byte character + // Reduce maxLength to split at start of character + $maxLength = $maxLength - ($lookBack - $encodedCharPos); + $foundSplitPos = true; + } elseif ($dec < 192) { // Middle byte of a multi byte character, look further back + $lookBack += 3; + } + } else { + // No encoded character found + $foundSplitPos = true; + } + } + return $maxLength; + } + + + /** + * Set the body wrapping. + * @access public + * @return void + */ + public function setWordWrap() + { + if ($this->WordWrap < 1) { + return; + } + + switch ($this->message_type) { + case 'alt': + case 'alt_inline': + case 'alt_attach': + case 'alt_inline_attach': + $this->AltBody = $this->wrapText($this->AltBody, $this->WordWrap); + break; + default: + $this->Body = $this->wrapText($this->Body, $this->WordWrap); + break; + } + } + + /** + * Assemble message headers. + * @access public + * @return string The assembled headers + */ + public function createHeader() + { + $result = ''; + + // Set the boundaries + $uniq_id = md5(uniqid(time())); + $this->boundary[1] = 'b1_' . $uniq_id; + $this->boundary[2] = 'b2_' . $uniq_id; + $this->boundary[3] = 'b3_' . $uniq_id; + + if ($this->MessageDate == '') { + $result .= $this->headerLine('Date', self::rfcDate()); + } else { + $result .= $this->headerLine('Date', $this->MessageDate); + } + + if ($this->ReturnPath) { + $result .= $this->headerLine('Return-Path', '<' . trim($this->ReturnPath) . '>'); + } elseif ($this->Sender == '') { + $result .= $this->headerLine('Return-Path', '<' . trim($this->From) . '>'); + } else { + $result .= $this->headerLine('Return-Path', '<' . trim($this->Sender) . '>'); + } + + // To be created automatically by mail() + if ($this->Mailer != 'mail') { + if ($this->SingleTo === true) { + foreach ($this->to as $t) { + $this->SingleToArray[] = $this->addrFormat($t); + } + } else { + if (count($this->to) > 0) { + $result .= $this->addrAppend('To', $this->to); + } elseif (count($this->cc) == 0) { + $result .= $this->headerLine('To', 'undisclosed-recipients:;'); + } + } + } + + $result .= $this->addrAppend('From', array(array(trim($this->From), $this->FromName))); + + // sendmail and mail() extract Cc from the header before sending + if (count($this->cc) > 0) { + $result .= $this->addrAppend('Cc', $this->cc); + } + + // sendmail and mail() extract Bcc from the header before sending + if ((($this->Mailer == 'sendmail') || ($this->Mailer == 'mail')) && (count($this->bcc) > 0)) { + $result .= $this->addrAppend('Bcc', $this->bcc); + } + + if (count($this->ReplyTo) > 0) { + $result .= $this->addrAppend('Reply-To', $this->ReplyTo); + } + + // mail() sets the subject itself + if ($this->Mailer != 'mail') { + $result .= $this->headerLine('Subject', $this->encodeHeader($this->secureHeader($this->Subject))); + } + + if ($this->MessageID != '') { + $result .= $this->headerLine('Message-ID', $this->MessageID); + } else { + $result .= sprintf("Message-ID: <%s@%s>%s", $uniq_id, $this->serverHostname(), $this->LE); + } + $result .= $this->headerLine('X-Priority', $this->Priority); + if ($this->XMailer == '') { + $result .= $this->headerLine( + 'X-Mailer', + 'PHPMailer ' . $this->Version . ' (https://github.com/PHPMailer/PHPMailer/)' + ); + } else { + $myXmailer = trim($this->XMailer); + if ($myXmailer) { + $result .= $this->headerLine('X-Mailer', $myXmailer); + } + } + + if ($this->ConfirmReadingTo != '') { + $result .= $this->headerLine('Disposition-Notification-To', '<' . trim($this->ConfirmReadingTo) . '>'); + } + + // Add custom headers + for ($index = 0; $index < count($this->CustomHeader); $index++) { + $result .= $this->headerLine( + trim($this->CustomHeader[$index][0]), + $this->encodeHeader(trim($this->CustomHeader[$index][1])) + ); + } + if (!$this->sign_key_file) { + $result .= $this->headerLine('MIME-Version', '1.0'); + $result .= $this->getMailMIME(); + } + + return $result; + } + + /** + * Get the message MIME type headers. + * @access public + * @return string + */ + public function getMailMIME() + { + $result = ''; + switch ($this->message_type) { + case 'inline': + $result .= $this->headerLine('Content-Type', 'multipart/related;'); + $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"'); + break; + case 'attach': + case 'inline_attach': + case 'alt_attach': + case 'alt_inline_attach': + $result .= $this->headerLine('Content-Type', 'multipart/mixed;'); + $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"'); + break; + case 'alt': + case 'alt_inline': + $result .= $this->headerLine('Content-Type', 'multipart/alternative;'); + $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"'); + break; + default: + // Catches case 'plain': and case '': + $result .= $this->textLine('Content-Type: ' . $this->ContentType . '; charset=' . $this->CharSet); + break; + } + //RFC1341 part 5 says 7bit is assumed if not specified + if ($this->Encoding != '7bit') { + $result .= $this->headerLine('Content-Transfer-Encoding', $this->Encoding); + } + + if ($this->Mailer != 'mail') { + $result .= $this->LE; + } + + return $result; + } + + /** + * Returns the whole MIME message. + * Includes complete headers and body. + * Only valid post preSend(). + * @see PHPMailer::PreSend() + * @access public + * @return string + */ + public function getSentMIMEMessage() + { + return $this->MIMEHeader . $this->mailHeader . self::CRLF . $this->MIMEBody; + } + + + /** + * Assemble the message body. + * Returns an empty string on failure. + * @access public + * @throws phpmailerException + * @return string The assembled message body + */ + public function createBody() + { + $body = ''; + + if ($this->sign_key_file) { + $body .= $this->getMailMIME() . $this->LE; + } + + $this->setWordWrap(); + + switch ($this->message_type) { + case 'inline': + $body .= $this->getBoundary($this->boundary[1], '', '', ''); + $body .= $this->encodeString($this->Body, $this->Encoding); + $body .= $this->LE . $this->LE; + $body .= $this->attachAll('inline', $this->boundary[1]); + break; + case 'attach': + $body .= $this->getBoundary($this->boundary[1], '', '', ''); + $body .= $this->encodeString($this->Body, $this->Encoding); + $body .= $this->LE . $this->LE; + $body .= $this->attachAll('attachment', $this->boundary[1]); + break; + case 'inline_attach': + $body .= $this->textLine('--' . $this->boundary[1]); + $body .= $this->headerLine('Content-Type', 'multipart/related;'); + $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"'); + $body .= $this->LE; + $body .= $this->getBoundary($this->boundary[2], '', '', ''); + $body .= $this->encodeString($this->Body, $this->Encoding); + $body .= $this->LE . $this->LE; + $body .= $this->attachAll('inline', $this->boundary[2]); + $body .= $this->LE; + $body .= $this->attachAll('attachment', $this->boundary[1]); + break; + case 'alt': + $body .= $this->getBoundary($this->boundary[1], '', 'text/plain', ''); + $body .= $this->encodeString($this->AltBody, $this->Encoding); + $body .= $this->LE . $this->LE; + $body .= $this->getBoundary($this->boundary[1], '', 'text/html', ''); + $body .= $this->encodeString($this->Body, $this->Encoding); + $body .= $this->LE . $this->LE; + if (!empty($this->Ical)) { + $body .= $this->getBoundary($this->boundary[1], '', 'text/calendar; method=REQUEST', ''); + $body .= $this->encodeString($this->Ical, $this->Encoding); + $body .= $this->LE . $this->LE; + } + $body .= $this->endBoundary($this->boundary[1]); + break; + case 'alt_inline': + $body .= $this->getBoundary($this->boundary[1], '', 'text/plain', ''); + $body .= $this->encodeString($this->AltBody, $this->Encoding); + $body .= $this->LE . $this->LE; + $body .= $this->textLine('--' . $this->boundary[1]); + $body .= $this->headerLine('Content-Type', 'multipart/related;'); + $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"'); + $body .= $this->LE; + $body .= $this->getBoundary($this->boundary[2], '', 'text/html', ''); + $body .= $this->encodeString($this->Body, $this->Encoding); + $body .= $this->LE . $this->LE; + $body .= $this->attachAll('inline', $this->boundary[2]); + $body .= $this->LE; + $body .= $this->endBoundary($this->boundary[1]); + break; + case 'alt_attach': + $body .= $this->textLine('--' . $this->boundary[1]); + $body .= $this->headerLine('Content-Type', 'multipart/alternative;'); + $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"'); + $body .= $this->LE; + $body .= $this->getBoundary($this->boundary[2], '', 'text/plain', ''); + $body .= $this->encodeString($this->AltBody, $this->Encoding); + $body .= $this->LE . $this->LE; + $body .= $this->getBoundary($this->boundary[2], '', 'text/html', ''); + $body .= $this->encodeString($this->Body, $this->Encoding); + $body .= $this->LE . $this->LE; + $body .= $this->endBoundary($this->boundary[2]); + $body .= $this->LE; + $body .= $this->attachAll('attachment', $this->boundary[1]); + break; + case 'alt_inline_attach': + $body .= $this->textLine('--' . $this->boundary[1]); + $body .= $this->headerLine('Content-Type', 'multipart/alternative;'); + $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"'); + $body .= $this->LE; + $body .= $this->getBoundary($this->boundary[2], '', 'text/plain', ''); + $body .= $this->encodeString($this->AltBody, $this->Encoding); + $body .= $this->LE . $this->LE; + $body .= $this->textLine('--' . $this->boundary[2]); + $body .= $this->headerLine('Content-Type', 'multipart/related;'); + $body .= $this->textLine("\tboundary=\"" . $this->boundary[3] . '"'); + $body .= $this->LE; + $body .= $this->getBoundary($this->boundary[3], '', 'text/html', ''); + $body .= $this->encodeString($this->Body, $this->Encoding); + $body .= $this->LE . $this->LE; + $body .= $this->attachAll('inline', $this->boundary[3]); + $body .= $this->LE; + $body .= $this->endBoundary($this->boundary[2]); + $body .= $this->LE; + $body .= $this->attachAll('attachment', $this->boundary[1]); + break; + default: + // catch case 'plain' and case '' + $body .= $this->encodeString($this->Body, $this->Encoding); + break; + } + + if ($this->isError()) { + $body = ''; + } elseif ($this->sign_key_file) { + try { + if (!defined('PKCS7_TEXT')) { + throw new phpmailerException($this->lang('signing') . ' OpenSSL extension missing.'); + } + $file = tempnam(sys_get_temp_dir(), 'mail'); + file_put_contents($file, $body); //TODO check this worked + $signed = tempnam(sys_get_temp_dir(), 'signed'); + if (@openssl_pkcs7_sign( + $file, + $signed, + 'file://' . realpath($this->sign_cert_file), + array('file://' . realpath($this->sign_key_file), $this->sign_key_pass), + null + ) + ) { + @unlink($file); + $body = file_get_contents($signed); + @unlink($signed); + } else { + @unlink($file); + @unlink($signed); + throw new phpmailerException($this->lang('signing') . openssl_error_string()); + } + } catch (phpmailerException $e) { + $body = ''; + if ($this->exceptions) { + throw $e; + } + } + } + return $body; + } + + /** + * Return the start of a message boundary. + * @access protected + * @param string $boundary + * @param string $charSet + * @param string $contentType + * @param string $encoding + * @return string + */ + protected function getBoundary($boundary, $charSet, $contentType, $encoding) + { + $result = ''; + if ($charSet == '') { + $charSet = $this->CharSet; + } + if ($contentType == '') { + $contentType = $this->ContentType; + } + if ($encoding == '') { + $encoding = $this->Encoding; + } + $result .= $this->textLine('--' . $boundary); + $result .= sprintf("Content-Type: %s; charset=%s", $contentType, $charSet); + $result .= $this->LE; + $result .= $this->headerLine('Content-Transfer-Encoding', $encoding); + $result .= $this->LE; + + return $result; + } + + /** + * Return the end of a message boundary. + * @access protected + * @param string $boundary + * @return string + */ + protected function endBoundary($boundary) + { + return $this->LE . '--' . $boundary . '--' . $this->LE; + } + + /** + * Set the message type. + * PHPMailer only supports some preset message types, + * not arbitrary MIME structures. + * @access protected + * @return void + */ + protected function setMessageType() + { + $this->message_type = array(); + if ($this->alternativeExists()) { + $this->message_type[] = "alt"; + } + if ($this->inlineImageExists()) { + $this->message_type[] = "inline"; + } + if ($this->attachmentExists()) { + $this->message_type[] = "attach"; + } + $this->message_type = implode("_", $this->message_type); + if ($this->message_type == "") { + $this->message_type = "plain"; + } + } + + /** + * Format a header line. + * @access public + * @param string $name + * @param string $value + * @return string + */ + public function headerLine($name, $value) + { + return $name . ': ' . $value . $this->LE; + } + + /** + * Return a formatted mail line. + * @access public + * @param string $value + * @return string + */ + public function textLine($value) + { + return $value . $this->LE; + } + + /** + * Add an attachment from a path on the filesystem. + * Returns false if the file could not be found or read. + * @param string $path Path to the attachment. + * @param string $name Overrides the attachment name. + * @param string $encoding File encoding (see $Encoding). + * @param string $type File extension (MIME) type. + * @param string $disposition Disposition to use + * @throws phpmailerException + * @return bool + */ + public function addAttachment($path, $name = '', $encoding = 'base64', $type = '', $disposition = 'attachment') + { + try { + if (!@is_file($path)) { + throw new phpmailerException($this->lang('file_access') . $path, self::STOP_CONTINUE); + } + + //If a MIME type is not specified, try to work it out from the file name + if ($type == '') { + $type = self::filenameToType($path); + } + + $filename = basename($path); + if ($name == '') { + $name = $filename; + } + + $this->attachment[] = array( + 0 => $path, + 1 => $filename, + 2 => $name, + 3 => $encoding, + 4 => $type, + 5 => false, // isStringAttachment + 6 => $disposition, + 7 => 0 + ); + + } catch (phpmailerException $e) { + $this->setError($e->getMessage()); + if ($this->exceptions) { + throw $e; + } + $this->edebug($e->getMessage() . "\n"); + return false; + } + return true; + } + + /** + * Return the array of attachments. + * @return array + */ + public function getAttachments() + { + return $this->attachment; + } + + /** + * Attach all file, string, and binary attachments to the message. + * Returns an empty string on failure. + * @access protected + * @param string $disposition_type + * @param string $boundary + * @return string + */ + protected function attachAll($disposition_type, $boundary) + { + // Return text of body + $mime = array(); + $cidUniq = array(); + $incl = array(); + + // Add all attachments + foreach ($this->attachment as $attachment) { + // Check if it is a valid disposition_filter + if ($attachment[6] == $disposition_type) { + // Check for string attachment + $string = ''; + $path = ''; + $bString = $attachment[5]; + if ($bString) { + $string = $attachment[0]; + } else { + $path = $attachment[0]; + } + + $inclhash = md5(serialize($attachment)); + if (in_array($inclhash, $incl)) { + continue; + } + $incl[] = $inclhash; + $name = $attachment[2]; + $encoding = $attachment[3]; + $type = $attachment[4]; + $disposition = $attachment[6]; + $cid = $attachment[7]; + if ($disposition == 'inline' && isset($cidUniq[$cid])) { + continue; + } + $cidUniq[$cid] = true; + + $mime[] = sprintf("--%s%s", $boundary, $this->LE); + $mime[] = sprintf( + "Content-Type: %s; name=\"%s\"%s", + $type, + $this->encodeHeader($this->secureHeader($name)), + $this->LE + ); + $mime[] = sprintf("Content-Transfer-Encoding: %s%s", $encoding, $this->LE); + + if ($disposition == 'inline') { + $mime[] = sprintf("Content-ID: <%s>%s", $cid, $this->LE); + } + + // If a filename contains any of these chars, it should be quoted, + // but not otherwise: RFC2183 & RFC2045 5.1 + // Fixes a warning in IETF's msglint MIME checker + // Allow for bypassing the Content-Disposition header totally + if (!(empty($disposition))) { + if (preg_match('/[ \(\)<>@,;:\\"\/\[\]\?=]/', $name)) { + $mime[] = sprintf( + "Content-Disposition: %s; filename=\"%s\"%s", + $disposition, + $this->encodeHeader($this->secureHeader($name)), + $this->LE . $this->LE + ); + } else { + $mime[] = sprintf( + "Content-Disposition: %s; filename=%s%s", + $disposition, + $this->encodeHeader($this->secureHeader($name)), + $this->LE . $this->LE + ); + } + } else { + $mime[] = $this->LE; + } + + // Encode as string attachment + if ($bString) { + $mime[] = $this->encodeString($string, $encoding); + if ($this->isError()) { + return ''; + } + $mime[] = $this->LE . $this->LE; + } else { + $mime[] = $this->encodeFile($path, $encoding); + if ($this->isError()) { + return ''; + } + $mime[] = $this->LE . $this->LE; + } + } + } + + $mime[] = sprintf("--%s--%s", $boundary, $this->LE); + + return implode("", $mime); + } + + /** + * Encode a file attachment in requested format. + * Returns an empty string on failure. + * @param string $path The full path to the file + * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable' + * @throws phpmailerException + * @see EncodeFile(encodeFile + * @access protected + * @return string + */ + protected function encodeFile($path, $encoding = 'base64') + { + try { + if (!is_readable($path)) { + throw new phpmailerException($this->lang('file_open') . $path, self::STOP_CONTINUE); + } + $magic_quotes = get_magic_quotes_runtime(); + if ($magic_quotes) { + if (version_compare(PHP_VERSION, '5.3.0', '<')) { + set_magic_quotes_runtime(0); + } else { + ini_set('magic_quotes_runtime', 0); + } + } + $file_buffer = file_get_contents($path); + $file_buffer = $this->encodeString($file_buffer, $encoding); + if ($magic_quotes) { + if (version_compare(PHP_VERSION, '5.3.0', '<')) { + set_magic_quotes_runtime($magic_quotes); + } else { + ini_set('magic_quotes_runtime', $magic_quotes); + } + } + return $file_buffer; + } catch (Exception $e) { + $this->setError($e->getMessage()); + return ''; + } + } + + /** + * Encode a string in requested format. + * Returns an empty string on failure. + * @param string $str The text to encode + * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable' + * @access public + * @return string + */ + public function encodeString($str, $encoding = 'base64') + { + $encoded = ''; + switch (strtolower($encoding)) { + case 'base64': + $encoded = chunk_split(base64_encode($str), 76, $this->LE); + break; + case '7bit': + case '8bit': + $encoded = $this->fixEOL($str); + //Make sure it ends with a line break + if (substr($encoded, -(strlen($this->LE))) != $this->LE) { + $encoded .= $this->LE; + } + break; + case 'binary': + $encoded = $str; + break; + case 'quoted-printable': + $encoded = $this->encodeQP($str); + break; + default: + $this->setError($this->lang('encoding') . $encoding); + break; + } + return $encoded; + } + + /** + * Encode a header string optimally. + * Picks shortest of Q, B, quoted-printable or none. + * @access public + * @param string $str + * @param string $position + * @return string + */ + public function encodeHeader($str, $position = 'text') + { + $x = 0; + switch (strtolower($position)) { + case 'phrase': + if (!preg_match('/[\200-\377]/', $str)) { + // Can't use addslashes as we don't know what value has magic_quotes_sybase + $encoded = addcslashes($str, "\0..\37\177\\\""); + if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) { + return ($encoded); + } else { + return ("\"$encoded\""); + } + } + $x = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches); + break; + /** @noinspection PhpMissingBreakStatementInspection */ + case 'comment': + $x = preg_match_all('/[()"]/', $str, $matches); + // Intentional fall-through + case 'text': + default: + $x += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches); + break; + } + + if ($x == 0) { //There are no chars that need encoding + return ($str); + } + + $maxlen = 75 - 7 - strlen($this->CharSet); + // Try to select the encoding which should produce the shortest output + if ($x > strlen($str) / 3) { + //More than a third of the content will need encoding, so B encoding will be most efficient + $encoding = 'B'; + if (function_exists('mb_strlen') && $this->hasMultiBytes($str)) { + // Use a custom function which correctly encodes and wraps long + // multibyte strings without breaking lines within a character + $encoded = $this->base64EncodeWrapMB($str, "\n"); + } else { + $encoded = base64_encode($str); + $maxlen -= $maxlen % 4; + $encoded = trim(chunk_split($encoded, $maxlen, "\n")); + } + } else { + $encoding = 'Q'; + $encoded = $this->encodeQ($str, $position); + $encoded = $this->wrapText($encoded, $maxlen, true); + $encoded = str_replace('=' . self::CRLF, "\n", trim($encoded)); + } + + $encoded = preg_replace('/^(.*)$/m', " =?" . $this->CharSet . "?$encoding?\\1?=", $encoded); + $encoded = trim(str_replace("\n", $this->LE, $encoded)); + + return $encoded; + } + + /** + * Check if a string contains multi-byte characters. + * @access public + * @param string $str multi-byte text to wrap encode + * @return bool + */ + public function hasMultiBytes($str) + { + if (function_exists('mb_strlen')) { + return (strlen($str) > mb_strlen($str, $this->CharSet)); + } else { // Assume no multibytes (we can't handle without mbstring functions anyway) + return false; + } + } + + /** + * Encode and wrap long multibyte strings for mail headers + * without breaking lines within a character. + * Adapted from a function by paravoid at http://uk.php.net/manual/en/function.mb-encode-mimeheader.php + * @access public + * @param string $str multi-byte text to wrap encode + * @param string $lf string to use as linefeed/end-of-line + * @return string + */ + public function base64EncodeWrapMB($str, $lf = null) + { + $start = "=?" . $this->CharSet . "?B?"; + $end = "?="; + $encoded = ""; + if ($lf === null) { + $lf = $this->LE; + } + + $mb_length = mb_strlen($str, $this->CharSet); + // Each line must have length <= 75, including $start and $end + $length = 75 - strlen($start) - strlen($end); + // Average multi-byte ratio + $ratio = $mb_length / strlen($str); + // Base64 has a 4:3 ratio + $avgLength = floor($length * $ratio * .75); + + for ($i = 0; $i < $mb_length; $i += $offset) { + $lookBack = 0; + do { + $offset = $avgLength - $lookBack; + $chunk = mb_substr($str, $i, $offset, $this->CharSet); + $chunk = base64_encode($chunk); + $lookBack++; + } while (strlen($chunk) > $length); + $encoded .= $chunk . $lf; + } + + // Chomp the last linefeed + $encoded = substr($encoded, 0, -strlen($lf)); + return $encoded; + } + + /** + * Encode a string in quoted-printable format. + * According to RFC2045 section 6.7. + * @access public + * @param string $string The text to encode + * @param integer $line_max Number of chars allowed on a line before wrapping + * @return string + * @link PHP version adapted from http://www.php.net/manual/en/function.quoted-printable-decode.php#89417 + */ + public function encodeQP($string, $line_max = 76) + { + if (function_exists('quoted_printable_encode')) { //Use native function if it's available (>= PHP5.3) + return quoted_printable_encode($string); + } + //Fall back to a pure PHP implementation + $string = str_replace( + array('%20', '%0D%0A.', '%0D%0A', '%'), + array(' ', "\r\n=2E", "\r\n", '='), + rawurlencode($string) + ); + $string = preg_replace('/[^\r\n]{' . ($line_max - 3) . '}[^=\r\n]{2}/', "$0=\r\n", $string); + return $string; + } -/** - * PHPMailer - PHP email creation and transport class - * NOTE: Requires PHP version 5 or later - * @package PHPMailer - * @author Andy Prevost - * @author Marcus Bointon - * @author Jim Jagielski - * @copyright 2010 - 2012 Jim Jagielski - * @copyright 2004 - 2009 Andy Prevost - * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License - */ + /** + * Backward compatibility wrapper for an old QP encoding function that was removed. + * @see PHPMailer::encodeQP() + * @access public + * @param string $string + * @param integer $line_max + * @param bool $space_conv + * @return string + * @deprecated Use encodeQP instead. + */ + public function encodeQPphp( + $string, + $line_max = 76, + /** @noinspection PhpUnusedParameterInspection */ $space_conv = false + ) { + return $this->encodeQP($string, $line_max); + } -if (version_compare(PHP_VERSION, '5.0.0', '<') ) { - exit("Sorry, PHPMailer will only run on PHP version 5 or greater!\n"); -} + /** + * Encode a string using Q encoding. + * @link http://tools.ietf.org/html/rfc2047 + * @param string $str the text to encode + * @param string $position Where the text is going to be used, see the RFC for what that means + * @access public + * @return string + */ + public function encodeQ($str, $position = 'text') + { + //There should not be any EOL in the string + $pattern = ''; + $encoded = str_replace(array("\r", "\n"), '', $str); + switch (strtolower($position)) { + case 'phrase': + $pattern = '^A-Za-z0-9!*+\/ -'; + break; + /** @noinspection PhpMissingBreakStatementInspection */ + case 'comment': + $pattern = '\(\)"'; + //intentional fall-through + //for this reason we build the $pattern without including delimiters and [] + case 'text': + default: + //Replace every high ascii, control =, ? and _ characters + //We put \075 (=) as first value to make sure it's the first one + //in being converted, preventing double encode + $pattern = '\075\000-\011\013\014\016-\037\077\137\177-\377' . $pattern; + break; + } + if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) { + foreach (array_unique($matches[0]) as $char) { + $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded); + } + } + //Replace every spaces to _ (more readable than =20) + return str_replace(' ', '_', $encoded); + } -/** - * PHP email creation and transport class - * @package PHPMailer - */ -class PHPMailer { - - ///////////////////////////////////////////////// - // PROPERTIES, PUBLIC - ///////////////////////////////////////////////// - - /** - * Email priority (1 = High, 3 = Normal, 5 = low). - * @var int - */ - public $Priority = 3; - - /** - * Sets the CharSet of the message. - * @var string - */ - public $CharSet = 'iso-8859-1'; - - /** - * Sets the Content-type of the message. - * @var string - */ - public $ContentType = 'text/plain'; - - /** - * Sets the Encoding of the message. Options for this are - * "8bit", "7bit", "binary", "base64", and "quoted-printable". - * @var string - */ - public $Encoding = '8bit'; - - /** - * Holds the most recent mailer error message. - * @var string - */ - public $ErrorInfo = ''; - - /** - * Sets the From email address for the message. - * @var string - */ - public $From = 'root@localhost'; - - /** - * Sets the From name of the message. - * @var string - */ - public $FromName = 'Root User'; - - /** - * Sets the Sender email (Return-Path) of the message. - * If not empty, will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode. - * @var string - */ - public $Sender = ''; - - /** - * Sets the Return-Path of the message. If empty, it will - * be set to either From or Sender. - * @var string - */ - public $ReturnPath = ''; - - /** - * Sets the Subject of the message. - * @var string - */ - public $Subject = ''; - - /** - * An HTML or plain text message body. - * If HTML then call IsHTML(true). - * @var string - */ - public $Body = ''; - - /** - * The plain-text message body. - * This body can be read by mail clients that do not have HTML email - * capability such as mutt & Eudora. - * Clients that can read HTML will view the normal Body. - * @var string - */ - public $AltBody = ''; - - /** - * An iCal message part body - * Only supported in simple alt or alt_inline message types - * To generate iCal events, use the bundled extras/EasyPeasyICS.php class or iCalcreator - * @link http://sprain.ch/blog/downloads/php-class-easypeasyics-create-ical-files-with-php/ - * @link http://kigkonsult.se/iCalcreator/ - * @var string - */ - public $Ical = ''; - - /** - * Stores the complete compiled MIME message body. - * @var string - * @access protected - */ - protected $MIMEBody = ''; - - /** - * Stores the complete compiled MIME message headers. - * @var string - * @access protected - */ - protected $MIMEHeader = ''; - - /** - * Stores the extra header list which CreateHeader() doesn't fold in - * @var string - * @access protected - */ - protected $mailHeader = ''; - - /** - * Sets word wrapping on the body of the message to a given number of - * characters. - * @var int - */ - public $WordWrap = 0; - - /** - * Method to send mail: ("mail", "sendmail", or "smtp"). - * @var string - */ - public $Mailer = 'mail'; - - /** - * Sets the path of the sendmail program. - * @var string - */ - public $Sendmail = '/usr/sbin/sendmail'; - - /** - * Determine if mail() uses a fully sendmail compatible MTA that - * supports sendmail's "-oi -f" options - * @var boolean - */ - public $UseSendmailOptions = true; - - /** - * Path to PHPMailer plugins. Useful if the SMTP class - * is in a different directory than the PHP include path. - * @var string - */ - public $PluginDir = ''; - - /** - * Sets the email address that a reading confirmation will be sent. - * @var string - */ - public $ConfirmReadingTo = ''; - - /** - * Sets the hostname to use in Message-Id and Received headers - * and as default HELO string. If empty, the value returned - * by SERVER_NAME is used or 'localhost.localdomain'. - * @var string - */ - public $Hostname = ''; - - /** - * Sets the message ID to be used in the Message-Id header. - * If empty, a unique id will be generated. - * @var string - */ - public $MessageID = ''; - - /** - * Sets the message Date to be used in the Date header. - * If empty, the current date will be added. - * @var string - */ - public $MessageDate = ''; - - ///////////////////////////////////////////////// - // PROPERTIES FOR SMTP - ///////////////////////////////////////////////// - - /** - * Sets the SMTP hosts. - * - * All hosts must be separated by a - * semicolon. You can also specify a different port - * for each host by using this format: [hostname:port] - * (e.g. "smtp1.example.com:25;smtp2.example.com"). - * Hosts will be tried in order. - * @var string - */ - public $Host = 'localhost'; - - /** - * Sets the default SMTP server port. - * @var int - */ - public $Port = 25; - - /** - * Sets the SMTP HELO of the message (Default is $Hostname). - * @var string - */ - public $Helo = ''; - - /** - * Sets connection prefix. Options are "", "ssl" or "tls" - * @var string - */ - public $SMTPSecure = ''; - - /** - * Sets SMTP authentication. Utilizes the Username and Password variables. - * @var bool - */ - public $SMTPAuth = false; - - /** - * Sets SMTP username. - * @var string - */ - public $Username = ''; - - /** - * Sets SMTP password. - * @var string - */ - public $Password = ''; - - /** - * Sets SMTP auth type. Options are LOGIN | PLAIN | NTLM | CRAM-MD5 (default LOGIN) - * @var string - */ - public $AuthType = ''; - - /** - * Sets SMTP realm. - * @var string - */ - public $Realm = ''; - - /** - * Sets SMTP workstation. - * @var string - */ - public $Workstation = ''; - - /** - * Sets the SMTP server timeout in seconds. - * This function will not work with the win32 version. - * @var int - */ - public $Timeout = 10; - - /** - * Sets SMTP class debugging on or off. - * @var bool - */ - public $SMTPDebug = false; - - /** - * Sets the function/method to use for debugging output. - * Right now we only honor "echo" or "error_log" - * @var string - */ - public $Debugoutput = "echo"; - - /** - * Prevents the SMTP connection from being closed after each mail - * sending. If this is set to true then to close the connection - * requires an explicit call to SmtpClose(). - * @var bool - */ - public $SMTPKeepAlive = false; - - /** - * Provides the ability to have the TO field process individual - * emails, instead of sending to entire TO addresses - * @var bool - */ - public $SingleTo = false; - - /** - * Should we generate VERP addresses when sending via SMTP? - * @link http://en.wikipedia.org/wiki/Variable_envelope_return_path - * @var bool - */ - public $do_verp = false; - - /** - * If SingleTo is true, this provides the array to hold the email addresses - * @var bool - */ - public $SingleToArray = array(); - - /** - * Should we allow sending messages with empty body? - * @var bool - */ - public $AllowEmpty = false; - - /** - * Provides the ability to change the generic line ending - * NOTE: The default remains '\n'. We force CRLF where we KNOW - * it must be used via self::CRLF - * @var string - */ - public $LE = "\n"; - - /** - * Used with DKIM Signing - * required parameter if DKIM is enabled - * - * domain selector example domainkey - * @var string - */ - public $DKIM_selector = ''; - - /** - * Used with DKIM Signing - * required if DKIM is enabled, in format of email address 'you@yourdomain.com' typically used as the source of the email - * @var string - */ - public $DKIM_identity = ''; - - /** - * Used with DKIM Signing - * optional parameter if your private key requires a passphras - * @var string - */ - public $DKIM_passphrase = ''; - - /** - * Used with DKIM Singing - * required if DKIM is enabled, in format of email address 'domain.com' - * @var string - */ - public $DKIM_domain = ''; - - /** - * Used with DKIM Signing - * required if DKIM is enabled, path to private key file - * @var string - */ - public $DKIM_private = ''; - - /** - * Callback Action function name. - * The function that handles the result of the send email action. - * It is called out by Send() for each email sent. - * - * Value can be: - * - 'function_name' for function names - * - 'Class::Method' for static method calls - * - array($object, 'Method') for calling methods on $object - * See http://php.net/is_callable manual page for more details. - * - * Parameters: - * bool $result result of the send action - * string $to email address of the recipient - * string $cc cc email addresses - * string $bcc bcc email addresses - * string $subject the subject - * string $body the email body - * string $from email address of sender - * @var string - */ - public $action_function = ''; //'callbackAction'; - - /** - * Sets the PHPMailer Version number - * @var string - */ - public $Version = '5.2.6'; - - /** - * What to use in the X-Mailer header - * @var string NULL for default, whitespace for None, or actual string to use - */ - public $XMailer = ''; - - ///////////////////////////////////////////////// - // PROPERTIES, PRIVATE AND PROTECTED - ///////////////////////////////////////////////// - - /** - * @var SMTP An instance of the SMTP sender class - * @access protected - */ - protected $smtp = null; - /** - * @var array An array of 'to' addresses - * @access protected - */ - protected $to = array(); - /** - * @var array An array of 'cc' addresses - * @access protected - */ - protected $cc = array(); - /** - * @var array An array of 'bcc' addresses - * @access protected - */ - protected $bcc = array(); - /** - * @var array An array of reply-to name and address - * @access protected - */ - protected $ReplyTo = array(); - /** - * @var array An array of all kinds of addresses: to, cc, bcc, replyto - * @access protected - */ - protected $all_recipients = array(); - /** - * @var array An array of attachments - * @access protected - */ - protected $attachment = array(); - /** - * @var array An array of custom headers - * @access protected - */ - protected $CustomHeader = array(); - /** - * @var string The message's MIME type - * @access protected - */ - protected $message_type = ''; - /** - * @var array An array of MIME boundary strings - * @access protected - */ - protected $boundary = array(); - /** - * @var array An array of available languages - * @access protected - */ - protected $language = array(); - /** - * @var integer The number of errors encountered - * @access protected - */ - protected $error_count = 0; - /** - * @var string The filename of a DKIM certificate file - * @access protected - */ - protected $sign_cert_file = ''; - /** - * @var string The filename of a DKIM key file - * @access protected - */ - protected $sign_key_file = ''; - /** - * @var string The password of a DKIM key - * @access protected - */ - protected $sign_key_pass = ''; - /** - * @var boolean Whether to throw exceptions for errors - * @access protected - */ - protected $exceptions = false; - - ///////////////////////////////////////////////// - // CONSTANTS - ///////////////////////////////////////////////// - - const STOP_MESSAGE = 0; // message only, continue processing - const STOP_CONTINUE = 1; // message?, likely ok to continue processing - const STOP_CRITICAL = 2; // message, plus full stop, critical error reached - const CRLF = "\r\n"; // SMTP RFC specified EOL - - ///////////////////////////////////////////////// - // METHODS, VARIABLES - ///////////////////////////////////////////////// - - /** - * Calls actual mail() function, but in a safe_mode aware fashion - * Also, unless sendmail_path points to sendmail (or something that - * claims to be sendmail), don't pass params (not a perfect fix, - * but it will do) - * @param string $to To - * @param string $subject Subject - * @param string $body Message Body - * @param string $header Additional Header(s) - * @param string $params Params - * @access private - * @return bool - */ - private function mail_passthru($to, $subject, $body, $header, $params) { - if ( ini_get('safe_mode') || !($this->UseSendmailOptions) ) { - $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($subject)), $body, $header); - } else { - $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($subject)), $body, $header, $params); - } - return $rt; - } - - /** - * Outputs debugging info via user-defined method - * @param string $str - */ - protected function edebug($str) { - switch ($this->Debugoutput) { - case 'error_log': - error_log($str); - break; - case 'html': - //Cleans up output a bit for a better looking display that's HTML-safe - echo htmlentities(preg_replace('/[\r\n]+/', '', $str), ENT_QUOTES, $this->CharSet)."
\n"; - break; - case 'echo': - default: - //Just echoes exactly what was received - echo $str; - } - } - - /** - * Constructor - * @param boolean $exceptions Should we throw external exceptions? - */ - public function __construct($exceptions = false) { - $this->exceptions = ($exceptions == true); - } - - /** - * Destructor - */ - public function __destruct() { - if ($this->Mailer == 'smtp') { //Close any open SMTP connection nicely - $this->SmtpClose(); - } - } - - /** - * Sets message type to HTML. - * @param bool $ishtml - * @return void - */ - public function IsHTML($ishtml = true) { - if ($ishtml) { - $this->ContentType = 'text/html'; - } else { - $this->ContentType = 'text/plain'; - } - } - - /** - * Sets Mailer to send message using SMTP. - * @return void - */ - public function IsSMTP() { - $this->Mailer = 'smtp'; - } - - /** - * Sets Mailer to send message using PHP mail() function. - * @return void - */ - public function IsMail() { - $this->Mailer = 'mail'; - } - - /** - * Sets Mailer to send message using the $Sendmail program. - * @return void - */ - public function IsSendmail() { - if (!stristr(ini_get('sendmail_path'), 'sendmail')) { - $this->Sendmail = '/var/qmail/bin/sendmail'; - } - $this->Mailer = 'sendmail'; - } - - /** - * Sets Mailer to send message using the qmail MTA. - * @return void - */ - public function IsQmail() { - if (stristr(ini_get('sendmail_path'), 'qmail')) { - $this->Sendmail = '/var/qmail/bin/sendmail'; - } - $this->Mailer = 'sendmail'; - } - - ///////////////////////////////////////////////// - // METHODS, RECIPIENTS - ///////////////////////////////////////////////// - - /** - * Adds a "To" address. - * @param string $address - * @param string $name - * @return boolean true on success, false if address already used - */ - public function AddAddress($address, $name = '') { - return $this->AddAnAddress('to', $address, $name); - } - - /** - * Adds a "Cc" address. - * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer. - * @param string $address - * @param string $name - * @return boolean true on success, false if address already used - */ - public function AddCC($address, $name = '') { - return $this->AddAnAddress('cc', $address, $name); - } - - /** - * Adds a "Bcc" address. - * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer. - * @param string $address - * @param string $name - * @return boolean true on success, false if address already used - */ - public function AddBCC($address, $name = '') { - return $this->AddAnAddress('bcc', $address, $name); - } - - /** - * Adds a "Reply-to" address. - * @param string $address - * @param string $name - * @return boolean - */ - public function AddReplyTo($address, $name = '') { - return $this->AddAnAddress('Reply-To', $address, $name); - } - - /** - * Adds an address to one of the recipient arrays - * Addresses that have been added already return false, but do not throw exceptions - * @param string $kind One of 'to', 'cc', 'bcc', 'ReplyTo' - * @param string $address The email address to send to - * @param string $name - * @throws phpmailerException - * @return boolean true on success, false if address already used or invalid in some way - * @access protected - */ - protected function AddAnAddress($kind, $address, $name = '') { - if (!preg_match('/^(to|cc|bcc|Reply-To)$/', $kind)) { - $this->SetError($this->Lang('Invalid recipient array').': '.$kind); - if ($this->exceptions) { - throw new phpmailerException('Invalid recipient array: ' . $kind); - } - if ($this->SMTPDebug) { - $this->edebug($this->Lang('Invalid recipient array').': '.$kind); - } - return false; - } - $address = trim($address); - $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim - if (!$this->ValidateAddress($address)) { - $this->SetError($this->Lang('invalid_address').': '. $address); - if ($this->exceptions) { - throw new phpmailerException($this->Lang('invalid_address').': '.$address); - } - if ($this->SMTPDebug) { - $this->edebug($this->Lang('invalid_address').': '.$address); - } - return false; - } - if ($kind != 'Reply-To') { - if (!isset($this->all_recipients[strtolower($address)])) { - array_push($this->$kind, array($address, $name)); - $this->all_recipients[strtolower($address)] = true; + + /** + * Add a string or binary attachment (non-filesystem). + * This method can be used to attach ascii or binary data, + * such as a BLOB record from a database. + * @param string $string String attachment data. + * @param string $filename Name of the attachment. + * @param string $encoding File encoding (see $Encoding). + * @param string $type File extension (MIME) type. + * @param string $disposition Disposition to use + * @return void + */ + public function addStringAttachment( + $string, + $filename, + $encoding = 'base64', + $type = '', + $disposition = 'attachment' + ) { + //If a MIME type is not specified, try to work it out from the file name + if ($type == '') { + $type = self::filenameToType($filename); + } + // Append to $attachment array + $this->attachment[] = array( + 0 => $string, + 1 => $filename, + 2 => basename($filename), + 3 => $encoding, + 4 => $type, + 5 => true, // isStringAttachment + 6 => $disposition, + 7 => 0 + ); + } + + /** + * Add an embedded (inline) attachment from a file. + * This can include images, sounds, and just about any other document type. + * These differ from 'regular' attachmants in that they are intended to be + * displayed inline with the message, not just attached for download. + * This is used in HTML messages that embed the images + * the HTML refers to using the $cid value. + * @param string $path Path to the attachment. + * @param string $cid Content ID of the attachment; Use this to reference + * the content when using an embedded image in HTML. + * @param string $name Overrides the attachment name. + * @param string $encoding File encoding (see $Encoding). + * @param string $type File MIME type. + * @param string $disposition Disposition to use + * @return bool True on successfully adding an attachment + */ + public function addEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = '', $disposition = 'inline') + { + if (!@is_file($path)) { + $this->setError($this->lang('file_access') . $path); + return false; + } + + //If a MIME type is not specified, try to work it out from the file name + if ($type == '') { + $type = self::filenameToType($path); + } + + $filename = basename($path); + if ($name == '') { + $name = $filename; + } + + // Append to $attachment array + $this->attachment[] = array( + 0 => $path, + 1 => $filename, + 2 => $name, + 3 => $encoding, + 4 => $type, + 5 => false, // isStringAttachment + 6 => $disposition, + 7 => $cid + ); return true; - } - } else { - if (!array_key_exists(strtolower($address), $this->ReplyTo)) { - $this->ReplyTo[strtolower($address)] = array($address, $name); - return true; - } - } - return false; -} + } - /** - * Set the From and FromName properties - * @param string $address - * @param string $name - * @param boolean $auto Whether to also set the Sender address, defaults to true - * @throws phpmailerException - * @return boolean - */ - public function SetFrom($address, $name = '', $auto = true) { - $address = trim($address); - $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim - if (!$this->ValidateAddress($address)) { - $this->SetError($this->Lang('invalid_address').': '. $address); - if ($this->exceptions) { - throw new phpmailerException($this->Lang('invalid_address').': '.$address); - } - if ($this->SMTPDebug) { - $this->edebug($this->Lang('invalid_address').': '.$address); - } - return false; - } - $this->From = $address; - $this->FromName = $name; - if ($auto) { - if (empty($this->Sender)) { - $this->Sender = $address; - } - } - return true; - } - - /** - * Check that a string looks roughly like an email address should - * Static so it can be used without instantiation, public so people can overload - * Conforms to RFC5322: Uses *correct* regex on which FILTER_VALIDATE_EMAIL is - * based; So why not use FILTER_VALIDATE_EMAIL? Because it was broken to - * not allow a@b type valid addresses :( - * @link http://squiloople.com/2009/12/20/email-address-validation/ - * @copyright regex Copyright Michael Rushton 2009-10 | http://squiloople.com/ | Feel free to use and redistribute this code. But please keep this copyright notice. - * @param string $address The email address to check - * @return boolean - * @static - * @access public - */ - public static function ValidateAddress($address) { - if (defined('PCRE_VERSION')) { //Check this instead of extension_loaded so it works when that function is disabled - if (version_compare(PCRE_VERSION, '8.0') >= 0) { - return (boolean)preg_match('/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD', $address); - } else { - //Fall back to an older regex that doesn't need a recent PCRE - return (boolean)preg_match('/^(?!(?>"?(?>\\\[ -~]|[^"])"?){255,})(?!(?>"?(?>\\\[ -~]|[^"])"?){65,}@)(?>[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*")(?>\.(?>[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*"))*@(?>(?![a-z0-9-]{64,})(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>\.(?![a-z0-9-]{64,})(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)){0,126}|\[(?:(?>IPv6:(?>(?>[a-f0-9]{1,4})(?>:[a-f0-9]{1,4}){7}|(?!(?:.*[a-f0-9][:\]]){8,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?::(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?))|(?>(?>IPv6:(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){5}:|(?!(?:.*[a-f0-9]:){6,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4})?::(?>(?:[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4}):)?))?(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?>\.(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}))\])$/isD', $address); - } - } else { - //No PCRE! Do something _very_ approximate! - //Check the address is 3 chars or longer and contains an @ that's not the first or last char - return (strlen($address) >= 3 and strpos($address, '@') >= 1 and strpos($address, '@') != strlen($address) - 1); - } - } - - ///////////////////////////////////////////////// - // METHODS, MAIL SENDING - ///////////////////////////////////////////////// - - /** - * Creates message and assigns Mailer. If the message is - * not sent successfully then it returns false. Use the ErrorInfo - * variable to view description of the error. - * @throws phpmailerException - * @return bool - */ - public function Send() { - try { - if(!$this->PreSend()) return false; - return $this->PostSend(); - } catch (phpmailerException $e) { - $this->mailHeader = ''; - $this->SetError($e->getMessage()); - if ($this->exceptions) { - throw $e; - } - return false; - } - } - - /** - * Prep mail by constructing all message entities - * @throws phpmailerException - * @return bool - */ - public function PreSend() { - try { - $this->mailHeader = ""; - if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) { - throw new phpmailerException($this->Lang('provide_address'), self::STOP_CRITICAL); - } - - // Set whether the message is multipart/alternative - if(!empty($this->AltBody)) { - $this->ContentType = 'multipart/alternative'; - } - - $this->error_count = 0; // reset errors - $this->SetMessageType(); - //Refuse to send an empty message unless we are specifically allowing it - if (!$this->AllowEmpty and empty($this->Body)) { - throw new phpmailerException($this->Lang('empty_message'), self::STOP_CRITICAL); - } - - $this->MIMEHeader = $this->CreateHeader(); - $this->MIMEBody = $this->CreateBody(); - - // To capture the complete message when using mail(), create - // an extra header list which CreateHeader() doesn't fold in - if ($this->Mailer == 'mail') { - if (count($this->to) > 0) { - $this->mailHeader .= $this->AddrAppend("To", $this->to); - } else { - $this->mailHeader .= $this->HeaderLine("To", "undisclosed-recipients:;"); - } - $this->mailHeader .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader(trim($this->Subject)))); - } - - // digitally sign with DKIM if enabled - if (!empty($this->DKIM_domain) && !empty($this->DKIM_private) && !empty($this->DKIM_selector) && !empty($this->DKIM_domain) && file_exists($this->DKIM_private)) { - $header_dkim = $this->DKIM_Add($this->MIMEHeader . $this->mailHeader, $this->EncodeHeader($this->SecureHeader($this->Subject)), $this->MIMEBody); - $this->MIMEHeader = str_replace("\r\n", "\n", $header_dkim) . $this->MIMEHeader; - } - - return true; - - } catch (phpmailerException $e) { - $this->SetError($e->getMessage()); - if ($this->exceptions) { - throw $e; - } - return false; - } - } - - /** - * Actual Email transport function - * Send the email via the selected mechanism - * @throws phpmailerException - * @return bool - */ - public function PostSend() { - try { - // Choose the mailer and send through it - switch($this->Mailer) { - case 'sendmail': - return $this->SendmailSend($this->MIMEHeader, $this->MIMEBody); - case 'smtp': - return $this->SmtpSend($this->MIMEHeader, $this->MIMEBody); - case 'mail': - return $this->MailSend($this->MIMEHeader, $this->MIMEBody); - default: - return $this->MailSend($this->MIMEHeader, $this->MIMEBody); - } - } catch (phpmailerException $e) { - $this->SetError($e->getMessage()); - if ($this->exceptions) { - throw $e; - } - if ($this->SMTPDebug) { - $this->edebug($e->getMessage()."\n"); - } - } - return false; - } - - /** - * Sends mail using the $Sendmail program. - * @param string $header The message headers - * @param string $body The message body - * @throws phpmailerException - * @access protected - * @return bool - */ - protected function SendmailSend($header, $body) { - if ($this->Sender != '') { - $sendmail = sprintf("%s -oi -f%s -t", escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender)); - } else { - $sendmail = sprintf("%s -oi -t", escapeshellcmd($this->Sendmail)); - } - if ($this->SingleTo === true) { - foreach ($this->SingleToArray as $val) { - if(!@$mail = popen($sendmail, 'w')) { - throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL); - } - fputs($mail, "To: " . $val . "\n"); - fputs($mail, $header); - fputs($mail, $body); - $result = pclose($mail); - // implement call back function if it exists - $isSent = ($result == 0) ? 1 : 0; - $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body); - if($result != 0) { - throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL); - } - } - } else { - if(!@$mail = popen($sendmail, 'w')) { - throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL); - } - fputs($mail, $header); - fputs($mail, $body); - $result = pclose($mail); - // implement call back function if it exists - $isSent = ($result == 0) ? 1 : 0; - $this->doCallback($isSent, $this->to, $this->cc, $this->bcc, $this->Subject, $body); - if($result != 0) { - throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL); - } - } - return true; - } - - /** - * Sends mail using the PHP mail() function. - * @param string $header The message headers - * @param string $body The message body - * @throws phpmailerException - * @access protected - * @return bool - */ - protected function MailSend($header, $body) { - $toArr = array(); - foreach($this->to as $t) { - $toArr[] = $this->AddrFormat($t); - } - $to = implode(', ', $toArr); - - if (empty($this->Sender)) { - $params = " "; - } else { - $params = sprintf("-f%s", $this->Sender); - } - if ($this->Sender != '' and !ini_get('safe_mode')) { - $old_from = ini_get('sendmail_from'); - ini_set('sendmail_from', $this->Sender); - } - $rt = false; - if ($this->SingleTo === true && count($toArr) > 1) { - foreach ($toArr as $val) { - $rt = $this->mail_passthru($val, $this->Subject, $body, $header, $params); - // implement call back function if it exists - $isSent = ($rt == 1) ? 1 : 0; - $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body); - } - } else { - $rt = $this->mail_passthru($to, $this->Subject, $body, $header, $params); - // implement call back function if it exists - $isSent = ($rt == 1) ? 1 : 0; - $this->doCallback($isSent, $to, $this->cc, $this->bcc, $this->Subject, $body); - } - if (isset($old_from)) { - ini_set('sendmail_from', $old_from); - } - if(!$rt) { - throw new phpmailerException($this->Lang('instantiate'), self::STOP_CRITICAL); - } - return true; - } - - /** - * Sends mail via SMTP using PhpSMTP - * Returns false if there is a bad MAIL FROM, RCPT, or DATA input. - * @param string $header The message headers - * @param string $body The message body - * @throws phpmailerException - * @uses SMTP - * @access protected - * @return bool - */ - protected function SmtpSend($header, $body) { - require_once $this->PluginDir . 'class.smtp.php'; - $bad_rcpt = array(); - - if(!$this->SmtpConnect()) { - throw new phpmailerException($this->Lang('smtp_connect_failed'), self::STOP_CRITICAL); - } - $smtp_from = ($this->Sender == '') ? $this->From : $this->Sender; - if(!$this->smtp->Mail($smtp_from)) { - $this->SetError($this->Lang('from_failed') . $smtp_from . ' : ' .implode(',', $this->smtp->getError())); - throw new phpmailerException($this->ErrorInfo, self::STOP_CRITICAL); - } - - // Attempt to send attach all recipients - foreach($this->to as $to) { - if (!$this->smtp->Recipient($to[0])) { - $bad_rcpt[] = $to[0]; - // implement call back function if it exists - $isSent = 0; - $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body); - } else { - // implement call back function if it exists - $isSent = 1; - $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body); - } - } - foreach($this->cc as $cc) { - if (!$this->smtp->Recipient($cc[0])) { - $bad_rcpt[] = $cc[0]; - // implement call back function if it exists - $isSent = 0; - $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body); - } else { - // implement call back function if it exists - $isSent = 1; - $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body); - } - } - foreach($this->bcc as $bcc) { - if (!$this->smtp->Recipient($bcc[0])) { - $bad_rcpt[] = $bcc[0]; - // implement call back function if it exists - $isSent = 0; - $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body); - } else { - // implement call back function if it exists - $isSent = 1; - $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body); - } - } - - - if (count($bad_rcpt) > 0 ) { //Create error message for any bad addresses - $badaddresses = implode(', ', $bad_rcpt); - throw new phpmailerException($this->Lang('recipients_failed') . $badaddresses); - } - if(!$this->smtp->Data($header . $body)) { - throw new phpmailerException($this->Lang('data_not_accepted'), self::STOP_CRITICAL); - } - if($this->SMTPKeepAlive == true) { - $this->smtp->Reset(); - } else { - $this->smtp->Quit(); - $this->smtp->Close(); - } - return true; - } - - /** - * Initiates a connection to an SMTP server. - * Returns false if the operation failed. - * @param array $options An array of options compatible with stream_context_create() - * @uses SMTP - * @access public - * @throws phpmailerException - * @return bool - */ - public function SmtpConnect($options = array()) { - if(is_null($this->smtp)) { - $this->smtp = new SMTP; - } - - //Already connected? - if ($this->smtp->Connected()) { - return true; - } - - $this->smtp->Timeout = $this->Timeout; - $this->smtp->do_debug = $this->SMTPDebug; - $this->smtp->Debugoutput = $this->Debugoutput; - $this->smtp->do_verp = $this->do_verp; - $index = 0; - $tls = ($this->SMTPSecure == 'tls'); - $ssl = ($this->SMTPSecure == 'ssl'); - $hosts = explode(';', $this->Host); - $lastexception = null; - - foreach ($hosts as $hostentry) { - $hostinfo = array(); - $host = $hostentry; - $port = $this->Port; - if (preg_match('/^(.+):([0-9]+)$/', $hostentry, $hostinfo)) { //If $hostentry contains 'address:port', override default - $host = $hostinfo[1]; - $port = $hostinfo[2]; - } - if ($this->smtp->Connect(($ssl ? 'ssl://':'').$host, $port, $this->Timeout, $options)) { - try { - if ($this->Helo) { - $hello = $this->Helo; - } else { - $hello = $this->ServerHostname(); - } - $this->smtp->Hello($hello); - - if ($tls) { - if (!$this->smtp->StartTLS()) { - throw new phpmailerException($this->Lang('connect_host')); + /** + * Add an embedded stringified attachment. + * This can include images, sounds, and just about any other document type. + * Be sure to set the $type to an image type for images: + * JPEG images use 'image/jpeg', GIF uses 'image/gif', PNG uses 'image/png'. + * @param string $string The attachment binary data. + * @param string $cid Content ID of the attachment; Use this to reference + * the content when using an embedded image in HTML. + * @param string $name + * @param string $encoding File encoding (see $Encoding). + * @param string $type MIME type. + * @param string $disposition Disposition to use + * @return bool True on successfully adding an attachment + */ + public function addStringEmbeddedImage( + $string, + $cid, + $name = '', + $encoding = 'base64', + $type = '', + $disposition = 'inline' + ) { + //If a MIME type is not specified, try to work it out from the name + if ($type == '') { + $type = self::filenameToType($name); + } + + // Append to $attachment array + $this->attachment[] = array( + 0 => $string, + 1 => $name, + 2 => $name, + 3 => $encoding, + 4 => $type, + 5 => true, // isStringAttachment + 6 => $disposition, + 7 => $cid + ); + return true; + } + + /** + * Check if an inline attachment is present. + * @access public + * @return bool + */ + public function inlineImageExists() + { + foreach ($this->attachment as $attachment) { + if ($attachment[6] == 'inline') { + return true; } - //We must resend HELO after tls negotiation - $this->smtp->Hello($hello); - } - if ($this->SMTPAuth) { - if (!$this->smtp->Authenticate($this->Username, $this->Password, $this->AuthType, $this->Realm, $this->Workstation)) { - throw new phpmailerException($this->Lang('authenticate')); + } + return false; + } + + /** + * Check if an attachment (non-inline) is present. + * @return bool + */ + public function attachmentExists() + { + foreach ($this->attachment as $attachment) { + if ($attachment[6] == 'attachment') { + return true; } - } - return true; - } catch (phpmailerException $e) { - $lastexception = $e; - //We must have connected, but then failed TLS or Auth, so close connection nicely - $this->smtp->Quit(); - } - } - } - //If we get here, all connection attempts have failed, so close connection hard - $this->smtp->Close(); - //As we've caught all exceptions, just report whatever the last one was - if ($this->exceptions and !is_null($lastexception)) { - throw $lastexception; - } - return false; - } - - /** - * Closes the active SMTP session if one exists. - * @return void - */ - public function SmtpClose() { - if ($this->smtp !== null) { - if($this->smtp->Connected()) { - $this->smtp->Quit(); - $this->smtp->Close(); - } - } - } - - /** - * Sets the language for all class error messages. - * Returns false if it cannot load the language file. The default language is English. - * @param string $langcode ISO 639-1 2-character language code (e.g. Portuguese: "br") - * @param string $lang_path Path to the language file directory - * @return bool - * @access public - */ - function SetLanguage($langcode = 'en', $lang_path = 'language/') { - //Define full set of translatable strings - $PHPMAILER_LANG = array( - 'authenticate' => 'SMTP Error: Could not authenticate.', - 'connect_host' => 'SMTP Error: Could not connect to SMTP host.', - 'data_not_accepted' => 'SMTP Error: Data not accepted.', - 'empty_message' => 'Message body empty', - 'encoding' => 'Unknown encoding: ', - 'execute' => 'Could not execute: ', - 'file_access' => 'Could not access file: ', - 'file_open' => 'File Error: Could not open file: ', - 'from_failed' => 'The following From address failed: ', - 'instantiate' => 'Could not instantiate mail function.', - 'invalid_address' => 'Invalid address', - 'mailer_not_supported' => ' mailer is not supported.', - 'provide_address' => 'You must provide at least one recipient email address.', - 'recipients_failed' => 'SMTP Error: The following recipients failed: ', - 'signing' => 'Signing Error: ', - 'smtp_connect_failed' => 'SMTP Connect() failed.', - 'smtp_error' => 'SMTP server error: ', - 'variable_set' => 'Cannot set or reset variable: ' - ); - //Overwrite language-specific strings. This way we'll never have missing translations - no more "language string failed to load"! - $l = true; - if ($langcode != 'en') { //There is no English translation file - $l = @include $lang_path.'phpmailer.lang-'.$langcode.'.php'; - } - $this->language = $PHPMAILER_LANG; - return ($l == true); //Returns false if language not found - } - - /** - * Return the current array of language strings - * @return array - */ - public function GetTranslations() { - return $this->language; - } - - ///////////////////////////////////////////////// - // METHODS, MESSAGE CREATION - ///////////////////////////////////////////////// - - /** - * Creates recipient headers. - * @access public - * @param string $type - * @param array $addr - * @return string - */ - public function AddrAppend($type, $addr) { - $addr_str = $type . ': '; - $addresses = array(); - foreach ($addr as $a) { - $addresses[] = $this->AddrFormat($a); - } - $addr_str .= implode(', ', $addresses); - $addr_str .= $this->LE; - - return $addr_str; - } - - /** - * Formats an address correctly. - * @access public - * @param string $addr - * @return string - */ - public function AddrFormat($addr) { - if (empty($addr[1])) { - return $this->SecureHeader($addr[0]); - } else { - return $this->EncodeHeader($this->SecureHeader($addr[1]), 'phrase') . " <" . $this->SecureHeader($addr[0]) . ">"; - } - } - - /** - * Wraps message for use with mailers that do not - * automatically perform wrapping and for quoted-printable. - * Original written by philippe. - * @param string $message The message to wrap - * @param integer $length The line length to wrap to - * @param boolean $qp_mode Whether to run in Quoted-Printable mode - * @access public - * @return string - */ - public function WrapText($message, $length, $qp_mode = false) { - $soft_break = ($qp_mode) ? sprintf(" =%s", $this->LE) : $this->LE; - // If utf-8 encoding is used, we will need to make sure we don't - // split multibyte characters when we wrap - $is_utf8 = (strtolower($this->CharSet) == "utf-8"); - $lelen = strlen($this->LE); - $crlflen = strlen(self::CRLF); - - $message = $this->FixEOL($message); - if (substr($message, -$lelen) == $this->LE) { - $message = substr($message, 0, -$lelen); - } - - $line = explode($this->LE, $message); // Magic. We know FixEOL uses $LE - $message = ''; - for ($i = 0 ;$i < count($line); $i++) { - $line_part = explode(' ', $line[$i]); - $buf = ''; - for ($e = 0; $e $length)) { - $space_left = $length - strlen($buf) - $crlflen; - if ($e != 0) { - if ($space_left > 20) { - $len = $space_left; - if ($is_utf8) { - $len = $this->UTF8CharBoundary($word, $len); - } elseif (substr($word, $len - 1, 1) == "=") { - $len--; - } elseif (substr($word, $len - 2, 1) == "=") { - $len -= 2; - } - $part = substr($word, 0, $len); - $word = substr($word, $len); - $buf .= ' ' . $part; - $message .= $buf . sprintf("=%s", self::CRLF); - } else { - $message .= $buf . $soft_break; + } + return false; + } + + /** + * Check if this message has an alternative body set. + * @return bool + */ + public function alternativeExists() + { + return !empty($this->AltBody); + } + + /** + * Clear all To recipients. + * @return void + */ + public function clearAddresses() + { + foreach ($this->to as $to) { + unset($this->all_recipients[strtolower($to[0])]); + } + $this->to = array(); + } + + /** + * Clear all CC recipients. + * @return void + */ + public function clearCCs() + { + foreach ($this->cc as $cc) { + unset($this->all_recipients[strtolower($cc[0])]); + } + $this->cc = array(); + } + + /** + * Clear all BCC recipients. + * @return void + */ + public function clearBCCs() + { + foreach ($this->bcc as $bcc) { + unset($this->all_recipients[strtolower($bcc[0])]); + } + $this->bcc = array(); + } + + /** + * Clear all ReplyTo recipients. + * @return void + */ + public function clearReplyTos() + { + $this->ReplyTo = array(); + } + + /** + * Clear all recipient types. + * @return void + */ + public function clearAllRecipients() + { + $this->to = array(); + $this->cc = array(); + $this->bcc = array(); + $this->all_recipients = array(); + } + + /** + * Clear all filesystem, string, and binary attachments. + * @return void + */ + public function clearAttachments() + { + $this->attachment = array(); + } + + /** + * Clear all custom headers. + * @return void + */ + public function clearCustomHeaders() + { + $this->CustomHeader = array(); + } + + /** + * Add an error message to the error container. + * @access protected + * @param string $msg + * @return void + */ + protected function setError($msg) + { + $this->error_count++; + if ($this->Mailer == 'smtp' and !is_null($this->smtp)) { + $lasterror = $this->smtp->getError(); + if (!empty($lasterror) and array_key_exists('smtp_msg', $lasterror)) { + $msg .= '

' . $this->lang('smtp_error') . $lasterror['smtp_msg'] . "

\n"; } - $buf = ''; - } - while (strlen($word) > 0) { - if ($length <= 0) { + } + $this->ErrorInfo = $msg; + } + + /** + * Return an RFC 822 formatted date. + * @access public + * @return string + * @static + */ + public static function rfcDate() + { + //Set the time zone to whatever the default is to avoid 500 errors + //Will default to UTC if it's not set properly in php.ini + date_default_timezone_set(@date_default_timezone_get()); + return date('D, j M Y H:i:s O'); + } + + /** + * Get the server hostname. + * Returns 'localhost.localdomain' if unknown. + * @access protected + * @return string + */ + protected function serverHostname() + { + if (!empty($this->Hostname)) { + $result = $this->Hostname; + } elseif (isset($_SERVER['SERVER_NAME'])) { + $result = $_SERVER['SERVER_NAME']; + } else { + $result = 'localhost.localdomain'; + } + + return $result; + } + + /** + * Get an error message in the current language. + * @access protected + * @param string $key + * @return string + */ + protected function lang($key) + { + if (count($this->language) < 1) { + $this->setLanguage('en'); // set the default language + } + + if (isset($this->language[$key])) { + return $this->language[$key]; + } else { + return 'Language string failed to load: ' . $key; + } + } + + /** + * Check if an error occurred. + * @access public + * @return bool True if an error did occur. + */ + public function isError() + { + return ($this->error_count > 0); + } + + /** + * Ensure consistent line endings in a string. + * Changes every end of line from CRLF, CR or LF to $this->LE. + * @access public + * @param string $str String to fixEOL + * @return string + */ + public function fixEOL($str) + { + // Normalise to \n + $nstr = str_replace(array("\r\n", "\r"), "\n", $str); + // Now convert LE as needed + if ($this->LE !== "\n") { + $nstr = str_replace("\n", $this->LE, $nstr); + } + return $nstr; + } + + /** + * Add a custom header. + * $name value can be overloaded to contain + * both header name and value (name:value) + * @access public + * @param string $name Custom header name + * @param string $value Header value + * @return void + */ + public function addCustomHeader($name, $value = null) + { + if ($value === null) { + // Value passed in as name:value + $this->CustomHeader[] = explode(':', $name, 2); + } else { + $this->CustomHeader[] = array($name, $value); + } + } + + /** + * Create a message from an HTML string. + * Automatically makes modifications for inline images and backgrounds + * and creates a plain-text version by converting the HTML. + * Overwrites any existing values in $this->Body and $this->AltBody + * @access public + * @param string $message HTML message string + * @param string $basedir baseline directory for path + * @param bool $advanced Whether to use the advanced HTML to text converter + * @return string $message + */ + public function msgHTML($message, $basedir = '', $advanced = false) + { + preg_match_all("/(src|background)=[\"'](.*)[\"']/Ui", $message, $images); + if (isset($images[2])) { + foreach ($images[2] as $i => $url) { + // do not change urls for absolute images (thanks to corvuscorax) + if (!preg_match('#^[A-z]+://#', $url)) { + $filename = basename($url); + $directory = dirname($url); + if ($directory == '.') { + $directory = ''; + } + $cid = md5($url) . '@phpmailer.0'; //RFC2392 S 2 + if (strlen($basedir) > 1 && substr($basedir, -1) != '/') { + $basedir .= '/'; + } + if (strlen($directory) > 1 && substr($directory, -1) != '/') { + $directory .= '/'; + } + if ($this->addEmbeddedImage( + $basedir . $directory . $filename, + $cid, + $filename, + 'base64', + self::_mime_types(self::mb_pathinfo($filename, PATHINFO_EXTENSION)) + ) + ) { + $message = preg_replace( + "/" . $images[1][$i] . "=[\"']" . preg_quote($url, '/') . "[\"']/Ui", + $images[1][$i] . "=\"cid:" . $cid . "\"", + $message + ); + } + } + } + } + $this->isHTML(true); + if (empty($this->AltBody)) { + $this->AltBody = 'To view this email message, open it in a program that understands HTML!' . "\n\n"; + } + //Convert all message body line breaks to CRLF, makes quoted-printable encoding work much better + $this->Body = $this->normalizeBreaks($message); + $this->AltBody = $this->normalizeBreaks($this->html2text($message, $advanced)); + return $this->Body; + } + + /** + * Convert an HTML string into plain text. + * @param string $html The HTML text to convert + * @param bool $advanced Should this use the more complex html2text converter or just a simple one? + * @return string + */ + public function html2text($html, $advanced = false) + { + if ($advanced) { + require_once 'extras/class.html2text.php'; + $h = new html2text($html); + return $h->get_text(); + } + return html_entity_decode( + trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/si', '', $html))), + ENT_QUOTES, + $this->CharSet + ); + } + + /** + * Get the MIME type for a file extension. + * @param string $ext File extension + * @access public + * @return string MIME type of file. + * @static + */ + public static function _mime_types($ext = '') + { + $mimes = array( + 'xl' => 'application/excel', + 'hqx' => 'application/mac-binhex40', + 'cpt' => 'application/mac-compactpro', + 'bin' => 'application/macbinary', + 'doc' => 'application/msword', + 'word' => 'application/msword', + 'class' => 'application/octet-stream', + 'dll' => 'application/octet-stream', + 'dms' => 'application/octet-stream', + 'exe' => 'application/octet-stream', + 'lha' => 'application/octet-stream', + 'lzh' => 'application/octet-stream', + 'psd' => 'application/octet-stream', + 'sea' => 'application/octet-stream', + 'so' => 'application/octet-stream', + 'oda' => 'application/oda', + 'pdf' => 'application/pdf', + 'ai' => 'application/postscript', + 'eps' => 'application/postscript', + 'ps' => 'application/postscript', + 'smi' => 'application/smil', + 'smil' => 'application/smil', + 'mif' => 'application/vnd.mif', + 'xls' => 'application/vnd.ms-excel', + 'ppt' => 'application/vnd.ms-powerpoint', + 'wbxml' => 'application/vnd.wap.wbxml', + 'wmlc' => 'application/vnd.wap.wmlc', + 'dcr' => 'application/x-director', + 'dir' => 'application/x-director', + 'dxr' => 'application/x-director', + 'dvi' => 'application/x-dvi', + 'gtar' => 'application/x-gtar', + 'php3' => 'application/x-httpd-php', + 'php4' => 'application/x-httpd-php', + 'php' => 'application/x-httpd-php', + 'phtml' => 'application/x-httpd-php', + 'phps' => 'application/x-httpd-php-source', + 'js' => 'application/x-javascript', + 'swf' => 'application/x-shockwave-flash', + 'sit' => 'application/x-stuffit', + 'tar' => 'application/x-tar', + 'tgz' => 'application/x-tar', + 'xht' => 'application/xhtml+xml', + 'xhtml' => 'application/xhtml+xml', + 'zip' => 'application/zip', + 'mid' => 'audio/midi', + 'midi' => 'audio/midi', + 'mp2' => 'audio/mpeg', + 'mp3' => 'audio/mpeg', + 'mpga' => 'audio/mpeg', + 'aif' => 'audio/x-aiff', + 'aifc' => 'audio/x-aiff', + 'aiff' => 'audio/x-aiff', + 'ram' => 'audio/x-pn-realaudio', + 'rm' => 'audio/x-pn-realaudio', + 'rpm' => 'audio/x-pn-realaudio-plugin', + 'ra' => 'audio/x-realaudio', + 'wav' => 'audio/x-wav', + 'bmp' => 'image/bmp', + 'gif' => 'image/gif', + 'jpeg' => 'image/jpeg', + 'jpe' => 'image/jpeg', + 'jpg' => 'image/jpeg', + 'png' => 'image/png', + 'tiff' => 'image/tiff', + 'tif' => 'image/tiff', + 'eml' => 'message/rfc822', + 'css' => 'text/css', + 'html' => 'text/html', + 'htm' => 'text/html', + 'shtml' => 'text/html', + 'log' => 'text/plain', + 'text' => 'text/plain', + 'txt' => 'text/plain', + 'rtx' => 'text/richtext', + 'rtf' => 'text/rtf', + 'xml' => 'text/xml', + 'xsl' => 'text/xml', + 'mpeg' => 'video/mpeg', + 'mpe' => 'video/mpeg', + 'mpg' => 'video/mpeg', + 'mov' => 'video/quicktime', + 'qt' => 'video/quicktime', + 'rv' => 'video/vnd.rn-realvideo', + 'avi' => 'video/x-msvideo', + 'movie' => 'video/x-sgi-movie' + ); + return (!isset($mimes[strtolower($ext)])) ? 'application/octet-stream' : $mimes[strtolower($ext)]; + } + + /** + * Map a file name to a MIME type. + * Defaults to 'application/octet-stream', i.e.. arbitrary binary data. + * @param string $filename A file name or full path, does not need to exist as a file + * @return string + * @static + */ + public static function filenameToType($filename) + { + //In case the path is a URL, strip any query string before getting extension + $qpos = strpos($filename, '?'); + if ($qpos !== false) { + $filename = substr($filename, 0, $qpos); + } + $pathinfo = self::mb_pathinfo($filename); + return self::_mime_types($pathinfo['extension']); + } + + /** + * Multi-byte-safe pathinfo replacement. + * Drop-in replacement for pathinfo(), but multibyte-safe, cross-platform-safe, old-version-safe. + * Works similarly to the one in PHP >= 5.2.0 + * @link http://www.php.net/manual/en/function.pathinfo.php#107461 + * @param string $path A filename or path, does not need to exist as a file + * @param integer|string $options Either a PATHINFO_* constant, + * or a string name to return only the specified piece, allows 'filename' to work on PHP < 5.2 + * @return string|array + * @static + */ + public static function mb_pathinfo($path, $options = null) + { + $ret = array('dirname' => '', 'basename' => '', 'extension' => '', 'filename' => ''); + $m = array(); + preg_match('%^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^\.\\\\/]+?)|))[\\\\/\.]*$%im', $path, $m); + if (array_key_exists(1, $m)) { + $ret['dirname'] = $m[1]; + } + if (array_key_exists(2, $m)) { + $ret['basename'] = $m[2]; + } + if (array_key_exists(5, $m)) { + $ret['extension'] = $m[5]; + } + if (array_key_exists(3, $m)) { + $ret['filename'] = $m[3]; + } + switch ($options) { + case PATHINFO_DIRNAME: + case 'dirname': + return $ret['dirname']; + break; + case PATHINFO_BASENAME: + case 'basename': + return $ret['basename']; + break; + case PATHINFO_EXTENSION: + case 'extension': + return $ret['extension']; break; + case PATHINFO_FILENAME: + case 'filename': + return $ret['filename']; + break; + default: + return $ret; + } + } + + /** + * Set or reset instance properties. + * + * Usage Example: + * $page->set('X-Priority', '3'); + * + * @access public + * @param string $name + * @param mixed $value + * NOTE: will not work with arrays, there are no arrays to set/reset + * @throws phpmailerException + * @return bool + * @todo Should this not be using __set() magic function? + */ + public function set($name, $value = '') + { + try { + if (isset($this->$name)) { + $this->$name = $value; + } else { + throw new phpmailerException($this->lang('variable_set') . $name, self::STOP_CRITICAL); } - $len = $length; - if ($is_utf8) { - $len = $this->UTF8CharBoundary($word, $len); - } elseif (substr($word, $len - 1, 1) == "=") { - $len--; - } elseif (substr($word, $len - 2, 1) == "=") { - $len -= 2; + } catch (Exception $e) { + $this->setError($e->getMessage()); + if ($e->getCode() == self::STOP_CRITICAL) { + return false; } - $part = substr($word, 0, $len); - $word = substr($word, $len); + } + return true; + } + + /** + * Strip newlines to prevent header injection. + * @access public + * @param string $str + * @return string + */ + public function secureHeader($str) + { + return trim(str_replace(array("\r", "\n"), '', $str)); + } - if (strlen($word) > 0) { - $message .= $part . sprintf("=%s", self::CRLF); + /** + * Normalize line breaks in a string. + * Converts UNIX LF, Mac CR and Windows CRLF line breaks into a single line break format. + * Defaults to CRLF (for message bodies) and preserves consecutive breaks. + * @param string $text + * @param string $breaktype What kind of line break to use, defaults to CRLF + * @return string + * @access public + * @static + */ + public static function normalizeBreaks($text, $breaktype = "\r\n") + { + return preg_replace('/(\r\n|\r|\n)/ms', $breaktype, $text); + } + + + /** + * Set the private key file and password for S/MIME signing. + * @access public + * @param string $cert_filename + * @param string $key_filename + * @param string $key_pass Password for private key + */ + public function sign($cert_filename, $key_filename, $key_pass) + { + $this->sign_cert_file = $cert_filename; + $this->sign_key_file = $key_filename; + $this->sign_key_pass = $key_pass; + } + + /** + * Quoted-Printable-encode a DKIM header. + * @access public + * @param string $txt + * @return string + */ + public function DKIM_QP($txt) + { + $line = ''; + for ($i = 0; $i < strlen($txt); $i++) { + $ord = ord($txt[$i]); + if (((0x21 <= $ord) && ($ord <= 0x3A)) || $ord == 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E))) { + $line .= $txt[$i]; } else { - $buf = $part; + $line .= "=" . sprintf("%02X", $ord); } - } - } else { - $buf_o = $buf; - $buf .= ($e == 0) ? $word : (' ' . $word); - - if (strlen($buf) > $length and $buf_o != '') { - $message .= $buf_o . $soft_break; - $buf = $word; - } - } - } - $message .= $buf . self::CRLF; - } - - return $message; - } - - /** - * Finds last character boundary prior to maxLength in a utf-8 - * quoted (printable) encoded string. - * Original written by Colin Brown. - * @access public - * @param string $encodedText utf-8 QP text - * @param int $maxLength find last character boundary prior to this length - * @return int - */ - public function UTF8CharBoundary($encodedText, $maxLength) { - $foundSplitPos = false; - $lookBack = 3; - while (!$foundSplitPos) { - $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack); - $encodedCharPos = strpos($lastChunk, "="); - if ($encodedCharPos !== false) { - // Found start of encoded character byte within $lookBack block. - // Check the encoded byte value (the 2 chars after the '=') - $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2); - $dec = hexdec($hex); - if ($dec < 128) { // Single byte character. - // If the encoded char was found at pos 0, it will fit - // otherwise reduce maxLength to start of the encoded char - $maxLength = ($encodedCharPos == 0) ? $maxLength : - $maxLength - ($lookBack - $encodedCharPos); - $foundSplitPos = true; - } elseif ($dec >= 192) { // First byte of a multi byte character - // Reduce maxLength to split at start of character - $maxLength = $maxLength - ($lookBack - $encodedCharPos); - $foundSplitPos = true; - } elseif ($dec < 192) { // Middle byte of a multi byte character, look further back - $lookBack += 3; - } - } else { - // No encoded character found - $foundSplitPos = true; - } - } - return $maxLength; - } - - - /** - * Set the body wrapping. - * @access public - * @return void - */ - public function SetWordWrap() { - if($this->WordWrap < 1) { - return; - } - - switch($this->message_type) { - case 'alt': - case 'alt_inline': - case 'alt_attach': - case 'alt_inline_attach': - $this->AltBody = $this->WrapText($this->AltBody, $this->WordWrap); - break; - default: - $this->Body = $this->WrapText($this->Body, $this->WordWrap); - break; - } - } - - /** - * Assembles message header. - * @access public - * @return string The assembled header - */ - public function CreateHeader() { - $result = ''; - - // Set the boundaries - $uniq_id = md5(uniqid(time())); - $this->boundary[1] = 'b1_' . $uniq_id; - $this->boundary[2] = 'b2_' . $uniq_id; - $this->boundary[3] = 'b3_' . $uniq_id; - - if ($this->MessageDate == '') { - $result .= $this->HeaderLine('Date', self::RFCDate()); - } else { - $result .= $this->HeaderLine('Date', $this->MessageDate); - } - - if ($this->ReturnPath) { - $result .= $this->HeaderLine('Return-Path', '<'.trim($this->ReturnPath).'>'); - } elseif ($this->Sender == '') { - $result .= $this->HeaderLine('Return-Path', '<'.trim($this->From).'>'); - } else { - $result .= $this->HeaderLine('Return-Path', '<'.trim($this->Sender).'>'); - } - - // To be created automatically by mail() - if($this->Mailer != 'mail') { - if ($this->SingleTo === true) { - foreach($this->to as $t) { - $this->SingleToArray[] = $this->AddrFormat($t); - } - } else { - if(count($this->to) > 0) { - $result .= $this->AddrAppend('To', $this->to); - } elseif (count($this->cc) == 0) { - $result .= $this->HeaderLine('To', 'undisclosed-recipients:;'); - } - } - } - - $from = array(); - $from[0][0] = trim($this->From); - $from[0][1] = $this->FromName; - $result .= $this->AddrAppend('From', $from); - - // sendmail and mail() extract Cc from the header before sending - if(count($this->cc) > 0) { - $result .= $this->AddrAppend('Cc', $this->cc); - } - - // sendmail and mail() extract Bcc from the header before sending - if((($this->Mailer == 'sendmail') || ($this->Mailer == 'mail')) && (count($this->bcc) > 0)) { - $result .= $this->AddrAppend('Bcc', $this->bcc); - } - - if(count($this->ReplyTo) > 0) { - $result .= $this->AddrAppend('Reply-To', $this->ReplyTo); - } - - // mail() sets the subject itself - if($this->Mailer != 'mail') { - $result .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader($this->Subject))); - } - - if($this->MessageID != '') { - $result .= $this->HeaderLine('Message-ID', $this->MessageID); - } else { - $result .= sprintf("Message-ID: <%s@%s>%s", $uniq_id, $this->ServerHostname(), $this->LE); - } - $result .= $this->HeaderLine('X-Priority', $this->Priority); - if ($this->XMailer == '') { - $result .= $this->HeaderLine('X-Mailer', 'PHPMailer '.$this->Version.' (https://github.com/PHPMailer/PHPMailer/)'); - } else { - $myXmailer = trim($this->XMailer); - if ($myXmailer) { - $result .= $this->HeaderLine('X-Mailer', $myXmailer); - } - } - - if($this->ConfirmReadingTo != '') { - $result .= $this->HeaderLine('Disposition-Notification-To', '<' . trim($this->ConfirmReadingTo) . '>'); - } - - // Add custom headers - for($index = 0; $index < count($this->CustomHeader); $index++) { - $result .= $this->HeaderLine(trim($this->CustomHeader[$index][0]), $this->EncodeHeader(trim($this->CustomHeader[$index][1]))); - } - if (!$this->sign_key_file) { - $result .= $this->HeaderLine('MIME-Version', '1.0'); - $result .= $this->GetMailMIME(); - } - - return $result; - } - - /** - * Returns the message MIME. - * @access public - * @return string - */ - public function GetMailMIME() { - $result = ''; - switch($this->message_type) { - case 'inline': - $result .= $this->HeaderLine('Content-Type', 'multipart/related;'); - $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1].'"'); - break; - case 'attach': - case 'inline_attach': - case 'alt_attach': - case 'alt_inline_attach': - $result .= $this->HeaderLine('Content-Type', 'multipart/mixed;'); - $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1].'"'); - break; - case 'alt': - case 'alt_inline': - $result .= $this->HeaderLine('Content-Type', 'multipart/alternative;'); - $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1].'"'); - break; - default: - // Catches case 'plain': and case '': - $result .= $this->TextLine('Content-Type: '.$this->ContentType.'; charset='.$this->CharSet); - break; - } - //RFC1341 part 5 says 7bit is assumed if not specified - if ($this->Encoding != '7bit') { - $result .= $this->HeaderLine('Content-Transfer-Encoding', $this->Encoding); - } - - if($this->Mailer != 'mail') { - $result .= $this->LE; - } - - return $result; - } - - /** - * Returns the MIME message (headers and body). Only really valid post PreSend(). - * @access public - * @return string - */ - public function GetSentMIMEMessage() { - return $this->MIMEHeader . $this->mailHeader . self::CRLF . $this->MIMEBody; - } - - - /** - * Assembles the message body. Returns an empty string on failure. - * @access public - * @throws phpmailerException - * @return string The assembled message body - */ - public function CreateBody() { - $body = ''; - - if ($this->sign_key_file) { - $body .= $this->GetMailMIME().$this->LE; - } - - $this->SetWordWrap(); - - switch($this->message_type) { - case 'inline': - $body .= $this->GetBoundary($this->boundary[1], '', '', ''); - $body .= $this->EncodeString($this->Body, $this->Encoding); - $body .= $this->LE.$this->LE; - $body .= $this->AttachAll('inline', $this->boundary[1]); - break; - case 'attach': - $body .= $this->GetBoundary($this->boundary[1], '', '', ''); - $body .= $this->EncodeString($this->Body, $this->Encoding); - $body .= $this->LE.$this->LE; - $body .= $this->AttachAll('attachment', $this->boundary[1]); - break; - case 'inline_attach': - $body .= $this->TextLine('--' . $this->boundary[1]); - $body .= $this->HeaderLine('Content-Type', 'multipart/related;'); - $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2].'"'); - $body .= $this->LE; - $body .= $this->GetBoundary($this->boundary[2], '', '', ''); - $body .= $this->EncodeString($this->Body, $this->Encoding); - $body .= $this->LE.$this->LE; - $body .= $this->AttachAll('inline', $this->boundary[2]); - $body .= $this->LE; - $body .= $this->AttachAll('attachment', $this->boundary[1]); - break; - case 'alt': - $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', ''); - $body .= $this->EncodeString($this->AltBody, $this->Encoding); - $body .= $this->LE.$this->LE; - $body .= $this->GetBoundary($this->boundary[1], '', 'text/html', ''); - $body .= $this->EncodeString($this->Body, $this->Encoding); - $body .= $this->LE.$this->LE; - if(!empty($this->Ical)) { - $body .= $this->GetBoundary($this->boundary[1], '', 'text/calendar; method=REQUEST', ''); - $body .= $this->EncodeString($this->Ical, $this->Encoding); - $body .= $this->LE.$this->LE; - } - $body .= $this->EndBoundary($this->boundary[1]); - break; - case 'alt_inline': - $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', ''); - $body .= $this->EncodeString($this->AltBody, $this->Encoding); - $body .= $this->LE.$this->LE; - $body .= $this->TextLine('--' . $this->boundary[1]); - $body .= $this->HeaderLine('Content-Type', 'multipart/related;'); - $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2].'"'); - $body .= $this->LE; - $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', ''); - $body .= $this->EncodeString($this->Body, $this->Encoding); - $body .= $this->LE.$this->LE; - $body .= $this->AttachAll('inline', $this->boundary[2]); - $body .= $this->LE; - $body .= $this->EndBoundary($this->boundary[1]); - break; - case 'alt_attach': - $body .= $this->TextLine('--' . $this->boundary[1]); - $body .= $this->HeaderLine('Content-Type', 'multipart/alternative;'); - $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2].'"'); - $body .= $this->LE; - $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', ''); - $body .= $this->EncodeString($this->AltBody, $this->Encoding); - $body .= $this->LE.$this->LE; - $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', ''); - $body .= $this->EncodeString($this->Body, $this->Encoding); - $body .= $this->LE.$this->LE; - $body .= $this->EndBoundary($this->boundary[2]); - $body .= $this->LE; - $body .= $this->AttachAll('attachment', $this->boundary[1]); - break; - case 'alt_inline_attach': - $body .= $this->TextLine('--' . $this->boundary[1]); - $body .= $this->HeaderLine('Content-Type', 'multipart/alternative;'); - $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2].'"'); - $body .= $this->LE; - $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', ''); - $body .= $this->EncodeString($this->AltBody, $this->Encoding); - $body .= $this->LE.$this->LE; - $body .= $this->TextLine('--' . $this->boundary[2]); - $body .= $this->HeaderLine('Content-Type', 'multipart/related;'); - $body .= $this->TextLine("\tboundary=\"" . $this->boundary[3].'"'); - $body .= $this->LE; - $body .= $this->GetBoundary($this->boundary[3], '', 'text/html', ''); - $body .= $this->EncodeString($this->Body, $this->Encoding); - $body .= $this->LE.$this->LE; - $body .= $this->AttachAll('inline', $this->boundary[3]); - $body .= $this->LE; - $body .= $this->EndBoundary($this->boundary[2]); - $body .= $this->LE; - $body .= $this->AttachAll('attachment', $this->boundary[1]); - break; - default: - // catch case 'plain' and case '' - $body .= $this->EncodeString($this->Body, $this->Encoding); - break; - } - - if ($this->IsError()) { - $body = ''; - } elseif ($this->sign_key_file) { - try { + } + return $line; + } + + /** + * Generate a DKIM signature. + * @access public + * @param string $s Header + * @throws phpmailerException + * @return string + */ + public function DKIM_Sign($s) + { if (!defined('PKCS7_TEXT')) { - throw new phpmailerException($this->Lang('signing').' OpenSSL extension missing.'); - } - $file = tempnam(sys_get_temp_dir(), 'mail'); - file_put_contents($file, $body); //TODO check this worked - $signed = tempnam(sys_get_temp_dir(), 'signed'); - if (@openssl_pkcs7_sign($file, $signed, 'file://'.realpath($this->sign_cert_file), array('file://'.realpath($this->sign_key_file), $this->sign_key_pass), null)) { - @unlink($file); - $body = file_get_contents($signed); - @unlink($signed); - } else { - @unlink($file); - @unlink($signed); - throw new phpmailerException($this->Lang('signing').openssl_error_string()); + if ($this->exceptions) { + throw new phpmailerException($this->lang("signing") . ' OpenSSL extension missing.'); + } + return ''; } - } catch (phpmailerException $e) { - $body = ''; - if ($this->exceptions) { - throw $e; - } - } - } - return $body; - } - - /** - * Returns the start of a message boundary. - * @access protected - * @param string $boundary - * @param string $charSet - * @param string $contentType - * @param string $encoding - * @return string - */ - protected function GetBoundary($boundary, $charSet, $contentType, $encoding) { - $result = ''; - if($charSet == '') { - $charSet = $this->CharSet; - } - if($contentType == '') { - $contentType = $this->ContentType; - } - if($encoding == '') { - $encoding = $this->Encoding; - } - $result .= $this->TextLine('--' . $boundary); - $result .= sprintf("Content-Type: %s; charset=%s", $contentType, $charSet); - $result .= $this->LE; - $result .= $this->HeaderLine('Content-Transfer-Encoding', $encoding); - $result .= $this->LE; - - return $result; - } - - /** - * Returns the end of a message boundary. - * @access protected - * @param string $boundary - * @return string - */ - protected function EndBoundary($boundary) { - return $this->LE . '--' . $boundary . '--' . $this->LE; - } - - /** - * Sets the message type. - * @access protected - * @return void - */ - protected function SetMessageType() { - $this->message_type = array(); - if($this->AlternativeExists()) $this->message_type[] = "alt"; - if($this->InlineImageExists()) $this->message_type[] = "inline"; - if($this->AttachmentExists()) $this->message_type[] = "attach"; - $this->message_type = implode("_", $this->message_type); - if($this->message_type == "") $this->message_type = "plain"; - } - - /** - * Returns a formatted header line. - * @access public - * @param string $name - * @param string $value - * @return string - */ - public function HeaderLine($name, $value) { - return $name . ': ' . $value . $this->LE; - } - - /** - * Returns a formatted mail line. - * @access public - * @param string $value - * @return string - */ - public function TextLine($value) { - return $value . $this->LE; - } - - ///////////////////////////////////////////////// - // CLASS METHODS, ATTACHMENTS - ///////////////////////////////////////////////// - - /** - * Adds an attachment from a path on the filesystem. - * Returns false if the file could not be found - * or accessed. - * @param string $path Path to the attachment. - * @param string $name Overrides the attachment name. - * @param string $encoding File encoding (see $Encoding). - * @param string $type File extension (MIME) type. - * @param string $disposition Disposition to use - * @throws phpmailerException - * @return bool - */ - public function AddAttachment($path, $name = '', $encoding = 'base64', $type = '', $disposition = 'attachment') { - try { - if ( !@is_file($path) ) { - throw new phpmailerException($this->Lang('file_access') . $path, self::STOP_CONTINUE); - } - - //If a MIME type is not specified, try to work it out from the file name - if ($type == '') { - $type = self::filenameToType($path); - } - - $filename = basename($path); - if ( $name == '' ) { - $name = $filename; - } - - $this->attachment[] = array( - 0 => $path, - 1 => $filename, - 2 => $name, - 3 => $encoding, - 4 => $type, - 5 => false, // isStringAttachment - 6 => $disposition, - 7 => 0 - ); - - } catch (phpmailerException $e) { - $this->SetError($e->getMessage()); - if ($this->exceptions) { - throw $e; - } - if ($this->SMTPDebug) { - $this->edebug($e->getMessage()."\n"); - } - return false; - } - return true; - } - - /** - * Return the current array of attachments - * @return array - */ - public function GetAttachments() { - return $this->attachment; - } - - /** - * Attaches all fs, string, and binary attachments to the message. - * Returns an empty string on failure. - * @access protected - * @param string $disposition_type - * @param string $boundary - * @return string - */ - protected function AttachAll($disposition_type, $boundary) { - // Return text of body - $mime = array(); - $cidUniq = array(); - $incl = array(); - - // Add all attachments - foreach ($this->attachment as $attachment) { - // CHECK IF IT IS A VALID DISPOSITION_FILTER - if($attachment[6] == $disposition_type) { - // Check for string attachment - $string = ''; - $path = ''; - $bString = $attachment[5]; - if ($bString) { - $string = $attachment[0]; + $privKeyStr = file_get_contents($this->DKIM_private); + if ($this->DKIM_passphrase != '') { + $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase); } else { - $path = $attachment[0]; - } - - $inclhash = md5(serialize($attachment)); - if (in_array($inclhash, $incl)) { continue; } - $incl[] = $inclhash; - $filename = $attachment[1]; - $name = $attachment[2]; - $encoding = $attachment[3]; - $type = $attachment[4]; - $disposition = $attachment[6]; - $cid = $attachment[7]; - if ( $disposition == 'inline' && isset($cidUniq[$cid]) ) { continue; } - $cidUniq[$cid] = true; - - $mime[] = sprintf("--%s%s", $boundary, $this->LE); - $mime[] = sprintf("Content-Type: %s; name=\"%s\"%s", $type, $this->EncodeHeader($this->SecureHeader($name)), $this->LE); - $mime[] = sprintf("Content-Transfer-Encoding: %s%s", $encoding, $this->LE); - - if($disposition == 'inline') { - $mime[] = sprintf("Content-ID: <%s>%s", $cid, $this->LE); - } - - //If a filename contains any of these chars, it should be quoted, but not otherwise: RFC2183 & RFC2045 5.1 - //Fixes a warning in IETF's msglint MIME checker - // - // Allow for bypassing the Content-Disposition header totally - if (!(empty($disposition))) { - if (preg_match('/[ \(\)<>@,;:\\"\/\[\]\?=]/', $name)) { - $mime[] = sprintf("Content-Disposition: %s; filename=\"%s\"%s", $disposition, $this->EncodeHeader($this->SecureHeader($name)), $this->LE.$this->LE); - } else { - $mime[] = sprintf("Content-Disposition: %s; filename=%s%s", $disposition, $this->EncodeHeader($this->SecureHeader($name)), $this->LE.$this->LE); - } - } else { - $mime[] = $this->LE; + $privKey = $privKeyStr; + } + if (openssl_sign($s, $signature, $privKey)) { + return base64_encode($signature); } + return ''; + } - // Encode as string attachment - if($bString) { - $mime[] = $this->EncodeString($string, $encoding); - if($this->IsError()) { - return ''; - } - $mime[] = $this->LE.$this->LE; - } else { - $mime[] = $this->EncodeFile($path, $encoding); - if($this->IsError()) { - return ''; - } - $mime[] = $this->LE.$this->LE; - } - } - } - - $mime[] = sprintf("--%s--%s", $boundary, $this->LE); - - return implode("", $mime); - } - - /** - * Encodes attachment in requested format. - * Returns an empty string on failure. - * @param string $path The full path to the file - * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable' - * @throws phpmailerException - * @see EncodeFile() - * @access protected - * @return string - */ - protected function EncodeFile($path, $encoding = 'base64') { - try { - if (!is_readable($path)) { - throw new phpmailerException($this->Lang('file_open') . $path, self::STOP_CONTINUE); - } - $magic_quotes = get_magic_quotes_runtime(); - if ($magic_quotes) { - if (version_compare(PHP_VERSION, '5.3.0', '<')) { - set_magic_quotes_runtime(0); - } else { - ini_set('magic_quotes_runtime', 0); - } - } - $file_buffer = file_get_contents($path); - $file_buffer = $this->EncodeString($file_buffer, $encoding); - if ($magic_quotes) { - if (version_compare(PHP_VERSION, '5.3.0', '<')) { - set_magic_quotes_runtime($magic_quotes); - } else { - ini_set('magic_quotes_runtime', $magic_quotes); - } - } - return $file_buffer; - } catch (Exception $e) { - $this->SetError($e->getMessage()); - return ''; - } - } - - /** - * Encodes string to requested format. - * Returns an empty string on failure. - * @param string $str The text to encode - * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable' - * @access public - * @return string - */ - public function EncodeString($str, $encoding = 'base64') { - $encoded = ''; - switch(strtolower($encoding)) { - case 'base64': - $encoded = chunk_split(base64_encode($str), 76, $this->LE); - break; - case '7bit': - case '8bit': - $encoded = $this->FixEOL($str); - //Make sure it ends with a line break - if (substr($encoded, -(strlen($this->LE))) != $this->LE) - $encoded .= $this->LE; - break; - case 'binary': - $encoded = $str; - break; - case 'quoted-printable': - $encoded = $this->EncodeQP($str); - break; - default: - $this->SetError($this->Lang('encoding') . $encoding); - break; - } - return $encoded; - } - - /** - * Encode a header string to best (shortest) of Q, B, quoted or none. - * @access public - * @param string $str - * @param string $position - * @return string - */ - public function EncodeHeader($str, $position = 'text') { - $x = 0; - - switch (strtolower($position)) { - case 'phrase': - if (!preg_match('/[\200-\377]/', $str)) { - // Can't use addslashes as we don't know what value has magic_quotes_sybase - $encoded = addcslashes($str, "\0..\37\177\\\""); - if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) { - return ($encoded); - } else { - return ("\"$encoded\""); - } - } - $x = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches); - break; - case 'comment': - $x = preg_match_all('/[()"]/', $str, $matches); - // Fall-through - case 'text': - default: - $x += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches); - break; - } - - if ($x == 0) { //There are no chars that need encoding - return ($str); - } - - $maxlen = 75 - 7 - strlen($this->CharSet); - // Try to select the encoding which should produce the shortest output - if ($x > strlen($str)/3) { //More than a third of the content will need encoding, so B encoding will be most efficient - $encoding = 'B'; - if (function_exists('mb_strlen') && $this->HasMultiBytes($str)) { - // Use a custom function which correctly encodes and wraps long - // multibyte strings without breaking lines within a character - $encoded = $this->Base64EncodeWrapMB($str, "\n"); - } else { - $encoded = base64_encode($str); - $maxlen -= $maxlen % 4; - $encoded = trim(chunk_split($encoded, $maxlen, "\n")); - } - } else { - $encoding = 'Q'; - $encoded = $this->EncodeQ($str, $position); - $encoded = $this->WrapText($encoded, $maxlen, true); - $encoded = str_replace('='.self::CRLF, "\n", trim($encoded)); - } - - $encoded = preg_replace('/^(.*)$/m', " =?".$this->CharSet."?$encoding?\\1?=", $encoded); - $encoded = trim(str_replace("\n", $this->LE, $encoded)); - - return $encoded; - } - - /** - * Checks if a string contains multibyte characters. - * @access public - * @param string $str multi-byte text to wrap encode - * @return bool - */ - public function HasMultiBytes($str) { - if (function_exists('mb_strlen')) { - return (strlen($str) > mb_strlen($str, $this->CharSet)); - } else { // Assume no multibytes (we can't handle without mbstring functions anyway) - return false; - } - } - - /** - * Correctly encodes and wraps long multibyte strings for mail headers - * without breaking lines within a character. - * Adapted from a function by paravoid at http://uk.php.net/manual/en/function.mb-encode-mimeheader.php - * @access public - * @param string $str multi-byte text to wrap encode - * @param string $lf string to use as linefeed/end-of-line - * @return string - */ - public function Base64EncodeWrapMB($str, $lf=null) { - $start = "=?".$this->CharSet."?B?"; - $end = "?="; - $encoded = ""; - if ($lf === null) { - $lf = $this->LE; - } - - $mb_length = mb_strlen($str, $this->CharSet); - // Each line must have length <= 75, including $start and $end - $length = 75 - strlen($start) - strlen($end); - // Average multi-byte ratio - $ratio = $mb_length / strlen($str); - // Base64 has a 4:3 ratio - $offset = $avgLength = floor($length * $ratio * .75); - - for ($i = 0; $i < $mb_length; $i += $offset) { - $lookBack = 0; - - do { - $offset = $avgLength - $lookBack; - $chunk = mb_substr($str, $i, $offset, $this->CharSet); - $chunk = base64_encode($chunk); - $lookBack++; - } - while (strlen($chunk) > $length); - - $encoded .= $chunk . $lf; - } - - // Chomp the last linefeed - $encoded = substr($encoded, 0, -strlen($lf)); - return $encoded; - } - - /** - * Encode string to RFC2045 (6.7) quoted-printable format - * @access public - * @param string $string The text to encode - * @param integer $line_max Number of chars allowed on a line before wrapping - * @return string - * @link PHP version adapted from http://www.php.net/manual/en/function.quoted-printable-decode.php#89417 - */ - public function EncodeQP($string, $line_max = 76) { - if (function_exists('quoted_printable_encode')) { //Use native function if it's available (>= PHP5.3) - return quoted_printable_encode($string); - } - //Fall back to a pure PHP implementation - $string = str_replace(array('%20', '%0D%0A.', '%0D%0A', '%'), array(' ', "\r\n=2E", "\r\n", '='), rawurlencode($string)); - $string = preg_replace('/[^\r\n]{'.($line_max - 3).'}[^=\r\n]{2}/', "$0=\r\n", $string); - return $string; - } - - /** - * Wrapper to preserve BC for old QP encoding function that was removed - * @see EncodeQP() - * @access public - * @param string $string - * @param integer $line_max - * @param bool $space_conv - * @return string - */ - public function EncodeQPphp($string, $line_max = 76, $space_conv = false) { - return $this->EncodeQP($string, $line_max); - } - - /** - * Encode string to q encoding. - * @link http://tools.ietf.org/html/rfc2047 - * @param string $str the text to encode - * @param string $position Where the text is going to be used, see the RFC for what that means - * @access public - * @return string - */ - public function EncodeQ($str, $position = 'text') { - //There should not be any EOL in the string - $pattern = ''; - $encoded = str_replace(array("\r", "\n"), '', $str); - switch (strtolower($position)) { - case 'phrase': - $pattern = '^A-Za-z0-9!*+\/ -'; - break; - - case 'comment': - $pattern = '\(\)"'; - //note that we don't break here! - //for this reason we build the $pattern without including delimiters and [] - - case 'text': - default: - //Replace every high ascii, control =, ? and _ characters - //We put \075 (=) as first value to make sure it's the first one in being converted, preventing double encode - $pattern = '\075\000-\011\013\014\016-\037\077\137\177-\377' . $pattern; - break; - } - - if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) { - foreach (array_unique($matches[0]) as $char) { - $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded); - } - } - - //Replace every spaces to _ (more readable than =20) - return str_replace(' ', '_', $encoded); -} + /** + * Generate a DKIM canonicalization header. + * @access public + * @param string $s Header + * @return string + */ + public function DKIM_HeaderC($s) + { + $s = preg_replace("/\r\n\s+/", " ", $s); + $lines = explode("\r\n", $s); + foreach ($lines as $key => $line) { + list($heading, $value) = explode(":", $line, 2); + $heading = strtolower($heading); + $value = preg_replace("/\s+/", " ", $value); // Compress useless spaces + $lines[$key] = $heading . ":" . trim($value); // Don't forget to remove WSP around the value + } + $s = implode("\r\n", $lines); + return $s; + } + /** + * Generate a DKIM canonicalization body. + * @access public + * @param string $body Message Body + * @return string + */ + public function DKIM_BodyC($body) + { + if ($body == '') { + return "\r\n"; + } + // stabilize line endings + $body = str_replace("\r\n", "\n", $body); + $body = str_replace("\n", "\r\n", $body); + // END stabilize line endings + while (substr($body, strlen($body) - 4, 4) == "\r\n\r\n") { + $body = substr($body, 0, strlen($body) - 2); + } + return $body; + } - /** - * Adds a string or binary attachment (non-filesystem) to the list. - * This method can be used to attach ascii or binary data, - * such as a BLOB record from a database. - * @param string $string String attachment data. - * @param string $filename Name of the attachment. - * @param string $encoding File encoding (see $Encoding). - * @param string $type File extension (MIME) type. - * @param string $disposition Disposition to use - * @return void - */ - public function AddStringAttachment($string, $filename, $encoding = 'base64', $type = '', $disposition = 'attachment') { - //If a MIME type is not specified, try to work it out from the file name - if ($type == '') { - $type = self::filenameToType($filename); - } - // Append to $attachment array - $this->attachment[] = array( - 0 => $string, - 1 => $filename, - 2 => basename($filename), - 3 => $encoding, - 4 => $type, - 5 => true, // isStringAttachment - 6 => $disposition, - 7 => 0 - ); - } - - /** - * Add an embedded attachment from a file. - * This can include images, sounds, and just about any other document type. - * @param string $path Path to the attachment. - * @param string $cid Content ID of the attachment; Use this to reference - * the content when using an embedded image in HTML. - * @param string $name Overrides the attachment name. - * @param string $encoding File encoding (see $Encoding). - * @param string $type File MIME type. - * @param string $disposition Disposition to use - * @return bool True on successfully adding an attachment - */ - public function AddEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = '', $disposition = 'inline') { - if ( !@is_file($path) ) { - $this->SetError($this->Lang('file_access') . $path); - return false; - } - - //If a MIME type is not specified, try to work it out from the file name - if ($type == '') { - $type = self::filenameToType($path); - } - - $filename = basename($path); - if ( $name == '' ) { - $name = $filename; - } - - // Append to $attachment array - $this->attachment[] = array( - 0 => $path, - 1 => $filename, - 2 => $name, - 3 => $encoding, - 4 => $type, - 5 => false, // isStringAttachment - 6 => $disposition, - 7 => $cid - ); - return true; - } - - - /** - * Add an embedded stringified attachment. - * This can include images, sounds, and just about any other document type. - * Be sure to set the $type to an image type for images: - * JPEG images use 'image/jpeg', GIF uses 'image/gif', PNG uses 'image/png'. - * @param string $string The attachment binary data. - * @param string $cid Content ID of the attachment; Use this to reference - * the content when using an embedded image in HTML. - * @param string $name - * @param string $encoding File encoding (see $Encoding). - * @param string $type MIME type. - * @param string $disposition Disposition to use - * @return bool True on successfully adding an attachment - */ - public function AddStringEmbeddedImage($string, $cid, $name = '', $encoding = 'base64', $type = '', $disposition = 'inline') { - //If a MIME type is not specified, try to work it out from the name - if ($type == '') { - $type = self::filenameToType($name); - } - - // Append to $attachment array - $this->attachment[] = array( - 0 => $string, - 1 => $name, - 2 => $name, - 3 => $encoding, - 4 => $type, - 5 => true, // isStringAttachment - 6 => $disposition, - 7 => $cid - ); - return true; - } - - /** - * Returns true if an inline attachment is present. - * @access public - * @return bool - */ - public function InlineImageExists() { - foreach($this->attachment as $attachment) { - if ($attachment[6] == 'inline') { - return true; - } - } - return false; - } - - /** - * Returns true if an attachment (non-inline) is present. - * @return bool - */ - public function AttachmentExists() { - foreach($this->attachment as $attachment) { - if ($attachment[6] == 'attachment') { - return true; - } - } - return false; - } - - /** - * Does this message have an alternative body set? - * @return bool - */ - public function AlternativeExists() { - return !empty($this->AltBody); - } - - ///////////////////////////////////////////////// - // CLASS METHODS, MESSAGE RESET - ///////////////////////////////////////////////// - - /** - * Clears all recipients assigned in the TO array. Returns void. - * @return void - */ - public function ClearAddresses() { - foreach($this->to as $to) { - unset($this->all_recipients[strtolower($to[0])]); - } - $this->to = array(); - } - - /** - * Clears all recipients assigned in the CC array. Returns void. - * @return void - */ - public function ClearCCs() { - foreach($this->cc as $cc) { - unset($this->all_recipients[strtolower($cc[0])]); - } - $this->cc = array(); - } - - /** - * Clears all recipients assigned in the BCC array. Returns void. - * @return void - */ - public function ClearBCCs() { - foreach($this->bcc as $bcc) { - unset($this->all_recipients[strtolower($bcc[0])]); - } - $this->bcc = array(); - } - - /** - * Clears all recipients assigned in the ReplyTo array. Returns void. - * @return void - */ - public function ClearReplyTos() { - $this->ReplyTo = array(); - } - - /** - * Clears all recipients assigned in the TO, CC and BCC - * array. Returns void. - * @return void - */ - public function ClearAllRecipients() { - $this->to = array(); - $this->cc = array(); - $this->bcc = array(); - $this->all_recipients = array(); - } - - /** - * Clears all previously set filesystem, string, and binary - * attachments. Returns void. - * @return void - */ - public function ClearAttachments() { - $this->attachment = array(); - } - - /** - * Clears all custom headers. Returns void. - * @return void - */ - public function ClearCustomHeaders() { - $this->CustomHeader = array(); - } - - ///////////////////////////////////////////////// - // CLASS METHODS, MISCELLANEOUS - ///////////////////////////////////////////////// - - /** - * Adds the error message to the error container. - * @access protected - * @param string $msg - * @return void - */ - protected function SetError($msg) { - $this->error_count++; - if ($this->Mailer == 'smtp' and !is_null($this->smtp)) { - $lasterror = $this->smtp->getError(); - if (!empty($lasterror) and array_key_exists('smtp_msg', $lasterror)) { - $msg .= '

' . $this->Lang('smtp_error') . $lasterror['smtp_msg'] . "

\n"; - } - } - $this->ErrorInfo = $msg; - } - - /** - * Returns the proper RFC 822 formatted date. - * @access public - * @return string - * @static - */ - public static function RFCDate() { - //Set the time zone to whatever the default is to avoid 500 errors - //Will default to UTC if it's not set properly in php.ini - date_default_timezone_set(@date_default_timezone_get()); - return date('D, j M Y H:i:s O'); - } - - /** - * Returns the server hostname or 'localhost.localdomain' if unknown. - * @access protected - * @return string - */ - protected function ServerHostname() { - if (!empty($this->Hostname)) { - $result = $this->Hostname; - } elseif (isset($_SERVER['SERVER_NAME'])) { - $result = $_SERVER['SERVER_NAME']; - } else { - $result = 'localhost.localdomain'; - } - - return $result; - } - - /** - * Returns a message in the appropriate language. - * @access protected - * @param string $key - * @return string - */ - protected function Lang($key) { - if(count($this->language) < 1) { - $this->SetLanguage('en'); // set the default language - } - - if(isset($this->language[$key])) { - return $this->language[$key]; - } else { - return 'Language string failed to load: ' . $key; - } - } - - /** - * Returns true if an error occurred. - * @access public - * @return bool - */ - public function IsError() { - return ($this->error_count > 0); - } - - /** - * Changes every end of line from CRLF, CR or LF to $this->LE. - * @access public - * @param string $str String to FixEOL - * @return string - */ - public function FixEOL($str) { - // condense down to \n - $nstr = str_replace(array("\r\n", "\r"), "\n", $str); - // Now convert LE as needed - if ($this->LE !== "\n") { - $nstr = str_replace("\n", $this->LE, $nstr); - } - return $nstr; - } - - /** - * Adds a custom header. $name value can be overloaded to contain - * both header name and value (name:value) - * @access public - * @param string $name custom header name - * @param string $value header value - * @return void - */ - public function AddCustomHeader($name, $value=null) { - if ($value === null) { - // Value passed in as name:value - $this->CustomHeader[] = explode(':', $name, 2); - } else { - $this->CustomHeader[] = array($name, $value); - } - } - - /** - * Creates a message from an HTML string, making modifications for inline images and backgrounds - * and creates a plain-text version by converting the HTML - * Overwrites any existing values in $this->Body and $this->AltBody - * @access public - * @param string $message HTML message string - * @param string $basedir baseline directory for path - * @param bool $advanced Whether to use the advanced HTML to text converter - * @return string $message - */ - public function MsgHTML($message, $basedir = '', $advanced = false) { - preg_match_all("/(src|background)=[\"'](.*)[\"']/Ui", $message, $images); - if (isset($images[2])) { - foreach ($images[2] as $i => $url) { - // do not change urls for absolute images (thanks to corvuscorax) - if (!preg_match('#^[A-z]+://#', $url)) { - $filename = basename($url); - $directory = dirname($url); - if ($directory == '.') { - $directory = ''; - } - $cid = md5($url).'@phpmailer.0'; //RFC2392 S 2 - if (strlen($basedir) > 1 && substr($basedir, -1) != '/') { - $basedir .= '/'; - } - if (strlen($directory) > 1 && substr($directory, -1) != '/') { - $directory .= '/'; - } - if ($this->AddEmbeddedImage($basedir.$directory.$filename, $cid, $filename, 'base64', self::_mime_types(self::mb_pathinfo($filename, PATHINFO_EXTENSION)))) { - $message = preg_replace("/".$images[1][$i]."=[\"']".preg_quote($url, '/')."[\"']/Ui", $images[1][$i]."=\"cid:".$cid."\"", $message); - } - } - } - } - $this->IsHTML(true); - if (empty($this->AltBody)) { - $this->AltBody = 'To view this email message, open it in a program that understands HTML!' . "\n\n"; - } - //Convert all message body line breaks to CRLF, makes quoted-printable encoding work much better - $this->Body = $this->NormalizeBreaks($message); - $this->AltBody = $this->NormalizeBreaks($this->html2text($message, $advanced)); - return $this->Body; - } - - /** - * Convert an HTML string into a plain text version - * @param string $html The HTML text to convert - * @param bool $advanced Should this use the more complex html2text converter or just a simple one? + /** + * Create the DKIM header and body in a new message header. + * @access public + * @param string $headers_line Header lines + * @param string $subject Subject + * @param string $body Body * @return string */ - public function html2text($html, $advanced = false) { - if ($advanced) { - require_once 'extras/class.html2text.php'; - $h = new html2text($html); - return $h->get_text(); - } - return html_entity_decode(trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/si', '', $html))), ENT_QUOTES, $this->CharSet); - } - - /** - * Gets the MIME type of the embedded or inline image - * @param string $ext File extension - * @access public - * @return string MIME type of ext - * @static - */ - public static function _mime_types($ext = '') { - $mimes = array( - 'xl' => 'application/excel', - 'hqx' => 'application/mac-binhex40', - 'cpt' => 'application/mac-compactpro', - 'bin' => 'application/macbinary', - 'doc' => 'application/msword', - 'word' => 'application/msword', - 'class' => 'application/octet-stream', - 'dll' => 'application/octet-stream', - 'dms' => 'application/octet-stream', - 'exe' => 'application/octet-stream', - 'lha' => 'application/octet-stream', - 'lzh' => 'application/octet-stream', - 'psd' => 'application/octet-stream', - 'sea' => 'application/octet-stream', - 'so' => 'application/octet-stream', - 'oda' => 'application/oda', - 'pdf' => 'application/pdf', - 'ai' => 'application/postscript', - 'eps' => 'application/postscript', - 'ps' => 'application/postscript', - 'smi' => 'application/smil', - 'smil' => 'application/smil', - 'mif' => 'application/vnd.mif', - 'xls' => 'application/vnd.ms-excel', - 'ppt' => 'application/vnd.ms-powerpoint', - 'wbxml' => 'application/vnd.wap.wbxml', - 'wmlc' => 'application/vnd.wap.wmlc', - 'dcr' => 'application/x-director', - 'dir' => 'application/x-director', - 'dxr' => 'application/x-director', - 'dvi' => 'application/x-dvi', - 'gtar' => 'application/x-gtar', - 'php3' => 'application/x-httpd-php', - 'php4' => 'application/x-httpd-php', - 'php' => 'application/x-httpd-php', - 'phtml' => 'application/x-httpd-php', - 'phps' => 'application/x-httpd-php-source', - 'js' => 'application/x-javascript', - 'swf' => 'application/x-shockwave-flash', - 'sit' => 'application/x-stuffit', - 'tar' => 'application/x-tar', - 'tgz' => 'application/x-tar', - 'xht' => 'application/xhtml+xml', - 'xhtml' => 'application/xhtml+xml', - 'zip' => 'application/zip', - 'mid' => 'audio/midi', - 'midi' => 'audio/midi', - 'mp2' => 'audio/mpeg', - 'mp3' => 'audio/mpeg', - 'mpga' => 'audio/mpeg', - 'aif' => 'audio/x-aiff', - 'aifc' => 'audio/x-aiff', - 'aiff' => 'audio/x-aiff', - 'ram' => 'audio/x-pn-realaudio', - 'rm' => 'audio/x-pn-realaudio', - 'rpm' => 'audio/x-pn-realaudio-plugin', - 'ra' => 'audio/x-realaudio', - 'wav' => 'audio/x-wav', - 'bmp' => 'image/bmp', - 'gif' => 'image/gif', - 'jpeg' => 'image/jpeg', - 'jpe' => 'image/jpeg', - 'jpg' => 'image/jpeg', - 'png' => 'image/png', - 'tiff' => 'image/tiff', - 'tif' => 'image/tiff', - 'eml' => 'message/rfc822', - 'css' => 'text/css', - 'html' => 'text/html', - 'htm' => 'text/html', - 'shtml' => 'text/html', - 'log' => 'text/plain', - 'text' => 'text/plain', - 'txt' => 'text/plain', - 'rtx' => 'text/richtext', - 'rtf' => 'text/rtf', - 'xml' => 'text/xml', - 'xsl' => 'text/xml', - 'mpeg' => 'video/mpeg', - 'mpe' => 'video/mpeg', - 'mpg' => 'video/mpeg', - 'mov' => 'video/quicktime', - 'qt' => 'video/quicktime', - 'rv' => 'video/vnd.rn-realvideo', - 'avi' => 'video/x-msvideo', - 'movie' => 'video/x-sgi-movie' - ); - return (!isset($mimes[strtolower($ext)])) ? 'application/octet-stream' : $mimes[strtolower($ext)]; - } - - /** - * Try to map a file name to a MIME type, default to application/octet-stream - * @param string $filename A file name or full path, does not need to exist as a file - * @return string - * @static - */ - public static function filenameToType($filename) { - //In case the path is a URL, strip any query string before getting extension - $qpos = strpos($filename, '?'); - if ($qpos !== false) { - $filename = substr($filename, 0, $qpos); - } - $pathinfo = self::mb_pathinfo($filename); - return self::_mime_types($pathinfo['extension']); - } - - /** - * Drop-in replacement for pathinfo(), but multibyte-safe, cross-platform-safe, old-version-safe. - * Works similarly to the one in PHP >= 5.2.0 - * @link http://www.php.net/manual/en/function.pathinfo.php#107461 - * @param string $path A filename or path, does not need to exist as a file - * @param integer|string $options Either a PATHINFO_* constant, or a string name to return only the specified piece, allows 'filename' to work on PHP < 5.2 - * @return string|array - * @static - */ - public static function mb_pathinfo($path, $options = null) { - $ret = array('dirname' => '', 'basename' => '', 'extension' => '', 'filename' => ''); - $m = array(); - preg_match('%^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^\.\\\\/]+?)|))[\\\\/\.]*$%im', $path, $m); - if(array_key_exists(1, $m)) { - $ret['dirname'] = $m[1]; - } - if(array_key_exists(2, $m)) { - $ret['basename'] = $m[2]; - } - if(array_key_exists(5, $m)) { - $ret['extension'] = $m[5]; - } - if(array_key_exists(3, $m)) { - $ret['filename'] = $m[3]; - } - switch($options) { - case PATHINFO_DIRNAME: - case 'dirname': - return $ret['dirname']; - break; - case PATHINFO_BASENAME: - case 'basename': - return $ret['basename']; - break; - case PATHINFO_EXTENSION: - case 'extension': - return $ret['extension']; - break; - case PATHINFO_FILENAME: - case 'filename': - return $ret['filename']; - break; - default: - return $ret; - } - } - - /** - * Set (or reset) Class Objects (variables) - * - * Usage Example: - * $page->set('X-Priority', '3'); - * - * @access public - * @param string $name - * @param mixed $value - * NOTE: will not work with arrays, there are no arrays to set/reset - * @throws phpmailerException - * @return bool - * @todo Should this not be using __set() magic function? - */ - public function set($name, $value = '') { - try { - if (isset($this->$name) ) { - $this->$name = $value; - } else { - throw new phpmailerException($this->Lang('variable_set') . $name, self::STOP_CRITICAL); - } - } catch (Exception $e) { - $this->SetError($e->getMessage()); - if ($e->getCode() == self::STOP_CRITICAL) { - return false; - } - } - return true; - } - - /** - * Strips newlines to prevent header injection. - * @access public - * @param string $str - * @return string - */ - public function SecureHeader($str) { - return trim(str_replace(array("\r", "\n"), '', $str)); - } - - /** - * Normalize UNIX LF, Mac CR and Windows CRLF line breaks into a single line break format - * Defaults to CRLF (for message bodies) and preserves consecutive breaks - * @param string $text - * @param string $breaktype What kind of line break to use, defaults to CRLF - * @return string - * @access public - * @static - */ - public static function NormalizeBreaks($text, $breaktype = "\r\n") { - return preg_replace('/(\r\n|\r|\n)/ms', $breaktype, $text); - } - - - /** - * Set the private key file and password to sign the message. - * - * @access public - * @param string $cert_filename - * @param string $key_filename - * @param string $key_pass Password for private key - */ - public function Sign($cert_filename, $key_filename, $key_pass) { - $this->sign_cert_file = $cert_filename; - $this->sign_key_file = $key_filename; - $this->sign_key_pass = $key_pass; - } - - /** - * Set the private key file and password to sign the message. - * - * @access public - * @param string $txt - * @return string - */ - public function DKIM_QP($txt) { - $line = ''; - for ($i = 0; $i < strlen($txt); $i++) { - $ord = ord($txt[$i]); - if ( ((0x21 <= $ord) && ($ord <= 0x3A)) || $ord == 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E)) ) { - $line .= $txt[$i]; - } else { - $line .= "=".sprintf("%02X", $ord); - } - } - return $line; - } - - /** - * Generate DKIM signature - * - * @access public - * @param string $s Header - * @throws phpmailerException - * @return string - */ - public function DKIM_Sign($s) { - if (!defined('PKCS7_TEXT')) { - if ($this->exceptions) { - throw new phpmailerException($this->Lang("signing").' OpenSSL extension missing.'); + public function DKIM_Add($headers_line, $subject, $body) + { + $DKIMsignatureType = 'rsa-sha1'; // Signature & hash algorithms + $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body + $DKIMquery = 'dns/txt'; // Query method + $DKIMtime = time(); // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone) + $subject_header = "Subject: $subject"; + $headers = explode($this->LE, $headers_line); + $from_header = ''; + $to_header = ''; + $current = ''; + foreach ($headers as $header) { + if (strpos($header, 'From:') === 0) { + $from_header = $header; + $current = 'from_header'; + } elseif (strpos($header, 'To:') === 0) { + $to_header = $header; + $current = 'to_header'; + } else { + if ($current && strpos($header, ' =?') === 0) { + $current .= $header; + } else { + $current = ''; + } + } + } + $from = str_replace('|', '=7C', $this->DKIM_QP($from_header)); + $to = str_replace('|', '=7C', $this->DKIM_QP($to_header)); + $subject = str_replace( + '|', + '=7C', + $this->DKIM_QP($subject_header) + ); // Copied header fields (dkim-quoted-printable) + $body = $this->DKIM_BodyC($body); + $DKIMlen = strlen($body); // Length of body + $DKIMb64 = base64_encode(pack("H*", sha1($body))); // Base64 of packed binary SHA-1 hash of body + $ident = ($this->DKIM_identity == '') ? '' : " i=" . $this->DKIM_identity . ";"; + $dkimhdrs = "DKIM-Signature: v=1; a=" . + $DKIMsignatureType . "; q=" . + $DKIMquery . "; l=" . + $DKIMlen . "; s=" . + $this->DKIM_selector . + ";\r\n" . + "\tt=" . $DKIMtime . "; c=" . $DKIMcanonicalization . ";\r\n" . + "\th=From:To:Subject;\r\n" . + "\td=" . $this->DKIM_domain . ";" . $ident . "\r\n" . + "\tz=$from\r\n" . + "\t|$to\r\n" . + "\t|$subject;\r\n" . + "\tbh=" . $DKIMb64 . ";\r\n" . + "\tb="; + $toSign = $this->DKIM_HeaderC( + $from_header . "\r\n" . $to_header . "\r\n" . $subject_header . "\r\n" . $dkimhdrs + ); + $signed = $this->DKIM_Sign($toSign); + return $dkimhdrs . $signed . "\r\n"; + } + + /** + * Perform a callback. + * @param bool $isSent + * @param string $to + * @param string $cc + * @param string $bcc + * @param string $subject + * @param string $body + * @param string $from + */ + protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body, $from = null) + { + if (!empty($this->action_function) && is_callable($this->action_function)) { + $params = array($isSent, $to, $cc, $bcc, $subject, $body, $from); + call_user_func_array($this->action_function, $params); } - return ''; } - $privKeyStr = file_get_contents($this->DKIM_private); - if ($this->DKIM_passphrase != '') { - $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase); - } else { - $privKey = $privKeyStr; - } - if (openssl_sign($s, $signature, $privKey)) { - return base64_encode($signature); - } - return ''; - } - - /** - * Generate DKIM Canonicalization Header - * - * @access public - * @param string $s Header - * @return string - */ - public function DKIM_HeaderC($s) { - $s = preg_replace("/\r\n\s+/", " ", $s); - $lines = explode("\r\n", $s); - foreach ($lines as $key => $line) { - list($heading, $value) = explode(":", $line, 2); - $heading = strtolower($heading); - $value = preg_replace("/\s+/", " ", $value) ; // Compress useless spaces - $lines[$key] = $heading.":".trim($value) ; // Don't forget to remove WSP around the value - } - $s = implode("\r\n", $lines); - return $s; - } - - /** - * Generate DKIM Canonicalization Body - * - * @access public - * @param string $body Message Body - * @return string - */ - public function DKIM_BodyC($body) { - if ($body == '') return "\r\n"; - // stabilize line endings - $body = str_replace("\r\n", "\n", $body); - $body = str_replace("\n", "\r\n", $body); - // END stabilize line endings - while (substr($body, strlen($body) - 4, 4) == "\r\n\r\n") { - $body = substr($body, 0, strlen($body) - 2); - } - return $body; - } - - /** - * Create the DKIM header, body, as new header - * - * @access public - * @param string $headers_line Header lines - * @param string $subject Subject - * @param string $body Body - * @return string - */ - public function DKIM_Add($headers_line, $subject, $body) { - $DKIMsignatureType = 'rsa-sha1'; // Signature & hash algorithms - $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body - $DKIMquery = 'dns/txt'; // Query method - $DKIMtime = time() ; // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone) - $subject_header = "Subject: $subject"; - $headers = explode($this->LE, $headers_line); - $from_header = ''; - $to_header = ''; - $current = ''; - foreach($headers as $header) { - if (strpos($header, 'From:') === 0) { - $from_header = $header; - $current = 'from_header'; - } elseif (strpos($header, 'To:') === 0) { - $to_header = $header; - $current = 'to_header'; - } else { - if($current && strpos($header, ' =?') === 0){ - $current .= $header; - } else { - $current = ''; - } - } - } - $from = str_replace('|', '=7C', $this->DKIM_QP($from_header)); - $to = str_replace('|', '=7C', $this->DKIM_QP($to_header)); - $subject = str_replace('|', '=7C', $this->DKIM_QP($subject_header)) ; // Copied header fields (dkim-quoted-printable - $body = $this->DKIM_BodyC($body); - $DKIMlen = strlen($body) ; // Length of body - $DKIMb64 = base64_encode(pack("H*", sha1($body))) ; // Base64 of packed binary SHA-1 hash of body - $ident = ($this->DKIM_identity == '')? '' : " i=" . $this->DKIM_identity . ";"; - $dkimhdrs = "DKIM-Signature: v=1; a=" . $DKIMsignatureType . "; q=" . $DKIMquery . "; l=" . $DKIMlen . "; s=" . $this->DKIM_selector . ";\r\n". - "\tt=" . $DKIMtime . "; c=" . $DKIMcanonicalization . ";\r\n". - "\th=From:To:Subject;\r\n". - "\td=" . $this->DKIM_domain . ";" . $ident . "\r\n". - "\tz=$from\r\n". - "\t|$to\r\n". - "\t|$subject;\r\n". - "\tbh=" . $DKIMb64 . ";\r\n". - "\tb="; - $toSign = $this->DKIM_HeaderC($from_header . "\r\n" . $to_header . "\r\n" . $subject_header . "\r\n" . $dkimhdrs); - $signed = $this->DKIM_Sign($toSign); - return $dkimhdrs.$signed."\r\n"; - } - - /** - * Perform callback - * @param boolean $isSent - * @param string $to - * @param string $cc - * @param string $bcc - * @param string $subject - * @param string $body - * @param string $from - */ - protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body, $from = null) { - if (!empty($this->action_function) && is_callable($this->action_function)) { - $params = array($isSent, $to, $cc, $bcc, $subject, $body, $from); - call_user_func_array($this->action_function, $params); - } - } } /** - * Exception handler for PHPMailer + * PHPMailer exception handler * @package PHPMailer */ -class phpmailerException extends Exception { - /** - * Prettify error message output - * @return string - */ - public function errorMessage() { - $errorMsg = '' . $this->getMessage() . "
\n"; - return $errorMsg; - } +class phpmailerException extends Exception +{ + /** + * Prettify error message output + * @return string + */ + public function errorMessage() + { + $errorMsg = '' . $this->getMessage() . "
\n"; + return $errorMsg; + } } diff --git a/class.pop3.php b/class.pop3.php index 603bb0671..83f2292e8 100644 --- a/class.pop3.php +++ b/class.pop3.php @@ -1,418 +1,383 @@ + * @author Jim Jagielski (jimjag) + * @author Andy Prevost (codeworxtech) + * @author Brent R. Matzelle (original founder) + * @copyright 2013 Marcus Bointon * @copyright 2010 - 2012 Jim Jagielski * @copyright 2004 - 2009 Andy Prevost - * @license http://www.gnu.org/copyleft/lesser.html Distributed under the Lesser General Public License (LGPL) + * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License + * @note This program is distributed in the hope that it will be useful - WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. */ /** - * PHP POP-Before-SMTP Authentication Class - * - * Version 5.2.6 - * - * @license: LGPL, see PHPMailer License - * - * Specifically for PHPMailer to allow POP before SMTP authentication. - * Does not yet work with APOP - if you have an APOP account, contact Jim Jagielski - * and we can test changes to this script. - * - * This class is based on the structure of the SMTP class originally authored by Chris Ryan - * - * This class is rfc 1939 compliant and implements all the commands - * required for POP3 connection, authentication and disconnection. - * + * PHPMailer POP-Before-SMTP Authentication Class. + * Specifically for PHPMailer to use for RFC1939 POP-before-SMTP authentication. + * Does not support APOP. * @package PHPMailer - * @author Richard Davey (orig) - * @author Andy Prevost - * @author Jim Jagielski + * @author Richard Davey (original author) + * @author Marcus Bointon (coolbru) + * @author Jim Jagielski (jimjag) + * @author Andy Prevost (codeworxtech) */ -class POP3 { - /** - * Default POP3 port - * @var int - */ - public $POP3_PORT = 110; - - /** - * Default Timeout - * @var int - */ - public $POP3_TIMEOUT = 30; - - /** - * POP3 Carriage Return + Line Feed - * @var string - */ - public $CRLF = "\r\n"; - - /** - * Displaying Debug warnings? (0 = now, 1+ = yes) - * @var int - */ - public $do_debug = 2; - - /** - * POP3 Mail Server - * @var string - */ - public $host; - - /** - * POP3 Port - * @var int - */ - public $port; - - /** - * POP3 Timeout Value - * @var int - */ - public $tval; - - /** - * POP3 Username - * @var string - */ - public $username; - - /** - * POP3 Password - * @var string - */ - public $password; - - /** - * Sets the POP3 PHPMailer Version number - * @var string - */ - public $Version = '5.2.6'; - - ///////////////////////////////////////////////// - // PROPERTIES, PRIVATE AND PROTECTED - ///////////////////////////////////////////////// - - /** - * @var resource Resource handle for the POP connection socket - */ - private $pop_conn; - /** - * @var boolean Are we connected? - */ - private $connected; - /** - * @var array Error container - */ - private $error; // Error log array - - /** - * Constructor, sets the initial values - * @access public - * @return POP3 - */ - public function __construct() { - $this->pop_conn = 0; - $this->connected = false; - $this->error = null; - } - - /** - * Combination of public events - connect, login, disconnect - * @access public - * @param string $host - * @param bool|int $port - * @param bool|int $tval - * @param string $username - * @param string $password - * @param int $debug_level - * @return bool - */ - public function Authorise ($host, $port = false, $tval = false, $username, $password, $debug_level = 0) { - $this->host = $host; - - // If no port value is passed, retrieve it - if ($port == false) { - $this->port = $this->POP3_PORT; - } else { - $this->port = $port; +class POP3 +{ + /** + * The POP3 PHPMailer Version number. + * @type string + * @access public + */ + public $Version = '5.2.7'; + + /** + * Default POP3 port number. + * @type int + * @access public + */ + public $POP3_PORT = 110; + + /** + * Default timeout in seconds. + * @type int + * @access public + */ + public $POP3_TIMEOUT = 30; + + /** + * POP3 Carriage Return + Line Feed. + * @type string + * @access public + */ + public $CRLF = "\r\n"; + + /** + * Debug display level. + * Options: 0 = no, 1+ = yes + * @type int + * @access public + */ + public $do_debug = 0; + + /** + * POP3 mail server hostname. + * @type string + * @access public + */ + public $host; + + /** + * POP3 port number. + * @type int + * @access public + */ + public $port; + + /** + * POP3 Timeout Value in seconds. + * @type int + * @access public + */ + public $tval; + + /** + * POP3 username + * @type string + * @access public + */ + public $username; + + /** + * POP3 password. + * @type string + * @access public + */ + public $password; + + /** + * Resource handle for the POP3 connection socket. + * @type resource + * @access private + */ + private $pop_conn; + + /** + * Are we connected? + * @type bool + * @access private + */ + private $connected; + + /** + * Error container. + * @type array + * @access private + */ + private $error; + + /** + * Constructor. + * @access public + * @access private + */ + public function __construct() + { + $this->pop_conn = 0; + $this->connected = false; + $this->error = null; } - // If no port value is passed, retrieve it - if ($tval == false) { - $this->tval = $this->POP3_TIMEOUT; - } else { - $this->tval = $tval; + /** + * Authenticate with a POP3 server. + * A connect, login, disconnect sequence + * appropriate for POP-before SMTP authorisation. + * @access public + * @param string $host + * @param bool|int $port + * @param bool|int $tval + * @param string $username + * @param string $password + * @param int $debug_level + * @return bool + */ + public function authorise($host, $port = false, $tval = false, $username = '', $password = '', $debug_level = 0) + { + $this->host = $host; + // If no port value is passed, retrieve it + if ($port == false) { + $this->port = $this->POP3_PORT; + } else { + $this->port = $port; + } + // If no port value is passed, retrieve it + if ($tval == false) { + $this->tval = $this->POP3_TIMEOUT; + } else { + $this->tval = $tval; + } + $this->do_debug = $debug_level; + $this->username = $username; + $this->password = $password; + // Refresh the error log + $this->error = null; + // connect + $result = $this->connect($this->host, $this->port, $this->tval); + if ($result) { + $login_result = $this->login($this->username, $this->password); + if ($login_result) { + $this->disconnect(); + return true; + } + } + // We need to disconnect regardless if the login succeeded + $this->disconnect(); + return false; } - $this->do_debug = $debug_level; - $this->username = $username; - $this->password = $password; - - // Refresh the error log - $this->error = null; - - // Connect - $result = $this->Connect($this->host, $this->port, $this->tval); - - if ($result) { - $login_result = $this->Login($this->username, $this->password); - - if ($login_result) { - $this->Disconnect(); - - return true; - } - + /** + * Connect to a POP3 server. + * @access public + * @param string $host + * @param bool|int $port + * @param integer $tval + * @return boolean + */ + public function connect($host, $port = false, $tval = 30) + { + // Are we already connected? + if ($this->connected) { + return true; + } + + //On Windows this will raise a PHP Warning error if the hostname doesn't exist. + //Rather than suppress it with @fsockopen, capture it cleanly instead + set_error_handler(array($this, 'catchWarning')); + + // connect to the POP3 server + $this->pop_conn = fsockopen( + $host, // POP3 Host + $port, // Port # + $errno, // Error Number + $errstr, // Error Message + $tval + ); // Timeout (seconds) + // Restore the error handler + restore_error_handler(); + // Does the Error Log now contain anything? + if ($this->error && $this->do_debug >= 1) { + $this->displayErrors(); + } + // Did we connect? + if ($this->pop_conn == false) { + // It would appear not... + $this->error = array( + 'error' => "Failed to connect to server $host on port $port", + 'errno' => $errno, + 'errstr' => $errstr + ); + if ($this->do_debug >= 1) { + $this->displayErrors(); + } + return false; + } + + // Increase the stream time-out + // Check for PHP 4.3.0 or later + if (version_compare(phpversion(), '5.0.0', 'ge')) { + stream_set_timeout($this->pop_conn, $tval, 0); + } else { + // Does not work on Windows + if (substr(PHP_OS, 0, 3) !== 'WIN') { + socket_set_timeout($this->pop_conn, $tval, 0); + } + } + + // Get the POP3 server response + $pop3_response = $this->getResponse(); + // Check for the +OK + if ($this->checkResponse($pop3_response)) { + // The connection is established and the POP3 server is talking + $this->connected = true; + return true; + } + return false; } - // We need to disconnect regardless if the login succeeded - $this->Disconnect(); - - return false; - } - - /** - * Connect to the POP3 server - * @access public - * @param string $host - * @param bool|int $port - * @param integer $tval - * @return boolean - */ - public function Connect ($host, $port = false, $tval = 30) { - // Are we already connected? - if ($this->connected) { - return true; + /** + * Log in to the POP3 server. + * Does not support APOP (RFC 2828, 4949). + * @access public + * @param string $username + * @param string $password + * @return boolean + */ + public function login($username = '', $password = '') + { + if ($this->connected == false) { + $this->error = 'Not connected to POP3 server'; + + if ($this->do_debug >= 1) { + $this->displayErrors(); + } + } + if (empty($username)) { + $username = $this->username; + } + if (empty($password)) { + $password = $this->password; + } + $pop_username = "USER $username" . $this->CRLF; + $pop_password = "PASS $password" . $this->CRLF; + // send the Username + $this->sendString($pop_username); + $pop3_response = $this->getResponse(); + if ($this->checkResponse($pop3_response)) { + // send the Password + $this->sendString($pop_password); + $pop3_response = $this->getResponse(); + if ($this->checkResponse($pop3_response)) { + return true; + } + } + return false; } - /* - On Windows this will raise a PHP Warning error if the hostname doesn't exist. - Rather than suppress it with @fsockopen, let's capture it cleanly instead - */ - - set_error_handler(array(&$this, 'catchWarning')); - - // Connect to the POP3 server - $this->pop_conn = fsockopen($host, // POP3 Host - $port, // Port # - $errno, // Error Number - $errstr, // Error Message - $tval); // Timeout (seconds) - - // Restore the error handler - restore_error_handler(); - - // Does the Error Log now contain anything? - if ($this->error && $this->do_debug >= 1) { - $this->displayErrors(); + /** + * Disconnect from the POP3 server. + * @access public + */ + public function disconnect() + { + $this->sendString('QUIT'); + fclose($this->pop_conn); } - // Did we connect? - if ($this->pop_conn == false) { - // It would appear not... - $this->error = array( - 'error' => "Failed to connect to server $host on port $port", - 'errno' => $errno, - 'errstr' => $errstr - ); - - if ($this->do_debug >= 1) { - $this->displayErrors(); - } - - return false; + /** + * Get a response from the POP3 server. + * $size is the maximum number of bytes to retrieve + * @param integer $size + * @return string + * @access private + */ + private function getResponse($size = 128) + { + $pop3_response = fgets($this->pop_conn, $size); + return $pop3_response; } - // Increase the stream time-out - - // Check for PHP 4.3.0 or later - if (version_compare(phpversion(), '5.0.0', 'ge')) { - stream_set_timeout($this->pop_conn, $tval, 0); - } else { - // Does not work on Windows - if (substr(PHP_OS, 0, 3) !== 'WIN') { - socket_set_timeout($this->pop_conn, $tval, 0); - } - } - - // Get the POP3 server response - $pop3_response = $this->getResponse(); - - // Check for the +OK - if ($this->checkResponse($pop3_response)) { - // The connection is established and the POP3 server is talking - $this->connected = true; - return true; - } - return false; - } - - /** - * Login to the POP3 server (does not support APOP yet) - * @access public - * @param string $username - * @param string $password - * @return boolean - */ - public function Login ($username = '', $password = '') { - if ($this->connected == false) { - $this->error = 'Not connected to POP3 server'; - - if ($this->do_debug >= 1) { - $this->displayErrors(); - } + /** + * Send raw data to the POP3 server. + * @param string $string + * @return integer + * @access private + */ + private function sendString($string) + { + $bytes_sent = fwrite($this->pop_conn, $string, strlen($string)); + return $bytes_sent; } - if (empty($username)) { - $username = $this->username; - } - - if (empty($password)) { - $password = $this->password; - } - - $pop_username = "USER $username" . $this->CRLF; - $pop_password = "PASS $password" . $this->CRLF; - - // Send the Username - $this->sendString($pop_username); - $pop3_response = $this->getResponse(); - - if ($this->checkResponse($pop3_response)) { - // Send the Password - $this->sendString($pop_password); - $pop3_response = $this->getResponse(); - - if ($this->checkResponse($pop3_response)) { - return true; - } + /** + * Checks the POP3 server response. + * Looks for for +OK or -ERR. + * @param string $string + * @return boolean + * @access private + */ + private function checkResponse($string) + { + if (substr($string, 0, 3) !== '+OK') { + $this->error = array( + 'error' => "Server reported an error: $string", + 'errno' => 0, + 'errstr' => '' + ); + if ($this->do_debug >= 1) { + $this->displayErrors(); + } + return false; + } else { + return true; + } } - return false; - } - /** - * Disconnect from the POP3 server - * @access public - */ - public function Disconnect () { - $this->sendString('QUIT'); - - fclose($this->pop_conn); - } - - ///////////////////////////////////////////////// - // Private Methods - ///////////////////////////////////////////////// - - /** - * Get the socket response back. - * $size is the maximum number of bytes to retrieve - * @access private - * @param integer $size - * @return string - */ - private function getResponse ($size = 128) { - $pop3_response = fgets($this->pop_conn, $size); - - return $pop3_response; - } - - /** - * Send a string down the open socket connection to the POP3 server - * @access private - * @param string $string - * @return integer - */ - private function sendString ($string) { - $bytes_sent = fwrite($this->pop_conn, $string, strlen($string)); - - return $bytes_sent; - } - - /** - * Checks the POP3 server response for +OK or -ERR - * @access private - * @param string $string - * @return boolean - */ - private function checkResponse ($string) { - if (substr($string, 0, 3) !== '+OK') { - $this->error = array( - 'error' => "Server reported an error: $string", - 'errno' => 0, - 'errstr' => '' - ); - - if ($this->do_debug >= 1) { - $this->displayErrors(); - } - - return false; - } else { - return true; + /** + * Display errors if debug is enabled. + * @access private + */ + private function displayErrors() + { + echo '
';
+        foreach ($this->error as $single_error) {
+            print_r($single_error);
+        }
+        echo '
'; } - } - - /** - * If debug is enabled, display the error message array - * @access private - */ - private function displayErrors () { - echo '
';
-
-    foreach ($this->error as $single_error) {
-      print_r($single_error);
+    /**
+     * POP3 connection error handler.
+     * @param integer $errno
+     * @param string $errstr
+     * @param string $errfile
+     * @param integer $errline
+     * @access private
+     */
+    private function catchWarning($errno, $errstr, $errfile, $errline)
+    {
+        $this->error[] = array(
+            'error' => "Connecting to the POP3 server raised a PHP warning: ",
+            'errno' => $errno,
+            'errstr' => $errstr,
+            'errfile' => $errfile,
+            'errline' => $errline
+        );
     }
-
-    echo '
'; - } - - /** - * Takes over from PHP for the socket warning handler - * @access private - * @param integer $errno - * @param string $errstr - * @param string $errfile - * @param integer $errline - */ - private function catchWarning ($errno, $errstr, $errfile, $errline) { - $this->error[] = array( - 'error' => "Connecting to the POP3 server raised a PHP warning: ", - 'errno' => $errno, - 'errstr' => $errstr - ); - } - - // End of class } diff --git a/class.smtp.php b/class.smtp.php index 4b02f9991..46e56f401 100644 --- a/class.smtp.php +++ b/class.smtp.php @@ -1,1092 +1,943 @@ + * @author Jim Jagielski (jimjag) + * @author Andy Prevost (codeworxtech) + * @copyright 2013 Marcus Bointon * @copyright 2004 - 2008 Andy Prevost - * @author Jim Jagielski * @copyright 2010 - 2012 Jim Jagielski - * @license http://www.gnu.org/copyleft/lesser.html Distributed under the Lesser General Public License (LGPL) + * @license http://www.gnu.org/copyleft/lesser.html Distributed under the Lesser General Public License (LGPL) */ /** - * PHP RFC821 SMTP client + * PHPMailer RFC821 SMTP email transport class. + * + * Implements RFC 821 SMTP commands + * and provides some utility methods for sending mail to an SMTP server. + * + * PHP Version 5.0.0 * - * Implements all the RFC 821 SMTP commands except TURN which will always return a not implemented error. - * SMTP also provides some utility methods for sending mail to an SMTP server. - * @author Chris Ryan - * @package PHPMailer + * @category PHP + * @package PHPMailer + * @link https://github.com/PHPMailer/PHPMailer/blob/master/class.smtp.php + * @author Chris Ryan + * @author Marcus Bointon + * @license http://www.gnu.org/copyleft/lesser.html Distributed under the Lesser General Public License (LGPL) */ -class SMTP { - /** - * SMTP server port - * @var int - */ - public $SMTP_PORT = 25; - - /** - * SMTP reply line ending (don't change) - * @var string - */ - public $CRLF = "\r\n"; - - /** - * Debug output level; 0 for no output - * @var int - */ - public $do_debug = 0; - - /** - * Sets the function/method to use for debugging output. - * Right now we only honor 'echo', 'html' or 'error_log' - * @var string - */ - public $Debugoutput = 'echo'; - - /** - * Sets VERP use on/off (default is off) - * @var bool - */ - public $do_verp = false; - - /** - * Sets the SMTP timeout value for reads, in seconds - * @var int - */ - public $Timeout = 15; - - /** - * Sets the SMTP timelimit value for reads, in seconds - * @var int - */ - public $Timelimit = 30; - - /** - * Sets the SMTP PHPMailer Version number - * @var string - */ - public $Version = '5.2.6'; - - ///////////////////////////////////////////////// - // PROPERTIES, PRIVATE AND PROTECTED - ///////////////////////////////////////////////// - - /** - * @var resource The socket to the server - */ - protected $smtp_conn; - /** - * @var string Error message, if any, for the last call - */ - protected $error; - /** - * @var string The reply the server sent to us for HELO - */ - protected $helo_rply; - - /** - * Outputs debugging info via user-defined method - * @param string $str - */ - protected function edebug($str) { - switch ($this->Debugoutput) { - case 'error_log': - error_log($str); - break; - case 'html': - //Cleans up output a bit for a better looking display that's HTML-safe - echo htmlentities(preg_replace('/[\r\n]+/', '', $str), ENT_QUOTES, 'UTF-8')."
\n"; - break; - case 'echo': - default: - //Just echoes exactly what was received - echo $str; - } - } - - /** - * Initialize the class so that the data is in a known state. - * @access public - * @return SMTP - */ - public function __construct() { - $this->smtp_conn = 0; - $this->error = null; - $this->helo_rply = null; - - $this->do_debug = 0; - } - - ///////////////////////////////////////////////// - // CONNECTION FUNCTIONS - ///////////////////////////////////////////////// - - /** - * Connect to an SMTP server - * - * SMTP CODE SUCCESS: 220 - * SMTP CODE FAILURE: 421 - * @access public - * @param string $host SMTP server IP or host name - * @param int $port The port number to connect to, or use the default port if not specified - * @param int $timeout How long to wait for the connection to open - * @param array $options An array of options compatible with stream_context_create() - * @return bool - */ - public function Connect($host, $port = 0, $timeout = 30, $options = array()) { - // Clear errors to avoid confusion - $this->error = null; - - // Make sure we are __not__ connected - if($this->connected()) { - // Already connected, generate error - $this->error = array('error' => 'Already connected to a server'); - return false; - } +class SMTP +{ + /** + * The PHPMailer SMTP Version number. + */ + const VERSION = '5.2.7'; - if(empty($port)) { - $port = $this->SMTP_PORT; - } + /** + * SMTP line break constant. + */ + const CRLF = "\r\n"; - // Connect to the SMTP server - $errno = 0; - $errstr = ''; - $socket_context = stream_context_create($options); - //Need to suppress errors here as connection failures can be handled at a higher level - $this->smtp_conn = @stream_socket_client($host.":".$port, $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, $socket_context); - - // Verify we connected properly - if(empty($this->smtp_conn)) { - $this->error = array('error' => 'Failed to connect to server', - 'errno' => $errno, - 'errstr' => $errstr); - if($this->do_debug >= 1) { - $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ": $errstr ($errno)"); - } - return false; - } + /** + * The SMTP port to use if one is not specified. + */ + const DEFAULT_SMTP_PORT = 25; - // SMTP server can take longer to respond, give longer timeout for first read - // Windows does not have support for this timeout function - if(substr(PHP_OS, 0, 3) != 'WIN') { - $max = ini_get('max_execution_time'); - if ($max != 0 && $timeout > $max) { // Don't bother if unlimited - @set_time_limit($timeout); - } - stream_set_timeout($this->smtp_conn, $timeout, 0); - } + /** + * The PHPMailer SMTP Version number. + * @type string + * @deprecated This should be a constant + * @see SMTP::VERSION + */ + public $Version = '5.2.7'; - // get any announcement - $announce = $this->get_lines(); + /** + * SMTP server port number. + * @type int + * @deprecated This is only ever ued as default value, so should be a constant + * @see SMTP::DEFAULT_SMTP_PORT + */ + public $SMTP_PORT = 25; - if($this->do_debug >= 2) { - $this->edebug('SMTP -> FROM SERVER:' . $announce); - } + /** + * SMTP reply line ending + * @type string + * @deprecated Use the class constant instead + * @see SMTP::CRLF + */ + public $CRLF = "\r\n"; - return true; - } - - /** - * Initiate a TLS communication with the server. - * - * SMTP CODE 220 Ready to start TLS - * SMTP CODE 501 Syntax error (no parameters allowed) - * SMTP CODE 454 TLS not available due to temporary reason - * @access public - * @return bool success - */ - public function StartTLS() { - $this->error = null; # to avoid confusion - - if(!$this->connected()) { - $this->error = array('error' => 'Called StartTLS() without being connected'); - return false; - } + /** + * Debug output level. + * Options: 0 for no output, 1 for commands, 2 for data and commands + * @type int + */ + public $do_debug = 0; + + /** + * The function/method to use for debugging output. + * Options: 'echo', 'html' or 'error_log' + * @type string + */ + public $Debugoutput = 'echo'; - $this->client_send('STARTTLS' . $this->CRLF); + /** + * Whether to use VERP. + * @type bool + */ + public $do_verp = false; - $rply = $this->get_lines(); - $code = substr($rply, 0, 3); + /** + * The SMTP timeout value for reads, in seconds. + * @type int + */ + public $Timeout = 15; - if($this->do_debug >= 2) { - $this->edebug('SMTP -> FROM SERVER:' . $rply); - } + /** + * The SMTP timelimit value for reads, in seconds. + * @type int + */ + public $Timelimit = 30; - if($code != 220) { - $this->error = - array('error' => 'STARTTLS not accepted from server', - 'smtp_code' => $code, - 'smtp_msg' => substr($rply, 4)); - if($this->do_debug >= 1) { - $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply); - } - return false; - } + /** + * The socket for the server connection. + * @type resource + */ + protected $smtp_conn; - // Begin encrypted connection - if(!stream_socket_enable_crypto($this->smtp_conn, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) { - return false; - } + /** + * Error message, if any, for the last call. + * @type string + */ + protected $error = ''; - return true; - } - - /** - * Performs SMTP authentication. Must be run after running the - * Hello() method. Returns true if successfully authenticated. - * @access public - * @param string $username - * @param string $password - * @param string $authtype - * @param string $realm - * @param string $workstation - * @return bool - */ - public function Authenticate($username, $password, $authtype='LOGIN', $realm='', $workstation='') { - if (empty($authtype)) { - $authtype = 'LOGIN'; - } + /** + * The reply the server sent to us for HELO. + * @type string + */ + protected $helo_rply = ''; - switch ($authtype) { - case 'PLAIN': - // Start authentication - $this->client_send('AUTH PLAIN' . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply, 0, 3); - - if($code != 334) { - $this->error = - array('error' => 'AUTH not accepted from server', - 'smtp_code' => $code, - 'smtp_msg' => substr($rply, 4)); - if($this->do_debug >= 1) { - $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply); - } - return false; - } - // Send encoded username and password - $this->client_send(base64_encode("\0".$username."\0".$password) . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply, 0, 3); - - if($code != 235) { - $this->error = - array('error' => 'Authentication not accepted from server', - 'smtp_code' => $code, - 'smtp_msg' => substr($rply, 4)); - if($this->do_debug >= 1) { - $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply); - } - return false; - } - break; - case 'LOGIN': - // Start authentication - $this->client_send('AUTH LOGIN' . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply, 0, 3); - - if($code != 334) { - $this->error = - array('error' => 'AUTH not accepted from server', - 'smtp_code' => $code, - 'smtp_msg' => substr($rply, 4)); - if($this->do_debug >= 1) { - $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply); - } - return false; - } + /** + * The most recent reply received from the server. + * @type string + */ + protected $last_reply = ''; - // Send encoded username - $this->client_send(base64_encode($username) . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply, 0, 3); - - if($code != 334) { - $this->error = - array('error' => 'Username not accepted from server', - 'smtp_code' => $code, - 'smtp_msg' => substr($rply, 4)); - if($this->do_debug >= 1) { - $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply); - } - return false; - } + /** + * Constructor. + * @access public + */ + public function __construct() + { + $this->smtp_conn = 0; + $this->error = null; + $this->helo_rply = null; + + $this->do_debug = 0; + } - // Send encoded password - $this->client_send(base64_encode($password) . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply, 0, 3); - - if($code != 235) { - $this->error = - array('error' => 'Password not accepted from server', - 'smtp_code' => $code, - 'smtp_msg' => substr($rply, 4)); - if($this->do_debug >= 1) { - $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply); - } - return false; + /** + * Output debugging info via a user-selected method. + * @param string $str Debug string to output + * @return void + */ + protected function edebug($str) + { + switch ($this->Debugoutput) { + case 'error_log': + //Don't output, just log + error_log($str); + break; + case 'html': + //Cleans up output a bit for a better looking, HTML-safe output + echo htmlentities( + preg_replace('/[\r\n]+/', '', $str), + ENT_QUOTES, + 'UTF-8' + ) + . "
\n"; + break; + case 'echo': + default: + //Just echoes whatever was received + echo $str; } - break; - case 'NTLM': - /* - * ntlm_sasl_client.php - ** Bundled with Permission - ** - ** How to telnet in windows: http://technet.microsoft.com/en-us/library/aa995718%28EXCHG.65%29.aspx - ** PROTOCOL Documentation http://curl.haxx.se/rfc/ntlm.html#ntlmSmtpAuthentication - */ - require_once 'extras/ntlm_sasl_client.php'; - $temp = new stdClass(); - $ntlm_client = new ntlm_sasl_client_class; - if(! $ntlm_client->Initialize($temp)){//let's test if every function its available - $this->error = array('error' => $temp->error); - if($this->do_debug >= 1) { - $this->edebug('You need to enable some modules in your php.ini file: ' . $this->error['error']); - } + } + + /** + * Connect to an SMTP server. + * @param string $host SMTP server IP or host name + * @param int $port The port number to connect to + * @param int $timeout How long to wait for the connection to open + * @param array $options An array of options for stream_context_create() + * @access public + * @return bool + */ + public function connect($host, $port = null, $timeout = 30, $options = array()) + { + // Clear errors to avoid confusion + $this->error = null; + + // Make sure we are __not__ connected + if ($this->connected()) { + // Already connected, generate error + $this->error = array('error' => 'Already connected to a server'); return false; } - $msg1 = $ntlm_client->TypeMsg1($realm, $workstation);//msg1 - $this->client_send('AUTH NTLM ' . base64_encode($msg1) . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply, 0, 3); + if (empty($port)) { + $port = self::DEFAULT_SMTP_PORT; + } - if($code != 334) { - $this->error = - array('error' => 'AUTH not accepted from server', - 'smtp_code' => $code, - 'smtp_msg' => substr($rply, 4)); - if($this->do_debug >= 1) { - $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply); + // Connect to the SMTP server + $errno = 0; + $errstr = ''; + $socket_context = stream_context_create($options); + //Suppress errors; connection failures are handled at a higher level + $this->smtp_conn = @stream_socket_client( + $host . ":" . $port, + $errno, + $errstr, + $timeout, + STREAM_CLIENT_CONNECT, + $socket_context + ); + + // Verify we connected properly + if (empty($this->smtp_conn)) { + $this->error = array( + 'error' => 'Failed to connect to server', + 'errno' => $errno, + 'errstr' => $errstr + ); + if ($this->do_debug >= 1) { + $this->edebug( + 'SMTP -> ERROR: ' . $this->error['error'] + . ": $errstr ($errno)" + ); } return false; } - $challenge = substr($rply, 3);//though 0 based, there is a white space after the 3 digit number....//msg2 - $challenge = base64_decode($challenge); - $ntlm_res = $ntlm_client->NTLMResponse(substr($challenge, 24, 8), $password); - $msg3 = $ntlm_client->TypeMsg3($ntlm_res, $username, $realm, $workstation);//msg3 - // Send encoded username - $this->client_send(base64_encode($msg3) . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply, 0, 3); - - if($code != 235) { - $this->error = - array('error' => 'Could not authenticate', - 'smtp_code' => $code, - 'smtp_msg' => substr($rply, 4)); - if($this->do_debug >= 1) { - $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply); + // SMTP server can take longer to respond, give longer timeout for first read + // Windows does not have support for this timeout function + if (substr(PHP_OS, 0, 3) != 'WIN') { + $max = ini_get('max_execution_time'); + if ($max != 0 && $timeout > $max) { // Don't bother if unlimited + @set_time_limit($timeout); } - return false; - } - break; - case 'CRAM-MD5': - // Start authentication - $this->client_send('AUTH CRAM-MD5' . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply, 0, 3); - - if($code != 334) { - $this->error = - array('error' => 'AUTH not accepted from server', - 'smtp_code' => $code, - 'smtp_msg' => substr($rply, 4)); - if($this->do_debug >= 1) { - $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply); - } - return false; + stream_set_timeout($this->smtp_conn, $timeout, 0); } - // Get the challenge - $challenge = base64_decode(substr($rply, 4)); + // Get any announcement + $announce = $this->get_lines(); - // Build the response - $response = $username . ' ' . $this->hmac($challenge, $password); + if ($this->do_debug >= 2) { + $this->edebug('SMTP -> FROM SERVER:' . $announce); + } - // Send encoded credentials - $this->client_send(base64_encode($response) . $this->CRLF); + return true; + } - $rply = $this->get_lines(); - $code = substr($rply, 0, 3); + /** + * Initiate a TLS (encrypted) session. + * @access public + * @return bool + */ + public function startTLS() + { + if (!$this->sendCommand("STARTTLS", "STARTTLS", 220)) { + return false; + } + // Begin encrypted connection + if (!stream_socket_enable_crypto( + $this->smtp_conn, + true, + STREAM_CRYPTO_METHOD_TLS_CLIENT + ) + ) { + return false; + } + return true; + } + + /** + * Perform SMTP authentication. + * Must be run after hello(). + * @see hello() + * @param string $username The user name + * @param string $password The password + * @param string $authtype The auth type (PLAIN, LOGIN, NTLM, CRAM-MD5) + * @param string $realm The auth realm for NTLM + * @param string $workstation The auth workstation for NTLM + * @access public + * @return bool True if successfully authenticated. + */ + public function authenticate( + $username, + $password, + $authtype = 'LOGIN', + $realm = '', + $workstation = '' + ) { + if (empty($authtype)) { + $authtype = 'LOGIN'; + } - if($code != 235) { - $this->error = - array('error' => 'Credentials not accepted from server', - 'smtp_code' => $code, - 'smtp_msg' => substr($rply, 4)); - if($this->do_debug >= 1) { - $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply); - } - return false; + switch ($authtype) { + case 'PLAIN': + // Start authentication + if (!$this->sendCommand('AUTH', 'AUTH PLAIN', 334)) { + return false; + } + // Send encoded username and password + if (!$this->sendCommand( + 'User & Password', + base64_encode("\0" . $username . "\0" . $password), + 235 + ) + ) { + return false; + } + break; + case 'LOGIN': + // Start authentication + if (!$this->sendCommand('AUTH', 'AUTH LOGIN', 334)) { + return false; + } + if (!$this->sendCommand("Username", base64_encode($username), 334)) { + return false; + } + if (!$this->sendCommand("Password", base64_encode($password), 235)) { + return false; + } + break; + case 'NTLM': + /* + * ntlm_sasl_client.php + * Bundled with Permission + * + * How to telnet in windows: + * http://technet.microsoft.com/en-us/library/aa995718%28EXCHG.65%29.aspx + * PROTOCOL Docs http://curl.haxx.se/rfc/ntlm.html#ntlmSmtpAuthentication + */ + require_once 'extras/ntlm_sasl_client.php'; + $temp = new stdClass(); + $ntlm_client = new ntlm_sasl_client_class; + //Check that functions are available + if (!$ntlm_client->Initialize($temp)) { + $this->error = array('error' => $temp->error); + if ($this->do_debug >= 1) { + $this->edebug( + 'You need to enable some modules in your php.ini file: ' + . $this->error['error'] + ); + } + return false; + } + //msg1 + $msg1 = $ntlm_client->TypeMsg1($realm, $workstation); //msg1 + + if (!$this->sendCommand( + 'AUTH NTLM', + 'AUTH NTLM ' . base64_encode($msg1), + 334 + ) + ) { + return false; + } + + //Though 0 based, there is a white space after the 3 digit number + //msg2 + $challenge = substr($this->last_reply, 3); + $challenge = base64_decode($challenge); + $ntlm_res = $ntlm_client->NTLMResponse( + substr($challenge, 24, 8), + $password + ); + //msg3 + $msg3 = $ntlm_client->TypeMsg3( + $ntlm_res, + $username, + $realm, + $workstation + ); + // send encoded username + return $this->sendCommand('Username', base64_encode($msg3), 235); + break; + case 'CRAM-MD5': + // Start authentication + if (!$this->sendCommand('AUTH CRAM-MD5', 'AUTH CRAM-MD5', 334)) { + return false; + } + // Get the challenge + $challenge = base64_decode(substr($this->last_reply, 4)); + + // Build the response + $response = $username . ' ' . $this->hmac($challenge, $password); + + // send encoded credentials + return $this->sendCommand('Username', base64_encode($response), 235); + break; } - break; + return true; } - return true; - } - - /** - * Works like hash_hmac('md5', $data, $key) in case that function is not available - * @access protected - * @param string $data - * @param string $key - * @return string - */ - protected function hmac($data, $key) { - if (function_exists('hash_hmac')) { - return hash_hmac('md5', $data, $key); - } - - // The following borrowed from http://php.net/manual/en/function.mhash.php#27225 - - // RFC 2104 HMAC implementation for php. - // Creates an md5 HMAC. - // Eliminates the need to install mhash to compute a HMAC - // Hacked by Lance Rushing - - $b = 64; // byte length for md5 - if (strlen($key) > $b) { - $key = pack('H*', md5($key)); - } - $key = str_pad($key, $b, chr(0x00)); - $ipad = str_pad('', $b, chr(0x36)); - $opad = str_pad('', $b, chr(0x5c)); - $k_ipad = $key ^ $ipad ; - $k_opad = $key ^ $opad; - - return md5($k_opad . pack('H*', md5($k_ipad . $data))); - } - - /** - * Returns true if connected to a server otherwise false - * @access public - * @return bool - */ - public function Connected() { - if(!empty($this->smtp_conn)) { - $sock_status = stream_get_meta_data($this->smtp_conn); - if($sock_status['eof']) { - // the socket is valid but we are not connected - if($this->do_debug >= 1) { - $this->edebug('SMTP -> NOTICE: EOF caught while checking if connected'); + + /** + * Calculate an MD5 HMAC hash. + * Works like hash_hmac('md5', $data, $key) + * in case that function is not available + * @param string $data The data to hash + * @param string $key The key to hash with + * @access protected + * @return string + */ + protected function hmac($data, $key) + { + if (function_exists('hash_hmac')) { + return hash_hmac('md5', $data, $key); } - $this->Close(); - return false; - } - return true; // everything looks good - } - return false; - } - - /** - * Closes the socket and cleans up the state of the class. - * It is not considered good to use this function without - * first trying to use QUIT. - * @access public - * @return void - */ - public function Close() { - $this->error = null; // so there is no confusion - $this->helo_rply = null; - if(!empty($this->smtp_conn)) { - // close the connection and cleanup - fclose($this->smtp_conn); - $this->smtp_conn = 0; - } - } - - ///////////////////////////////////////////////// - // SMTP COMMANDS - ///////////////////////////////////////////////// - - /** - * Issues a data command and sends the msg_data to the server - * finializing the mail transaction. $msg_data is the message - * that is to be send with the headers. Each header needs to be - * on a single line followed by a with the message headers - * and the message body being separated by and additional . - * - * Implements rfc 821: DATA - * - * SMTP CODE INTERMEDIATE: 354 - * [data] - * . - * SMTP CODE SUCCESS: 250 - * SMTP CODE FAILURE: 552, 554, 451, 452 - * SMTP CODE FAILURE: 451, 554 - * SMTP CODE ERROR : 500, 501, 503, 421 - * @access public - * @param string $msg_data - * @return bool - */ - public function Data($msg_data) { - $this->error = null; // so no confusion is caused - - if(!$this->connected()) { - $this->error = array( - 'error' => 'Called Data() without being connected'); - return false; - } - $this->client_send('DATA' . $this->CRLF); + // The following borrowed from + // http://php.net/manual/en/function.mhash.php#27225 - $rply = $this->get_lines(); - $code = substr($rply, 0, 3); + // RFC 2104 HMAC implementation for php. + // Creates an md5 HMAC. + // Eliminates the need to install mhash to compute a HMAC + // Hacked by Lance Rushing - if($this->do_debug >= 2) { - $this->edebug('SMTP -> FROM SERVER:' . $rply); - } + $b = 64; // byte length for md5 + if (strlen($key) > $b) { + $key = pack('H*', md5($key)); + } + $key = str_pad($key, $b, chr(0x00)); + $ipad = str_pad('', $b, chr(0x36)); + $opad = str_pad('', $b, chr(0x5c)); + $k_ipad = $key ^ $ipad; + $k_opad = $key ^ $opad; - if($code != 354) { - $this->error = - array('error' => 'DATA command not accepted from server', - 'smtp_code' => $code, - 'smtp_msg' => substr($rply, 4)); - if($this->do_debug >= 1) { - $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply); - } - return false; + return md5($k_opad . pack('H*', md5($k_ipad . $data))); } - /* the server is ready to accept data! - * according to rfc 821 we should not send more than 1000 - * including the CRLF - * characters on a single line so we will break the data up - * into lines by \r and/or \n then if needed we will break - * each of those into smaller lines to fit within the limit. - * in addition we will be looking for lines that start with - * a period '.' and append and additional period '.' to that - * line. NOTE: this does not count towards limit. + /** + * Check connection state. + * @access public + * @return bool True if connected. */ + public function connected() + { + if (!empty($this->smtp_conn)) { + $sock_status = stream_get_meta_data($this->smtp_conn); + if ($sock_status['eof']) { + // the socket is valid but we are not connected + if ($this->do_debug >= 1) { + $this->edebug( + 'SMTP -> NOTICE: EOF caught while checking if connected' + ); + } + $this->close(); + return false; + } + return true; // everything looks good + } + return false; + } - // normalize the line breaks so we know the explode works - $msg_data = str_replace("\r\n", "\n", $msg_data); - $msg_data = str_replace("\r", "\n", $msg_data); - $lines = explode("\n", $msg_data); - - /* we need to find a good way to determine is headers are - * in the msg_data or if it is a straight msg body - * currently I am assuming rfc 822 definitions of msg headers - * and if the first field of the first line (':' sperated) - * does not contain a space then it _should_ be a header - * and we can process all lines before a blank "" line as - * headers. + /** + * Close the socket and clean up the state of the class. + * Don't use this function without first trying to use QUIT. + * @see quit() + * @access public + * @return void */ - - $field = substr($lines[0], 0, strpos($lines[0], ':')); - $in_headers = false; - if(!empty($field) && !strstr($field, ' ')) { - $in_headers = true; + public function close() + { + $this->error = null; // so there is no confusion + $this->helo_rply = null; + if (!empty($this->smtp_conn)) { + // close the connection and cleanup + fclose($this->smtp_conn); + $this->smtp_conn = 0; + } } - $max_line_length = 998; // used below; set here for ease in change - - while(list(, $line) = @each($lines)) { - $lines_out = null; - if($line == '' && $in_headers) { - $in_headers = false; - } - // ok we need to break this line up into several smaller lines - while(strlen($line) > $max_line_length) { - $pos = strrpos(substr($line, 0, $max_line_length), ' '); - - // Patch to fix DOS attack - if(!$pos) { - $pos = $max_line_length - 1; - $lines_out[] = substr($line, 0, $pos); - $line = substr($line, $pos); - } else { - $lines_out[] = substr($line, 0, $pos); - $line = substr($line, $pos + 1); + /** + * Send an SMTP DATA command. + * Issues a data command and sends the msg_data to the server, + * finializing the mail transaction. $msg_data is the message + * that is to be send with the headers. Each header needs to be + * on a single line followed by a with the message headers + * and the message body being separated by and additional . + * Implements rfc 821: DATA + * @param string $msg_data Message data to send + * @access public + * @return bool + */ + public function data($msg_data) + { + if (!$this->sendCommand('DATA', 'DATA', 354)) { + return false; } - /* if processing headers add a LWSP-char to the front of new line - * rfc 822 on long msg headers + /* The server is ready to accept data! + * according to rfc821 we should not send more than 1000 + * including the CRLF + * characters on a single line so we will break the data up + * into lines by \r and/or \n then if needed we will break + * each of those into smaller lines to fit within the limit. + * in addition we will be looking for lines that start with + * a period '.' and append and additional period '.' to that + * line. NOTE: this does not count towards limit. */ - if($in_headers) { - $line = "\t" . $line; - } - } - $lines_out[] = $line; - - // send the lines to the server - while(list(, $line_out) = @each($lines_out)) { - if(strlen($line_out) > 0) - { - if(substr($line_out, 0, 1) == '.') { - $line_out = '.' . $line_out; - } + + // Normalize the line breaks before exploding + $msg_data = str_replace("\r\n", "\n", $msg_data); + $msg_data = str_replace("\r", "\n", $msg_data); + $lines = explode("\n", $msg_data); + + /* We need to find a good way to determine if headers are + * in the msg_data or if it is a straight msg body + * currently I am assuming rfc822 definitions of msg headers + * and if the first field of the first line (':' separated) + * does not contain a space then it _should_ be a header + * and we can process all lines before a blank "" line as + * headers. + */ + + $field = substr($lines[0], 0, strpos($lines[0], ':')); + $in_headers = false; + if (!empty($field) && !strstr($field, ' ')) { + $in_headers = true; } - $this->client_send($line_out . $this->CRLF); - } - } - // message data has been sent - $this->client_send($this->CRLF . '.' . $this->CRLF); + //RFC 2822 section 2.1.1 limit + $max_line_length = 998; - $rply = $this->get_lines(); - $code = substr($rply, 0, 3); + foreach ($lines as $line) { + $lines_out = null; + if ($line == '' && $in_headers) { + $in_headers = false; + } + // ok we need to break this line up into several smaller lines + while (strlen($line) > $max_line_length) { + $pos = strrpos(substr($line, 0, $max_line_length), ' '); + + // Patch to fix DOS attack + if (!$pos) { + $pos = $max_line_length - 1; + $lines_out[] = substr($line, 0, $pos); + $line = substr($line, $pos); + } else { + $lines_out[] = substr($line, 0, $pos); + $line = substr($line, $pos + 1); + } + + /* If processing headers add a LWSP-char to the front of new line + * rfc822 on long msg headers + */ + if ($in_headers) { + $line = "\t" . $line; + } + } + $lines_out[] = $line; + + // send the lines to the server + while (list(, $line_out) = @each($lines_out)) { + if (strlen($line_out) > 0) { + if (substr($line_out, 0, 1) == '.') { + $line_out = '.' . $line_out; + } + } + $this->client_send($line_out . self::CRLF); + } + } - if($this->do_debug >= 2) { - $this->edebug('SMTP -> FROM SERVER:' . $rply); + // Message data has been sent, complete the command + return $this->sendCommand('DATA END', self::CRLF . '.', 250); } - if($code != 250) { - $this->error = - array('error' => 'DATA not accepted from server', - 'smtp_code' => $code, - 'smtp_msg' => substr($rply, 4)); - if($this->do_debug >= 1) { - $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply); - } - return false; - } - return true; - } - - /** - * Sends the HELO command to the smtp server. - * This makes sure that we and the server are in - * the same known state. - * - * Implements from rfc 821: HELO - * - * SMTP CODE SUCCESS: 250 - * SMTP CODE ERROR : 500, 501, 504, 421 - * @access public - * @param string $host - * @return bool - */ - public function Hello($host = '') { - $this->error = null; // so no confusion is caused - - if(!$this->connected()) { - $this->error = array( - 'error' => 'Called Hello() without being connected'); - return false; - } + /** + * Send an SMTP HELO or EHLO command. + * Used to identify the sending server to the receiving server. + * This makes sure that client and server are in a known state. + * Implements from RFC 821: HELO + * and RFC 2821 EHLO. + * @param string $host The host name or IP to connect to + * @access public + * @return bool + */ + public function hello($host = '') + { + // Try extended hello first (RFC 2821) + if (!$this->sendHello('EHLO', $host)) { + if (!$this->sendHello('HELO', $host)) { + return false; + } + } - // if hostname for HELO was not specified send default - if(empty($host)) { - // determine appropriate default to send to server - $host = 'localhost'; + return true; } - // Send extended hello first (RFC 2821) - if(!$this->SendHello('EHLO', $host)) { - if(!$this->SendHello('HELO', $host)) { - return false; - } + /** + * Send an SMTP HELO or EHLO command. + * Low-level implementation used by hello() + * @see hello() + * @param string $hello The HELO string + * @param string $host The hostname to say we are + * @access protected + * @return bool + */ + protected function sendHello($hello, $host) + { + $noerror = $this->sendCommand($hello, $hello . ' ' . $host, 250); + $this->helo_rply = $this->last_reply; + return $noerror; + } + + /** + * Send an SMTP MAIL command. + * Starts a mail transaction from the email address specified in + * $from. Returns true if successful or false otherwise. If True + * the mail transaction is started and then one or more recipient + * commands may be called followed by a data command. + * Implements rfc 821: MAIL FROM: + * @param string $from Source address of this message + * @access public + * @return bool + */ + public function mail($from) + { + $useVerp = ($this->do_verp ? ' XVERP' : ''); + return $this->sendCommand( + 'MAIL FROM', + 'MAIL FROM:<' . $from . '>' . $useVerp, + 250 + ); + } + + /** + * Send an SMTP QUIT command. + * Closes the socket if there is no error or the $close_on_error argument is true. + * Implements from rfc 821: QUIT + * @param bool $close_on_error Should the connection close if an error occurs? + * @access public + * @return bool + */ + public function quit($close_on_error = true) + { + $noerror = $this->sendCommand('QUIT', 'QUIT', 221); + $e = $this->error; //Save any error + if ($noerror or $close_on_error) { + $this->close(); + $this->error = $e; //Restore any error from the quit command + } + return $noerror; } - return true; - } - - /** - * Sends a HELO/EHLO command. - * @access protected - * @param string $hello - * @param string $host - * @return bool - */ - protected function SendHello($hello, $host) { - $this->client_send($hello . ' ' . $host . $this->CRLF); + /** + * Send an SMTP RCPT command. + * Sets the TO argument to $to. + * Returns true if the recipient was accepted false if it was rejected. + * Implements from rfc 821: RCPT TO: + * @param string $to The address the message is being sent to + * @access public + * @return bool + */ + public function recipient($to) + { + return $this->sendCommand( + 'RCPT TO ', + 'RCPT TO:<' . $to . '>', + array(250, 251) + ); + } + + /** + * Send an SMTP RSET command. + * Abort any transaction that is currently in progress. + * Implements rfc 821: RSET + * @access public + * @return bool True on success. + */ + public function reset() + { + return $this->sendCommand('RSET', 'RSET', 250); + } + + /** + * Send a command to an SMTP server and check its return code. + * @param string $command The command name - not sent to the server + * @param string $commandstring The actual command to send + * @param int|array $expect One or more expected integer success codes + * @access protected + * @return bool True on success. + */ + protected function sendCommand($command, $commandstring, $expect) + { + if (!$this->connected()) { + $this->error = array( + "error" => "Called $command without being connected" + ); + return false; + } + $this->client_send($commandstring . self::CRLF); - $rply = $this->get_lines(); - $code = substr($rply, 0, 3); + $reply = $this->get_lines(); + $code = substr($reply, 0, 3); - if($this->do_debug >= 2) { - $this->edebug('SMTP -> FROM SERVER: ' . $rply); - } + if ($this->do_debug >= 2) { + $this->edebug('SMTP -> FROM SERVER:' . $reply); + } - if($code != 250) { - $this->error = - array('error' => $hello . ' not accepted from server', - 'smtp_code' => $code, - 'smtp_msg' => substr($rply, 4)); - if($this->do_debug >= 1) { - $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply); - } - return false; - } + if (!in_array($code, (array)$expect)) { + $this->last_reply = null; + $this->error = array( + "error" => "$command command failed", + "smtp_code" => $code, + "detail" => substr($reply, 4) + ); + if ($this->do_debug >= 1) { + $this->edebug( + 'SMTP -> ERROR: ' . $this->error['error'] . ': ' . $reply + ); + } + return false; + } - $this->helo_rply = $rply; - - return true; - } - - /** - * Starts a mail transaction from the email address specified in - * $from. Returns true if successful or false otherwise. If True - * the mail transaction is started and then one or more Recipient - * commands may be called followed by a Data command. - * - * Implements rfc 821: MAIL FROM: - * - * SMTP CODE SUCCESS: 250 - * SMTP CODE SUCCESS: 552, 451, 452 - * SMTP CODE SUCCESS: 500, 501, 421 - * @access public - * @param string $from - * @return bool - */ - public function Mail($from) { - $this->error = null; // so no confusion is caused - - if(!$this->connected()) { - $this->error = array( - 'error' => 'Called Mail() without being connected'); - return false; + $this->last_reply = $reply; + $this->error = null; + return true; + } + + /** + * Send an SMTP SAML command. + * Starts a mail transaction from the email address specified in $from. + * Returns true if successful or false otherwise. If True + * the mail transaction is started and then one or more recipient + * commands may be called followed by a data command. This command + * will send the message to the users terminal if they are logged + * in and send them an email. + * Implements rfc 821: SAML FROM: + * @param string $from The address the message is from + * @access public + * @return bool + */ + public function sendAndMail($from) + { + return $this->sendCommand("SAML", "SAML FROM:$from", 250); } - $useVerp = ($this->do_verp ? ' XVERP' : ''); - $this->client_send('MAIL FROM:<' . $from . '>' . $useVerp . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply, 0, 3); - - if($this->do_debug >= 2) { - $this->edebug('SMTP -> FROM SERVER:' . $rply); + /** + * Send an SMTP VRFY command. + * @param string $name The name to verify + * @access public + * @return bool + */ + public function verify($name) + { + return $this->sendCommand("VRFY", "VRFY $name", array(250, 251)); } - if($code != 250) { - $this->error = - array('error' => 'MAIL not accepted from server', - 'smtp_code' => $code, - 'smtp_msg' => substr($rply, 4)); - if($this->do_debug >= 1) { - $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply); - } - return false; - } - return true; - } - - /** - * Sends the quit command to the server and then closes the socket - * if there is no error or the $close_on_error argument is true. - * - * Implements from rfc 821: QUIT - * - * SMTP CODE SUCCESS: 221 - * SMTP CODE ERROR : 500 - * @access public - * @param bool $close_on_error - * @return bool - */ - public function Quit($close_on_error = true) { - $this->error = null; // so there is no confusion - - if(!$this->connected()) { - $this->error = array( - 'error' => 'Called Quit() without being connected'); - return false; + /** + * Send an SMTP NOOP command. + * Used to keep keep-alives alive, doesn't actually do anything + * @access public + * @return bool + */ + public function noop() + { + return $this->sendCommand("NOOP", "NOOP", 250); + } + + /** + * Send an SMTP TURN command. + * This is an optional command for SMTP that this class does not support. + * This method is here to make the RFC821 Definition + * complete for this class and __may__ be implemented in future + * Implements from rfc 821: TURN + * @access public + * @return bool + */ + public function turn() + { + $this->error = array( + 'error' => 'The SMTP TURN command is not implemented' + ); + if ($this->do_debug >= 1) { + $this->edebug('SMTP -> NOTICE: ' . $this->error['error']); + } + return false; } - // send the quit command to the server - $this->client_send('quit' . $this->CRLF); - - // get any good-bye messages - $byemsg = $this->get_lines(); - - if($this->do_debug >= 2) { - $this->edebug('SMTP -> FROM SERVER:' . $byemsg); + /** + * Send raw data to the server. + * @param string $data The data to send + * @access public + * @return int|bool The number of bytes sent to the server or FALSE on error + */ + public function client_send($data) + { + if ($this->do_debug >= 1) { + $this->edebug("CLIENT -> SMTP: $data"); + } + return fwrite($this->smtp_conn, $data); } - $rval = true; - $e = null; - - $code = substr($byemsg, 0, 3); - if($code != 221) { - // use e as a tmp var cause Close will overwrite $this->error - $e = array('error' => 'SMTP server rejected quit command', - 'smtp_code' => $code, - 'smtp_rply' => substr($byemsg, 4)); - $rval = false; - if($this->do_debug >= 1) { - $this->edebug('SMTP -> ERROR: ' . $e['error'] . ': ' . $byemsg); - } + /** + * Get the latest error. + * @access public + * @return array + */ + public function getError() + { + return $this->error; } - if(empty($e) || $close_on_error) { - $this->Close(); + /** + * Get the last reply from the server. + * @access public + * @return string + */ + public function getLastReply() + { + return $this->last_reply; + } + + /** + * Read the SMTP server's response. + * Either before eof or socket timeout occurs on the operation. + * With SMTP we can tell if we have more lines to read if the + * 4th character is '-' symbol. If it is a space then we don't + * need to read anything else. + * @access protected + * @return string + */ + protected function get_lines() + { + $data = ''; + $endtime = 0; + // If the connection is bad, give up now + if (!is_resource($this->smtp_conn)) { + return $data; + } + stream_set_timeout($this->smtp_conn, $this->Timeout); + if ($this->Timelimit > 0) { + $endtime = time() + $this->Timelimit; + } + while (is_resource($this->smtp_conn) && !feof($this->smtp_conn)) { + $str = @fgets($this->smtp_conn, 515); + if ($this->do_debug >= 4) { + $this->edebug("SMTP -> get_lines(): \$data was \"$data\""); + $this->edebug("SMTP -> get_lines(): \$str is \"$str\""); + } + $data .= $str; + if ($this->do_debug >= 4) { + $this->edebug("SMTP -> get_lines(): \$data is \"$data\""); + } + // if 4th character is a space, we are done reading, break the loop + if (substr($str, 3, 1) == ' ') { + break; + } + // Timed-out? Log and break + $info = stream_get_meta_data($this->smtp_conn); + if ($info['timed_out']) { + if ($this->do_debug >= 4) { + $this->edebug( + 'SMTP -> get_lines(): timed-out (' . $this->Timeout . ' sec)' + ); + } + break; + } + // Now check if reads took too long + if ($endtime) { + if (time() > $endtime) { + if ($this->do_debug >= 4) { + $this->edebug( + 'SMTP -> get_lines(): timelimit reached (' + . $this->Timelimit . ' sec)' + ); + } + break; + } + } + } + return $data; } - return $rval; - } - - /** - * Sends the command RCPT to the SMTP server with the TO: argument of $to. - * Returns true if the recipient was accepted false if it was rejected. - * - * Implements from rfc 821: RCPT TO: - * - * SMTP CODE SUCCESS: 250, 251 - * SMTP CODE FAILURE: 550, 551, 552, 553, 450, 451, 452 - * SMTP CODE ERROR : 500, 501, 503, 421 - * @access public - * @param string $to - * @return bool - */ - public function Recipient($to) { - $this->error = null; // so no confusion is caused - - if(!$this->connected()) { - $this->error = array( - 'error' => 'Called Recipient() without being connected'); - return false; + /** + * Enable or disable VERP address generation. + * @param bool $enabled + */ + public function setVerp($enabled = false) + { + $this->do_verp = $enabled; } - $this->client_send('RCPT TO:<' . $to . '>' . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply, 0, 3); - - if($this->do_debug >= 2) { - $this->edebug('SMTP -> FROM SERVER:' . $rply); + /** + * Get VERP address generation mode. + * @return bool + */ + public function getVerp() + { + return $this->do_verp; } - if($code != 250 && $code != 251) { - $this->error = - array('error' => 'RCPT not accepted from server', - 'smtp_code' => $code, - 'smtp_msg' => substr($rply, 4)); - if($this->do_debug >= 1) { - $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply); - } - return false; - } - return true; - } - - /** - * Sends the RSET command to abort and transaction that is - * currently in progress. Returns true if successful false - * otherwise. - * - * Implements rfc 821: RSET - * - * SMTP CODE SUCCESS: 250 - * SMTP CODE ERROR : 500, 501, 504, 421 - * @access public - * @return bool - */ - public function Reset() { - $this->error = null; // so no confusion is caused - - if(!$this->connected()) { - $this->error = array('error' => 'Called Reset() without being connected'); - return false; + /** + * Set debug output method. + * @param string $method The function/method to use for debugging output. + */ + public function setDebugOutput($method = 'echo') + { + $this->Debugoutput = $method; } - $this->client_send('RSET' . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply, 0, 3); - - if($this->do_debug >= 2) { - $this->edebug('SMTP -> FROM SERVER:' . $rply); + /** + * Get debug output method. + * @return string + */ + public function getDebugOutput() + { + return $this->Debugoutput; } - if($code != 250) { - $this->error = - array('error' => 'RSET failed', - 'smtp_code' => $code, - 'smtp_msg' => substr($rply, 4)); - if($this->do_debug >= 1) { - $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply); - } - return false; + /** + * Set debug output level. + * @param int $level + */ + public function setDebugLevel($level = 0) + { + $this->do_debug = $level; } - return true; - } - - /** - * Starts a mail transaction from the email address specified in - * $from. Returns true if successful or false otherwise. If True - * the mail transaction is started and then one or more Recipient - * commands may be called followed by a Data command. This command - * will send the message to the users terminal if they are logged - * in and send them an email. - * - * Implements rfc 821: SAML FROM: - * - * SMTP CODE SUCCESS: 250 - * SMTP CODE SUCCESS: 552, 451, 452 - * SMTP CODE SUCCESS: 500, 501, 502, 421 - * @access public - * @param string $from - * @return bool - */ - public function SendAndMail($from) { - $this->error = null; // so no confusion is caused - - if(!$this->connected()) { - $this->error = array( - 'error' => 'Called SendAndMail() without being connected'); - return false; + /** + * Get debug output level. + * @return int + */ + public function getDebugLevel() + { + return $this->do_debug; } - $this->client_send('SAML FROM:' . $from . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply, 0, 3); - - if($this->do_debug >= 2) { - $this->edebug('SMTP -> FROM SERVER:' . $rply); + /** + * Set SMTP timeout. + * @param int $timeout + */ + public function setTimeout($timeout = 0) + { + $this->Timeout = $timeout; } - if($code != 250) { - $this->error = - array('error' => 'SAML not accepted from server', - 'smtp_code' => $code, - 'smtp_msg' => substr($rply, 4)); - if($this->do_debug >= 1) { - $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply); - } - return false; - } - return true; - } - - /** - * This is an optional command for SMTP that this class does not - * support. This method is here to make the RFC821 Definition - * complete for this class and __may__ be implimented in the future - * - * Implements from rfc 821: TURN - * - * SMTP CODE SUCCESS: 250 - * SMTP CODE FAILURE: 502 - * SMTP CODE ERROR : 500, 503 - * @access public - * @return bool - */ - public function Turn() { - $this->error = array('error' => 'This method, TURN, of the SMTP '. - 'is not implemented'); - if($this->do_debug >= 1) { - $this->edebug('SMTP -> NOTICE: ' . $this->error['error']); - } - return false; - } - - /** - * Sends data to the server - * @param string $data - * @access public - * @return Integer number of bytes sent to the server or FALSE on error - */ - public function client_send($data) { - if ($this->do_debug >= 1) { - $this->edebug("CLIENT -> SMTP: $data"); - } - return fwrite($this->smtp_conn, $data); - } - - /** - * Get the current error - * @access public - * @return array - */ - public function getError() { - return $this->error; - } - - ///////////////////////////////////////////////// - // INTERNAL FUNCTIONS - ///////////////////////////////////////////////// - - /** - * Read in as many lines as possible - * either before eof or socket timeout occurs on the operation. - * With SMTP we can tell if we have more lines to read if the - * 4th character is '-' symbol. If it is a space then we don't - * need to read anything else. - * @access protected - * @return string - */ - protected function get_lines() { - $data = ''; - $endtime = 0; - /* If for some reason the fp is bad, don't inf loop */ - if (!is_resource($this->smtp_conn)) { - return $data; - } - stream_set_timeout($this->smtp_conn, $this->Timeout); - if ($this->Timelimit > 0) { - $endtime = time() + $this->Timelimit; - } - while(is_resource($this->smtp_conn) && !feof($this->smtp_conn)) { - $str = @fgets($this->smtp_conn, 515); - if($this->do_debug >= 4) { - $this->edebug("SMTP -> get_lines(): \$data was \"$data\""); - $this->edebug("SMTP -> get_lines(): \$str is \"$str\""); - } - $data .= $str; - if($this->do_debug >= 4) { - $this->edebug("SMTP -> get_lines(): \$data is \"$data\""); - } - // if 4th character is a space, we are done reading, break the loop - if(substr($str, 3, 1) == ' ') { break; } - // Timed-out? Log and break - $info = stream_get_meta_data($this->smtp_conn); - if ($info['timed_out']) { - if($this->do_debug >= 4) { - $this->edebug('SMTP -> get_lines(): timed-out (' . $this->Timeout . ' seconds)'); - } - break; - } - // Now check if reads took too long - if ($endtime) { - if (time() > $endtime) { - if($this->do_debug >= 4) { - $this->edebug('SMTP -> get_lines(): timelimit reached (' . $this->Timelimit . ' seconds)'); - } - break; - } - } + /** + * Get SMTP timeout. + * @return int + */ + public function getTimeout() + { + return $this->Timeout; } - return $data; - } - } diff --git a/docs/Note_for_SMTP_debugging.txt b/docs/Note_for_SMTP_debugging.txt index afb5b58ef..128b2d9d8 100644 --- a/docs/Note_for_SMTP_debugging.txt +++ b/docs/Note_for_SMTP_debugging.txt @@ -1,10 +1,8 @@ -If you are having problems connecting or sending emails through your SMTP server, please note: - -1. The new rewrite of class.smtp.php provides more information about the processing/errors taking place -2. Use the debug functionality of class.smtp.php. To do that, in your own script add the debug level you wish to use. An example of that is: +If you are having problems connecting or sending emails through your SMTP server, the SMTP class can provide more information about the processing/errors taking place. +Use the debug functionality of the class to see what's going on in your connections. To do that, set the debug level in your script. For example: $mail->SMTPDebug = 1; -$mail->IsSMTP(); // telling the class to use SMTP +$mail->isSMTP(); // telling the class to use SMTP $mail->SMTPAuth = true; // enable SMTP authentication $mail->Port = 26; // set the SMTP port $mail->Host = "mail.yourhost.com"; // SMTP server @@ -12,12 +10,8 @@ $mail->Username = "name@yourhost.com"; // SMTP account username $mail->Password = "your password"; // SMTP account password Notes on this: -$mail->SMTPDebug = 0; ... will disable debugging (you can also leave this out completely, 0 is the default -$mail->SMTPDebug = 1; ... will echo errors and messages -$mail->SMTPDebug = 2; ... will echo messages only -... and finally, the options are 0, 1, and 2 ... any number greater than 2 will be interpreted as 2 +$mail->SMTPDebug = 0; ... will disable debugging (you can also leave this out completely, 0 is the default) +$mail->SMTPDebug = 1; ... will echo errors and server responses +$mail->SMTPDebug = 2; ... will echo errors, server responses and client messages And finally, don't forget to disable debugging before going into production. - -Enjoy! -Andy \ No newline at end of file diff --git a/docs/extending.html b/docs/extending.html index 310f97a3b..e5f16cec4 100644 --- a/docs/extending.html +++ b/docs/extending.html @@ -27,8 +27,8 @@

1. Advanced Example

@MYSQL_CONNECT("localhost","root","password"); @mysql_select_db("my_company"); -$query  = "SELECT full_name, email, photo FROM employee WHERE id=$id"; -$result = @MYSQL_QUERY($query); +$query� =�"SELECT full_name, email,�photo�FROM employee�WHERE�id=$id"; +$result�=�@MYSQL_QUERY($query); while ($row = mysql_fetch_array ($result)) { @@ -46,15 +46,15 @@

1. Advanced Example

$mail->Body = $body; $mail->AltBody = $text_body; - $mail->AddAddress($row["email"], $row["full_name"]); - $mail->AddStringAttachment($row["photo"], "YourPhoto.jpg"); + $mail->addAddress($row["email"], $row["full_name"]); + $mail->addStringAttachment($row["photo"], "YourPhoto.jpg"); - if(!$mail->Send()) + if(!$mail->send()) echo "There has been a mail error sending to " . $row["email"] . "<br>"; // Clear all addresses and attachments for next loop - $mail->ClearAddresses(); - $mail->ClearAttachments(); + $mail->clearAddresses(); + $mail->clearAttachments(); } @@ -90,7 +90,7 @@

2. Extending phpmailer

var $From = "from@example.com"; var $FromName = "Mailer"; var $Host = "smtp1.example.com;smtp2.example.com"; - var $Mailer = "smtp"; // Alternative to IsSMTP() + var $Mailer = "smtp"; // Alternative to isSMTP() var $WordWrap = 75; // Replace the default error_handler @@ -106,15 +106,14 @@

2. Extending phpmailer

// Place your new code here } } +
-Now here's a normal PHP page in the site, which will have all the defaults set -above:
+Now here's a normal PHP page in the site, which will have all the defaults set above:
Normal PHP file: mail_test.php -

@@ -126,12 +125,12 @@

2. Extending phpmailer

$mail = new my_phpmailer; // Now you only need to add the necessary stuff -$mail->AddAddress("josh@example.com", "Josh Adams"); +$mail->addAddress("josh@example.com", "Josh Adams"); $mail->Subject = "Here is the subject"; $mail->Body = "This is the message body"; -$mail->AddAttachment("c:/temp/11-10-00.zip", "new_name.zip"); // optional name +$mail->addAttachment("c:/temp/11-10-00.zip", "new_name.zip"); // optional name -if(!$mail->Send()) +if(!$mail->send()) { echo "There was an error sending the message"; exit; @@ -142,7 +141,5 @@

2. Extending phpmailer

-

- diff --git a/docs/generatedocs.sh b/docs/generatedocs.sh index e4d690bf6..f4d065f37 100755 --- a/docs/generatedocs.sh +++ b/docs/generatedocs.sh @@ -1,4 +1,5 @@ #!/bin/sh # Regenerate PHPMailer documentation +# Run from within the docs folder rm -rf phpdocs/* phpdoc --directory .. --target ./phpdoc --ignore test/,examples/,extras/,test_script/ --sourcecode --force --title PHPMailer diff --git a/docs/pop3_article.txt b/docs/pop3_article.txt index cc54f7c00..fb90b9c76 100644 --- a/docs/pop3_article.txt +++ b/docs/pop3_article.txt @@ -1,20 +1,33 @@ This is built for PHP Mailer 1.72 and was not tested with any previous version. It was developed under PHP 4.3.11 (E_ALL). It works under PHP 5 and 5.1 with E_ALL, but not in Strict mode due to var deprecation (but then neither does PHP Mailer either!). It follows the RFC 1939 standard explicitly and is fully commented. With that noted, here is how to implement it: -Install the class file -I didn't want to modify the PHP Mailer classes at all, so you will have to include/require this class along with the base one. It can sit quite happily in the phpmailer-1.72 directory: -[geshi lang=php] require 'phpmailer-1.72/class.phpmailer.php'; require 'phpmailer-1.72/class.pop3.php'; [/geshi] +I didn't want to modify the PHP Mailer classes at all, so you will have to include/require this class along with the base one. It can sit quite happily in the phpmailer directory. + When you need it, create your POP3 object Right before I invoke PHP Mailer I activate the POP3 authorisation. POP3 before SMTP is a process whereby you login to your web hosts POP3 mail server BEFORE sending out any emails via SMTP. The POP3 logon 'verifies' your ability to send email by SMTP, which typically otherwise blocks you. On my web host (Pair Networks) a single POP3 logon is enough to 'verify' you for 90 minutes. Here is some sample PHP code that activates the POP3 logon and then sends an email via PHP Mailer: -[geshi lang=php] Authorise('pop3.example.com', 110, 30, 'mailer', 'password', 1); $mail = new PHPMailer(); $mail->SMTPDebug = 2; $mail->IsSMTP(); $mail->IsHTML(false); $mail->Host = 'relay.example.com'; $mail->From = 'mailer@example.com'; $mail->FromName = 'Example Mailer'; $mail->Subject = 'My subject'; $mail->Body = 'Hello world'; $mail->AddAddress('rich@corephp.co.uk', 'Richard Davey'); if (!$mail->Send()) { echo $mail->ErrorInfo; } ?> [/geshi] -The PHP Mailer parts of this code should be obvious to anyone who has used PHP Mailer before. One thing to note - you almost certainly will not need to use SMTP Authentication *and* POP3 before SMTP together. The Authorisation method is a proxy method to all of the others within that class. There are Connect, Logon and Disconnect methods available, but I wrapped them in the single Authorisation one to make things easier. +authorise('pop3.example.com', 110, 30, 'mailer', 'password', 1); +$mail = new PHPMailer(); $mail->SMTPDebug = 2; $mail->isSMTP(); +$mail->isHTML(false); $mail->Host = 'relay.example.com'; +$mail->From = 'mailer@example.com'; +$mail->FromName = 'Example Mailer'; +$mail->Subject = 'My subject'; +$mail->Body = 'Hello world'; +$mail->addAddress('rich@corephp.co.uk', 'Richard Davey'); +if (!$mail->send()) { + echo $mail->ErrorInfo; +} +?> + +The PHP Mailer parts of this code should be obvious to anyone who has used PHP Mailer before. One thing to note - you almost certainly will not need to use SMTP Authentication *and* POP3 before SMTP together. The Authorisation method is a proxy method to all of the others within that class. There are connect, Logon and disconnect methods available, but I wrapped them in the single Authorisation one to make things easier. The Parameters -The Authorise parameters are as follows: -[geshi lang=php]$pop->Authorise('pop3.example.com', 110, 30, 'mailer', 'password', 1);[/geshi] +The authorise parameters are as follows: + +$pop->authorise('pop3.example.com', 110, 30, 'mailer', 'password', 1); 1. pop3.example.com - The POP3 Mail Server Name (hostname or IP address) 2. 110 - The POP3 Port on which to connect (default is usually 110, but check with your host) @@ -34,6 +47,4 @@ Final Comments + the Download 4) There are lots of other POP3 classes for PHP available. However most of them implement the full POP3 command set, where-as this one is purely for authentication, and much lighter as a result. However using any of the other POP3 classes to just logon to your server would have the same net result. At the end of the day, use whatever method you feel most comfortable with. Download -Here is the full class file plus my test script: POP_before_SMTP_PHPMailer.zip (4 KB) - Please note that it does not include PHPMailer itself. - My thanks to Chris Ryan for the inspiration (even if indirectly, via his SMTP class) diff --git a/examples/code_generator.phps b/examples/code_generator.phps index b9c79255f..4af07b3ae 100644 --- a/examples/code_generator.phps +++ b/examples/code_generator.phps @@ -3,40 +3,43 @@ * revised, updated and corrected 27/02/2013 * by matt.sturdy@gmail.com */ -require '../class.phpmailer.php'; +require '../PHPMailerAutoload.php'; -$CFG['smtp_debug'] = 2; //0 == off, 1 for client output, 2 for client and server -$CFG['smtp_debugoutput'] = 'html'; -$CFG['smtp_server'] = 'localhost'; -$CFG['smtp_port'] = '25'; +$CFG['smtp_debug'] = 2; //0 == off, 1 for client output, 2 for client and server +$CFG['smtp_debugoutput'] = 'html'; +$CFG['smtp_server'] = 'localhost'; +$CFG['smtp_port'] = '25'; $CFG['smtp_authenticate'] = false; -$CFG['smtp_username'] = 'name@example.com'; -$CFG['smtp_password'] = 'yourpassword'; -$CFG['smtp_secure'] = 'None'; - -$from_name = ( isset($_POST['From_Name'])) ? $_POST['From_Name'] : ''; -$from_email = ( isset($_POST['From_Email'])) ? $_POST['From_Email'] : ''; -$to_name = ( isset($_POST['To_Name'])) ? $_POST['To_Name'] : ''; -$to_email = ( isset($_POST['To_Email'])) ? $_POST['To_Email'] : ''; -$cc_email = ( isset($_POST['cc_Email'])) ? $_POST['cc_Email'] : ''; -$bcc_email = ( isset($_POST['bcc_Email'])) ? $_POST['bcc_Email'] : ''; -$subject = ( isset($_POST['Subject'])) ? $_POST['Subject'] : ''; -$message = ( isset($_POST['Message'])) ? $_POST['Message'] : ''; -$test_type = ( isset($_POST['test_type'])) ? $_POST['test_type'] : 'smtp'; -$smtp_debug = ( isset($_POST['smtp_debug'])) ? $_POST['smtp_debug'] : $CFG['smtp_debug']; -$smtp_server = ( isset($_POST['smtp_server'])) ? $_POST['smtp_server'] : $CFG['smtp_server']; -$smtp_port = ( isset($_POST['smtp_port'])) ? $_POST['smtp_port'] : $CFG['smtp_port']; -$smtp_secure = strtolower(( isset($_POST['smtp_secure'])) ? $_POST['smtp_secure'] : $CFG['smtp_secure']); -$smtp_authenticate = ( isset($_POST['smtp_authenticate'])) ? $_POST['smtp_authenticate'] : $CFG['smtp_authenticate']; -$authenticate_password = ( isset($_POST['authenticate_password'])) ? $_POST['authenticate_password'] : $CFG['smtp_password']; -$authenticate_username = ( isset($_POST['authenticate_username'])) ? $_POST['authenticate_username'] : $CFG['smtp_username']; +$CFG['smtp_username'] = 'name@example.com'; +$CFG['smtp_password'] = 'yourpassword'; +$CFG['smtp_secure'] = 'None'; + +$from_name = (isset($_POST['From_Name'])) ? $_POST['From_Name'] : ''; +$from_email = (isset($_POST['From_Email'])) ? $_POST['From_Email'] : ''; +$to_name = (isset($_POST['To_Name'])) ? $_POST['To_Name'] : ''; +$to_email = (isset($_POST['To_Email'])) ? $_POST['To_Email'] : ''; +$cc_email = (isset($_POST['cc_Email'])) ? $_POST['cc_Email'] : ''; +$bcc_email = (isset($_POST['bcc_Email'])) ? $_POST['bcc_Email'] : ''; +$subject = (isset($_POST['Subject'])) ? $_POST['Subject'] : ''; +$message = (isset($_POST['Message'])) ? $_POST['Message'] : ''; +$test_type = (isset($_POST['test_type'])) ? $_POST['test_type'] : 'smtp'; +$smtp_debug = (isset($_POST['smtp_debug'])) ? $_POST['smtp_debug'] : $CFG['smtp_debug']; +$smtp_server = (isset($_POST['smtp_server'])) ? $_POST['smtp_server'] : $CFG['smtp_server']; +$smtp_port = (isset($_POST['smtp_port'])) ? $_POST['smtp_port'] : $CFG['smtp_port']; +$smtp_secure = strtolower((isset($_POST['smtp_secure'])) ? $_POST['smtp_secure'] : $CFG['smtp_secure']); +$smtp_authenticate = (isset($_POST['smtp_authenticate'])) ? + $_POST['smtp_authenticate'] : $CFG['smtp_authenticate']; +$authenticate_password = (isset($_POST['authenticate_password'])) ? + $_POST['authenticate_password'] : $CFG['smtp_password']; +$authenticate_username = (isset($_POST['authenticate_username'])) ? + $_POST['authenticate_username'] : $CFG['smtp_username']; // storing all status output from the script to be shown to the user later $results_messages = array(); // $example_code represents the "final code" that we're using, and will // be shown to the user at the end. -$example_code = "\nrequire_once '../class.phpmailer.php';"; +$example_code = "\nrequire_once '../PHPMailerAutoload.php';"; $example_code .= "\n\n\$results_messages = array();"; $mail = new PHPMailer(true); //PHPMailer instance with exceptions enabled @@ -45,154 +48,159 @@ $mail->Debugoutput = $CFG['smtp_debugoutput']; $example_code .= "\n\n\$mail = new PHPMailer(true);"; $example_code .= "\n\$mail->CharSet = 'utf-8';"; -class phpmailerAppException extends phpmailerException {} +class phpmailerAppException extends phpmailerException +{ +} $example_code .= "\n\nclass phpmailerAppException extends phpmailerException {}"; $example_code .= "\n\ntry {"; try { - if ( isset($_POST["submit"]) && $_POST['submit'] == "Submit" ) { - $to = $_POST['To_Email']; - if (!PHPMailer::ValidateAddress($to)) { - throw new phpmailerAppException("Email address " . $to . " is invalid -- aborting!"); - } - - $example_code .= "\n\$to = '{$_POST['To_Email']}';"; - $example_code .= "\nif(!PHPMailer::ValidateAddress(\$to)) {"; - $example_code .= "\n throw new phpmailerAppException(\"Email address \" . \$to . \" is invalid -- aborting!\");"; - $example_code .= "\n}"; - - switch ($_POST['test_type']) { - case 'smtp': - $mail->IsSMTP(); // telling the class to use SMTP - $mail->SMTPDebug = (integer)$_POST['smtp_debug']; - $mail->Host = $_POST['smtp_server']; // SMTP server - $mail->Port = (integer)$_POST['smtp_port']; // set the SMTP port - if ($_POST['smtp_secure']) { - $mail->SMTPSecure = strtolower($_POST['smtp_secure']); - } - $mail->SMTPAuth = array_key_exists('smtp_authenticate', $_POST); // enable SMTP authentication? - if (array_key_exists('smtp_authenticate', $_POST)) { - $mail->Username = $_POST['authenticate_username']; // SMTP account username - $mail->Password = $_POST['authenticate_password']; // SMTP account password + if (isset($_POST["submit"]) && $_POST['submit'] == "Submit") { + $to = $_POST['To_Email']; + if (!PHPMailer::validateAddress($to)) { + throw new phpmailerAppException("Email address " . $to . " is invalid -- aborting!"); } - $example_code .= "\n\$mail->IsSMTP();"; - $example_code .= "\n\$mail->SMTPDebug = ".$_POST['smtp_debug'].";"; - $example_code .= "\n\$mail->Host = \"".$_POST['smtp_server']."\";"; - $example_code .= "\n\$mail->Port = \"".$_POST['smtp_port']."\";"; - $example_code .= "\n\$mail->SMTPSecure = \"".strtolower($_POST['smtp_secure'])."\";"; - $example_code .= "\n\$mail->SMTPAuth = ".(array_key_exists('smtp_authenticate', $_POST)?'true':'false').";"; - if (array_key_exists('smtp_authenticate', $_POST)) { - $example_code .= "\n\$mail->Username = \"".$_POST['authenticate_username']."\";"; - $example_code .= "\n\$mail->Password = \"".$_POST['authenticate_password']."\";"; + $example_code .= "\n\$to = '{$_POST['To_Email']}';"; + $example_code .= "\nif(!PHPMailer::validateAddress(\$to)) {"; + $example_code .= "\n throw new phpmailerAppException(\"Email address \" . " . + "\$to . \" is invalid -- aborting!\");"; + $example_code .= "\n}"; + + switch ($_POST['test_type']) { + case 'smtp': + $mail->isSMTP(); // telling the class to use SMTP + $mail->SMTPDebug = (integer)$_POST['smtp_debug']; + $mail->Host = $_POST['smtp_server']; // SMTP server + $mail->Port = (integer)$_POST['smtp_port']; // set the SMTP port + if ($_POST['smtp_secure']) { + $mail->SMTPSecure = strtolower($_POST['smtp_secure']); + } + $mail->SMTPAuth = array_key_exists('smtp_authenticate', $_POST); // enable SMTP authentication? + if (array_key_exists('smtp_authenticate', $_POST)) { + $mail->Username = $_POST['authenticate_username']; // SMTP account username + $mail->Password = $_POST['authenticate_password']; // SMTP account password + } + + $example_code .= "\n\$mail->isSMTP();"; + $example_code .= "\n\$mail->SMTPDebug = " . $_POST['smtp_debug'] . ";"; + $example_code .= "\n\$mail->Host = \"" . $_POST['smtp_server'] . "\";"; + $example_code .= "\n\$mail->Port = \"" . $_POST['smtp_port'] . "\";"; + $example_code .= "\n\$mail->SMTPSecure = \"" . strtolower($_POST['smtp_secure']) . "\";"; + $example_code .= "\n\$mail->SMTPAuth = " . (array_key_exists( + 'smtp_authenticate', + $_POST + ) ? 'true' : 'false') . ";"; + if (array_key_exists('smtp_authenticate', $_POST)) { + $example_code .= "\n\$mail->Username = \"" . $_POST['authenticate_username'] . "\";"; + $example_code .= "\n\$mail->Password = \"" . $_POST['authenticate_password'] . "\";"; + } + break; + case 'mail': + $mail->isMail(); // telling the class to use PHP's mail() + $example_code .= "\n\$mail->isMail();"; + break; + case 'sendmail': + $mail->isSendmail(); // telling the class to use Sendmail + $example_code .= "\n\$mail->isSendmail();"; + break; + case 'qmail': + $mail->isQmail(); // telling the class to use Qmail + $example_code .= "\n\$mail->isQmail();"; + break; + default: + throw new phpmailerAppException('Invalid test_type provided'); } - break; - case 'mail': - $mail->IsMail(); // telling the class to use PHP's Mail() - $example_code .= "\n\$mail->IsMail();"; - break; - case 'sendmail': - $mail->IsSendmail(); // telling the class to use Sendmail - $example_code .= "\n\$mail->IsSendmail();"; - break; - case 'qmail': - $mail->IsQmail(); // telling the class to use Qmail - $example_code .= "\n\$mail->IsQmail();"; - break; - default: - throw new phpmailerAppException('Invalid test_type provided'); - } - try { - if ( $_POST['From_Name'] != '' ) { - $mail->AddReplyTo($_POST['From_Email'], $_POST['From_Name']); - $mail->From = $_POST['From_Email']; - $mail->FromName = $_POST['From_Name']; - - $example_code .= "\n\$mail->AddReplyTo(\"".$_POST['From_Email']."\", \"".$_POST['From_Name']."\");"; - $example_code .= "\n\$mail->From = \"".$_POST['From_Email']."\";"; - $example_code .= "\n\$mail->FromName = \"".$_POST['From_Name']."\";"; - } - else { - $mail->AddReplyTo($_POST['From_Email']); - $mail->From = $_POST['From_Email']; - $mail->FromName = $_POST['From_Email']; - - $example_code .= "\n\$mail->AddReplyTo(\"".$_POST['From_Email']."\");"; - $example_code .= "\n\$mail->From = \"".$_POST['From_Email']."\";"; - $example_code .= "\n\$mail->FromName = \"".$_POST['From_Email']."\";"; - } - - if ( $_POST['To_Name'] != '' ) { - $mail->AddAddress($to, $_POST['To_Name']); - $example_code .= "\n\$mail->AddAddress(\"$to\", \"".$_POST['To_Name']."\");"; - } - else { - $mail->AddAddress($to); - $example_code .= "\n\$mail->AddAddress(\"$to\");"; - } - - if ( $_POST['bcc_Email'] != '' ) { - $indiBCC = explode(" ", $_POST['bcc_Email']); - foreach ($indiBCC as $key => $value) { - $mail->AddBCC($value); - $example_code .= "\n\$mail->AddBCC(\"$value\");"; + try { + if ($_POST['From_Name'] != '') { + $mail->addReplyTo($_POST['From_Email'], $_POST['From_Name']); + $mail->From = $_POST['From_Email']; + $mail->FromName = $_POST['From_Name']; + + $example_code .= "\n\$mail->addReplyTo(\"" . + $_POST['From_Email'] . "\", \"" . $_POST['From_Name'] . "\");"; + $example_code .= "\n\$mail->From = \"" . $_POST['From_Email'] . "\";"; + $example_code .= "\n\$mail->FromName = \"" . $_POST['From_Name'] . "\";"; + } else { + $mail->addReplyTo($_POST['From_Email']); + $mail->From = $_POST['From_Email']; + $mail->FromName = $_POST['From_Email']; + + $example_code .= "\n\$mail->addReplyTo(\"" . $_POST['From_Email'] . "\");"; + $example_code .= "\n\$mail->From = \"" . $_POST['From_Email'] . "\";"; + $example_code .= "\n\$mail->FromName = \"" . $_POST['From_Email'] . "\";"; + } + + if ($_POST['To_Name'] != '') { + $mail->addAddress($to, $_POST['To_Name']); + $example_code .= "\n\$mail->addAddress(\"$to\", \"" . $_POST['To_Name'] . "\");"; + } else { + $mail->addAddress($to); + $example_code .= "\n\$mail->addAddress(\"$to\");"; + } + + if ($_POST['bcc_Email'] != '') { + $indiBCC = explode(" ", $_POST['bcc_Email']); + foreach ($indiBCC as $key => $value) { + $mail->addBCC($value); + $example_code .= "\n\$mail->addBCC(\"$value\");"; + } + } + + if ($_POST['cc_Email'] != '') { + $indiCC = explode(" ", $_POST['cc_Email']); + foreach ($indiCC as $key => $value) { + $mail->addCC($value); + $example_code .= "\n\$mail->addCC(\"$value\");"; + } + } + } catch (phpmailerException $e) { //Catch all kinds of bad addressing + throw new phpmailerAppException($e->getMessage()); } - } - - if ( $_POST['cc_Email'] != '' ) { - $indiCC = explode(" ", $_POST['cc_Email']); - foreach ($indiCC as $key => $value) { - $mail->AddCC($value); - $example_code .= "\n\$mail->AddCC(\"$value\");"; + $mail->Subject = $_POST['Subject'] . ' (PHPMailer test using ' . strtoupper($_POST['test_type']) . ')'; + $example_code .= "\n\$mail->Subject = \"" . $_POST['Subject'] . + '(PHPMailer test using ' . strtoupper($_POST['test_type']) . ')";'; + + if ($_POST['Message'] == '') { + $body = file_get_contents('contents.html'); + } else { + $body = $_POST['Message']; } - } - } - catch (phpmailerException $e) { //Catch all kinds of bad addressing - throw new phpmailerAppException($e->getMessage()); - } - $mail->Subject = $_POST['Subject'] . ' (PHPMailer test using ' . strtoupper($_POST['test_type']) . ')'; - $example_code .= "\n\$mail->Subject = \"".$_POST['Subject'].'(PHPMailer test using ' . strtoupper($_POST['test_type']) . ')";'; - if ( $_POST['Message'] == '' ) { - $body = file_get_contents('contents.html'); - } else { - $body = $_POST['Message']; - } + $example_code .= "\n\$body = <<<'EOT'\n" . htmlentities($body) . "\nEOT;"; - $example_code .= "\n\$body = <<<'EOT'\n".htmlentities($body)."\nEOT;"; + $mail->WordWrap = 80; // set word wrap + $mail->msgHTML($body, dirname(__FILE__), true); //Create message bodies and embed images - $mail->WordWrap = 80; // set word wrap - $mail->MsgHTML($body, dirname(__FILE__), true); //Create message bodies and embed images + $example_code .= "\n\$mail->WordWrap = 80;"; + $example_code .= "\n\$mail->msgHTML(\$body, dirname(__FILE__), true); //Create message bodies and embed images"; - $example_code .= "\n\$mail->WordWrap = 80;"; - $example_code .= "\n\$mail->MsgHTML(\$body, dirname(__FILE__), true); //Create message bodies and embed images"; + $mail->addAttachment('images/phpmailer_mini.gif', 'phpmailer_mini.gif'); // optional name + $mail->addAttachment('images/phpmailer.png', 'phpmailer.png'); // optional name + $example_code .= "\n\$mail->addAttachment('images/phpmailer_mini.gif'," . + "'phpmailer_mini.gif'); // optional name"; + $example_code .= "\n\$mail->addAttachment('images/phpmailer.png', 'phpmailer.png'); // optional name"; - $mail->AddAttachment('images/phpmailer_mini.gif', 'phpmailer_mini.gif'); // optional name - $mail->AddAttachment('images/phpmailer.png', 'phpmailer.png'); // optional name - $example_code .= "\n\$mail->AddAttachment('images/phpmailer_mini.gif', 'phpmailer_mini.gif'); // optional name"; - $example_code .= "\n\$mail->AddAttachment('images/phpmailer.png', 'phpmailer.png'); // optional name"; + try { + $mail->send(); + $results_messages[] = "Message has been sent using " . strtoupper($_POST["test_type"]); + } catch (phpmailerException $e) { + throw new phpmailerAppException("Unable to send to: " . $to . ': ' . $e->getMessage()); + } - try { - $mail->Send(); - $results_messages[] = "Message has been sent using " . strtoupper($_POST["test_type"]); - } - catch (phpmailerException $e) { - throw new phpmailerAppException("Unable to send to: " . $to. ': '.$e->getMessage()); + $example_code .= "\n\ntry {"; + $example_code .= "\n \$mail->send();"; + $example_code .= "\n \$results_messages[] = \"Message has been sent using " . + strtoupper($_POST['test_type']) . "\";"; + $example_code .= "\n}"; + $example_code .= "\ncatch (phpmailerException \$e) {"; + $example_code .= "\n throw new phpmailerAppException('Unable to send to: ' . \$to. ': '.\$e->getMessage());"; + $example_code .= "\n}"; } - - $example_code .= "\n\ntry {"; - $example_code .= "\n \$mail->Send();"; - $example_code .= "\n \$results_messages[] = \"Message has been sent using ". strtoupper($_POST['test_type'])."\";"; - $example_code .= "\n}"; - $example_code .= "\ncatch (phpmailerException \$e) {"; - $example_code .= "\n throw new phpmailerAppException('Unable to send to: ' . \$to. ': '.\$e->getMessage());"; - $example_code .= "\n}"; - } -} -catch (phpmailerAppException $e) { - $results_messages[] = $e->errorMessage(); +} catch (phpmailerAppException $e) { + $results_messages[] = $e->errorMessage(); } $example_code .= "\n}"; $example_code .= "\ncatch (phpmailerAppException \$e) {"; @@ -209,319 +217,380 @@ $example_code .= "\n}"; ?> - - PHPMailer Test Page - - - - - - + + + + + - "; - echo exit("ERROR: Wrong PHP version. Must be PHP 5 or above."); - } +"; + echo exit("ERROR: Wrong PHP version. Must be PHP 5 or above."); +} - if (count($results_messages) > 0) { - echo '

Run results

'; - echo '
    '; - foreach ($results_messages as $result) { +if (count($results_messages) > 0) { + echo '

    Run results

    '; + echo '
      '; + foreach ($results_messages as $result) { echo "
    • $result
    • "; - } - echo '
    '; } + echo '
'; +} - if (isset($_POST["submit"]) && $_POST["submit"] == "Submit") { - echo "
\n"; - echo "
Script:\n"; - echo "
\n";
-        echo $example_code;
-        echo "\n
\n"; - echo "\n
\n"; - } - ?> -
+if (isset($_POST["submit"]) && $_POST["submit"] == "Submit") { + echo "
\n"; + echo "
Script:\n"; + echo "
\n";
+    echo $example_code;
+    echo "\n
\n"; + echo "\n
\n"; +} +?> +
-
-
- Mail Details - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - -
- - - -
- - - -
- - - -
- - - -
- - - -
- - - -
- - - -
-
Test will include two attachments.
-
-
-
-
- Mail Test Specs - - - - - -
Test Type -
- - required> -
-
- - required> -
-
- - required> -
-
- - required> +
+
+ Mail Details + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + +
+ + + +
+ + + +
+ + + +
+ + + +
+ + + +
+ + + +
+ + + +
+
Test will include two attachments.
+
+
+
+
+ Mail Test Specs + + + + + +
Test Type +
+ + + required> +
+
+ + + required> +
+
+ + + required> +
+
+ + + required> +
+
+
"> + SMTP Specific Options: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+ +
+ +
+ + value=""> +
+ +
+ +
-
-
"> - SMTP Specific Options: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -
- -
- -
- -
- value=""> -
- -
- -
-
-
-
-
-
-
- + +
+
+ +
+
+ +
+
- -
-
+ \ No newline at end of file diff --git a/examples/exceptions.phps b/examples/exceptions.phps index 633cb4858..a4b3224d1 100644 --- a/examples/exceptions.phps +++ b/examples/exceptions.phps @@ -1,40 +1,40 @@ - - PHPMailer - Exceptions test + + PHPMailer - Exceptions test SetFrom('from@example.com', 'First Last'); - //Set an alternative reply-to address - $mail->AddReplyTo('replyto@example.com','First Last'); - //Set who the message is to be sent to - $mail->AddAddress('whoto@example.com', 'John Doe'); - //Set the subject line - $mail->Subject = 'PHPMailer Exceptions test'; - //Read an HTML message body from an external file, convert referenced images to embedded, - //and convert the HTML into a basic plain-text alternative body - $mail->MsgHTML(file_get_contents('contents.html'), dirname(__FILE__)); - //Replace the plain text body with one created manually - $mail->AltBody = 'This is a plain-text message body'; - //Attach an image file - $mail->AddAttachment('images/phpmailer_mini.gif'); - //Send the message - //Note that we don't need check the response from this because it will throw an exception if it has trouble - $mail->Send(); - echo "Message sent!"; + //Set who the message is to be sent from + $mail->setFrom('from@example.com', 'First Last'); + //Set an alternative reply-to address + $mail->addReplyTo('replyto@example.com', 'First Last'); + //Set who the message is to be sent to + $mail->addAddress('whoto@example.com', 'John Doe'); + //Set the subject line + $mail->Subject = 'PHPMailer Exceptions test'; + //Read an HTML message body from an external file, convert referenced images to embedded, + //and convert the HTML into a basic plain-text alternative body + $mail->msgHTML(file_get_contents('contents.html'), dirname(__FILE__)); + //Replace the plain text body with one created manually + $mail->AltBody = 'This is a plain-text message body'; + //Attach an image file + $mail->addAttachment('images/phpmailer_mini.gif'); + //send the message + //Note that we don't need check the response from this because it will throw an exception if it has trouble + $mail->send(); + echo "Message sent!"; } catch (phpmailerException $e) { - echo $e->errorMessage(); //Pretty error messages from PHPMailer + echo $e->errorMessage(); //Pretty error messages from PHPMailer } catch (Exception $e) { - echo $e->getMessage(); //Boring error messages from anything else! + echo $e->getMessage(); //Boring error messages from anything else! } ?> diff --git a/examples/gmail.phps b/examples/gmail.phps index 2883a3849..a1b403ffd 100644 --- a/examples/gmail.phps +++ b/examples/gmail.phps @@ -1,8 +1,8 @@ - - PHPMailer - GMail SMTP test + + PHPMailer - GMail SMTP test IsSMTP(); +$mail->isSMTP(); //Enable SMTP debugging // 0 = off (for production use) // 1 = client messages // 2 = client and server messages -$mail->SMTPDebug = 2; +$mail->SMTPDebug = 2; //Ask for HTML-friendly debug output $mail->Debugoutput = 'html'; //Set the hostname of the mail server -$mail->Host = 'smtp.gmail.com'; +$mail->Host = 'smtp.gmail.com'; //Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission -$mail->Port = 587; +$mail->Port = 587; //Set the encryption system to use - ssl (deprecated) or tls $mail->SMTPSecure = 'tls'; //Whether to use SMTP authentication -$mail->SMTPAuth = true; +$mail->SMTPAuth = true; //Username to use for SMTP authentication - use full email address for gmail -$mail->Username = "username@gmail.com"; +$mail->Username = "username@gmail.com"; //Password to use for SMTP authentication -$mail->Password = "yourpassword"; +$mail->Password = "yourpassword"; //Set who the message is to be sent from -$mail->SetFrom('from@example.com', 'First Last'); +$mail->setFrom('from@example.com', 'First Last'); //Set an alternative reply-to address -$mail->AddReplyTo('replyto@example.com','First Last'); +$mail->addReplyTo('replyto@example.com', 'First Last'); //Set who the message is to be sent to -$mail->AddAddress('whoto@example.com', 'John Doe'); +$mail->addAddress('whoto@example.com', 'John Doe'); //Set the subject line $mail->Subject = 'PHPMailer GMail SMTP test'; -//Read an HTML message body from an external file, convert referenced images to embedded, convert HTML into a basic plain-text alternative body -$mail->MsgHTML(file_get_contents('contents.html'), dirname(__FILE__)); +//Read an HTML message body from an external file, convert referenced images to embedded, +//convert HTML into a basic plain-text alternative body +$mail->msgHTML(file_get_contents('contents.html'), dirname(__FILE__)); //Replace the plain text body with one created manually $mail->AltBody = 'This is a plain-text message body'; //Attach an image file -$mail->AddAttachment('images/phpmailer_mini.gif'); +$mail->addAttachment('images/phpmailer_mini.gif'); -//Send the message, check for errors -if(!$mail->Send()) { - echo "Mailer Error: " . $mail->ErrorInfo; +//send the message, check for errors +if (!$mail->send()) { + echo "Mailer Error: " . $mail->ErrorInfo; } else { - echo "Message sent!"; + echo "Message sent!"; } ?> diff --git a/examples/mail.phps b/examples/mail.phps index 7a99cec38..fcc8ef9dc 100644 --- a/examples/mail.phps +++ b/examples/mail.phps @@ -1,35 +1,36 @@ - - PHPMailer - mail() test + + PHPMailer - mail() test SetFrom('from@example.com', 'First Last'); +$mail->setFrom('from@example.com', 'First Last'); //Set an alternative reply-to address -$mail->AddReplyTo('replyto@example.com','First Last'); +$mail->addReplyTo('replyto@example.com', 'First Last'); //Set who the message is to be sent to -$mail->AddAddress('whoto@example.com', 'John Doe'); +$mail->addAddress('whoto@example.com', 'John Doe'); //Set the subject line $mail->Subject = 'PHPMailer mail() test'; -//Read an HTML message body from an external file, convert referenced images to embedded, convert HTML into a basic plain-text alternative body -$mail->MsgHTML(file_get_contents('contents.html'), dirname(__FILE__)); +//Read an HTML message body from an external file, convert referenced images to embedded, +//convert HTML into a basic plain-text alternative body +$mail->msgHTML(file_get_contents('contents.html'), dirname(__FILE__)); //Replace the plain text body with one created manually $mail->AltBody = 'This is a plain-text message body'; //Attach an image file -$mail->AddAttachment('images/phpmailer_mini.gif'); +$mail->addAttachment('images/phpmailer_mini.gif'); -//Send the message, check for errors -if(!$mail->Send()) { - echo "Mailer Error: " . $mail->ErrorInfo; +//send the message, check for errors +if (!$mail->send()) { + echo "Mailer Error: " . $mail->ErrorInfo; } else { - echo "Message sent!"; + echo "Message sent!"; } ?> diff --git a/examples/mailing_list.phps b/examples/mailing_list.phps index 8fbd838c7..8d0fc5fcd 100644 --- a/examples/mailing_list.phps +++ b/examples/mailing_list.phps @@ -1,49 +1,51 @@ IsSMTP(); -$mail->Host = 'smtp.example.com'; -$mail->SMTPAuth = true; -$mail->SMTPKeepAlive = true; // SMTP connection will not close after each email sent, reduces SMTP overhead -$mail->Host = 'mail.example.com'; -$mail->Port = 25; -$mail->Username = 'yourname@example.com'; -$mail->Password = 'yourpassword'; -$mail->SetFrom('list@example.com', 'List manager'); -$mail->AddReplyTo('list@example.com', 'List manager'); +$mail->isSMTP(); +$mail->Host = 'smtp.example.com'; +$mail->SMTPAuth = true; +$mail->SMTPKeepAlive = true; // SMTP connection will not close after each email sent, reduces SMTP overhead +$mail->Host = 'mail.example.com'; +$mail->Port = 25; +$mail->Username = 'yourname@example.com'; +$mail->Password = 'yourpassword'; +$mail->setFrom('list@example.com', 'List manager'); +$mail->addReplyTo('list@example.com', 'List manager'); -$mail->Subject = "PHPMailer Simple database mailing list test"; +$mail->Subject = "PHPMailer Simple database mailing list test"; -//Connect to the database and select the recipients from your mailing list that have not yet been sent to +//connect to the database and select the recipients from your mailing list that have not yet been sent to //You'll need to alter this to match your database $mysql = mysql_connect('localhost', 'username', 'password'); mysql_select_db('mydb', $mysql); $result = mysql_query("SELECT full_name, email, photo FROM mailinglist WHERE sent = false", $mysql); while ($row = mysql_fetch_array($result)) { - $mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; - $mail->MsgHTML($body); - $mail->AddAddress($row['email'], $row['full_name']); - $mail->AddStringAttachment($row['photo'], 'YourPhoto.jpg'); //Assumes the image data is stored in the DB - - if(!$mail->Send()) { - echo "Mailer Error (" . str_replace("@", "@", $row["email"]) . ') ' . $mail->ErrorInfo . '
'; - break; //Abandon sending - } else { - echo "Message sent to :" . $row['full_name'] . ' (' . str_replace("@", "@", $row['email']) . ')
'; - //Mark it as sent in the DB - mysql_query("UPDATE mailinglist SET sent = true WHERE email = '".mysql_real_escape_string($row['email'], $mysql)."'"); - } - // Clear all addresses and attachments for next loop - $mail->ClearAddresses(); - $mail->ClearAttachments(); + $mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; + $mail->msgHTML($body); + $mail->addAddress($row['email'], $row['full_name']); + $mail->addStringAttachment($row['photo'], 'YourPhoto.jpg'); //Assumes the image data is stored in the DB + + if (!$mail->send()) { + echo "Mailer Error (" . str_replace("@", "@", $row["email"]) . ') ' . $mail->ErrorInfo . '
'; + break; //Abandon sending + } else { + echo "Message sent to :" . $row['full_name'] . ' (' . str_replace("@", "@", $row['email']) . ')
'; + //Mark it as sent in the DB + mysql_query( + "UPDATE mailinglist SET sent = true WHERE email = '" . mysql_real_escape_string($row['email'], $mysql) . "'" + ); + } + // Clear all addresses and attachments for next loop + $mail->clearAddresses(); + $mail->clearAttachments(); } diff --git a/examples/pop_before_smtp.phps b/examples/pop_before_smtp.phps index e69d3242a..68a96b851 100644 --- a/examples/pop_before_smtp.phps +++ b/examples/pop_before_smtp.phps @@ -1,18 +1,17 @@ - - PHPMailer - POP-before-SMTP test + + PHPMailer - POP-before-SMTP test Authorise('pop3.yourdomain.com', 110, 30, 'username', 'password', 1); +//authenticate via POP +$pop->authorise('pop3.yourdomain.com', 110, 30, 'username', 'password', 1); //Now you should be clear to submit messages over SMTP for a while //Only applies if your host supports POP-before-SMTP @@ -20,43 +19,43 @@ $pop->Authorise('pop3.yourdomain.com', 110, 30, 'username', 'password', 1); //Passing true to the constructor enables the use of exceptions for error handling $mail = new PHPMailer(true); try { - $mail->IsSMTP(); - //Enable SMTP debugging - // 0 = off (for production use) - // 1 = client messages - // 2 = client and server messages - $mail->SMTPDebug = 2; - //Ask for HTML-friendly debug output - $mail->Debugoutput = 'html'; - //Set the hostname of the mail server - $mail->Host = "mail.example.com"; - //Set the SMTP port number - likely to be 25, 465 or 587 - $mail->Port = 25; - //Whether to use SMTP authentication - $mail->SMTPAuth = false; - //Set who the message is to be sent from - $mail->SetFrom('from@example.com', 'First Last'); - //Set an alternative reply-to address - $mail->AddReplyTo('replyto@example.com','First Last'); - //Set who the message is to be sent to - $mail->AddAddress('whoto@example.com', 'John Doe'); - //Set the subject line - $mail->Subject = 'PHPMailer POP-before-SMTP test'; - //Read an HTML message body from an external file, convert referenced images to embedded, - //and convert the HTML into a basic plain-text alternative body - $mail->MsgHTML(file_get_contents('contents.html'), dirname(__FILE__)); - //Replace the plain text body with one created manually - $mail->AltBody = 'This is a plain-text message body'; - //Attach an image file - $mail->AddAttachment('images/phpmailer_mini.gif'); - //Send the message - //Note that we don't need check the response from this because it will throw an exception if it has trouble - $mail->Send(); - echo "Message sent!"; + $mail->isSMTP(); + //Enable SMTP debugging + // 0 = off (for production use) + // 1 = client messages + // 2 = client and server messages + $mail->SMTPDebug = 2; + //Ask for HTML-friendly debug output + $mail->Debugoutput = 'html'; + //Set the hostname of the mail server + $mail->Host = "mail.example.com"; + //Set the SMTP port number - likely to be 25, 465 or 587 + $mail->Port = 25; + //Whether to use SMTP authentication + $mail->SMTPAuth = false; + //Set who the message is to be sent from + $mail->setFrom('from@example.com', 'First Last'); + //Set an alternative reply-to address + $mail->addReplyTo('replyto@example.com', 'First Last'); + //Set who the message is to be sent to + $mail->addAddress('whoto@example.com', 'John Doe'); + //Set the subject line + $mail->Subject = 'PHPMailer POP-before-SMTP test'; + //Read an HTML message body from an external file, convert referenced images to embedded, + //and convert the HTML into a basic plain-text alternative body + $mail->msgHTML(file_get_contents('contents.html'), dirname(__FILE__)); + //Replace the plain text body with one created manually + $mail->AltBody = 'This is a plain-text message body'; + //Attach an image file + $mail->addAttachment('images/phpmailer_mini.gif'); + //send the message + //Note that we don't need check the response from this because it will throw an exception if it has trouble + $mail->send(); + echo "Message sent!"; } catch (phpmailerException $e) { - echo $e->errorMessage(); //Pretty error messages from PHPMailer + echo $e->errorMessage(); //Pretty error messages from PHPMailer } catch (Exception $e) { - echo $e->getMessage(); //Boring error messages from anything else! + echo $e->getMessage(); //Boring error messages from anything else! } ?> diff --git a/examples/sendmail.phps b/examples/sendmail.phps index 3185a3b2b..9e080386e 100644 --- a/examples/sendmail.phps +++ b/examples/sendmail.phps @@ -1,37 +1,38 @@ - - PHPMailer - sendmail test + + PHPMailer - sendmail test IsSendmail(); +$mail->isSendmail(); //Set who the message is to be sent from -$mail->SetFrom('from@example.com', 'First Last'); +$mail->setFrom('from@example.com', 'First Last'); //Set an alternative reply-to address -$mail->AddReplyTo('replyto@example.com','First Last'); +$mail->addReplyTo('replyto@example.com', 'First Last'); //Set who the message is to be sent to -$mail->AddAddress('whoto@example.com', 'John Doe'); +$mail->addAddress('whoto@example.com', 'John Doe'); //Set the subject line $mail->Subject = 'PHPMailer sendmail test'; -//Read an HTML message body from an external file, convert referenced images to embedded, convert HTML into a basic plain-text alternative body -$mail->MsgHTML(file_get_contents('contents.html'), dirname(__FILE__)); +//Read an HTML message body from an external file, convert referenced images to embedded, +//convert HTML into a basic plain-text alternative body +$mail->msgHTML(file_get_contents('contents.html'), dirname(__FILE__)); //Replace the plain text body with one created manually $mail->AltBody = 'This is a plain-text message body'; //Attach an image file -$mail->AddAttachment('images/phpmailer_mini.gif'); +$mail->addAttachment('images/phpmailer_mini.gif'); -//Send the message, check for errors -if(!$mail->Send()) { - echo "Mailer Error: " . $mail->ErrorInfo; +//send the message, check for errors +if (!$mail->send()) { + echo "Mailer Error: " . $mail->ErrorInfo; } else { - echo "Message sent!"; + echo "Message sent!"; } ?> diff --git a/examples/smtp.phps b/examples/smtp.phps index 69fe05656..b0ddd3d43 100644 --- a/examples/smtp.phps +++ b/examples/smtp.phps @@ -1,8 +1,8 @@ - - PHPMailer - SMTP test + + PHPMailer - SMTP test IsSMTP(); +$mail->isSMTP(); //Enable SMTP debugging // 0 = off (for production use) // 1 = client messages // 2 = client and server messages -$mail->SMTPDebug = 2; +$mail->SMTPDebug = 2; //Ask for HTML-friendly debug output $mail->Debugoutput = 'html'; //Set the hostname of the mail server -$mail->Host = "mail.example.com"; +$mail->Host = "mail.example.com"; //Set the SMTP port number - likely to be 25, 465 or 587 -$mail->Port = 25; +$mail->Port = 25; //Whether to use SMTP authentication -$mail->SMTPAuth = true; +$mail->SMTPAuth = true; //Username to use for SMTP authentication -$mail->Username = "yourname@example.com"; +$mail->Username = "yourname@example.com"; //Password to use for SMTP authentication -$mail->Password = "yourpassword"; +$mail->Password = "yourpassword"; //Set who the message is to be sent from -$mail->SetFrom('from@example.com', 'First Last'); +$mail->setFrom('from@example.com', 'First Last'); //Set an alternative reply-to address -$mail->AddReplyTo('replyto@example.com','First Last'); +$mail->addReplyTo('replyto@example.com', 'First Last'); //Set who the message is to be sent to -$mail->AddAddress('whoto@example.com', 'John Doe'); +$mail->addAddress('whoto@example.com', 'John Doe'); //Set the subject line $mail->Subject = 'PHPMailer SMTP test'; -//Read an HTML message body from an external file, convert referenced images to embedded, convert HTML into a basic plain-text alternative body -$mail->MsgHTML(file_get_contents('contents.html'), dirname(__FILE__)); +//Read an HTML message body from an external file, convert referenced images to embedded, +//convert HTML into a basic plain-text alternative body +$mail->msgHTML(file_get_contents('contents.html'), dirname(__FILE__)); //Replace the plain text body with one created manually $mail->AltBody = 'This is a plain-text message body'; //Attach an image file -$mail->AddAttachment('images/phpmailer_mini.gif'); +$mail->addAttachment('images/phpmailer_mini.gif'); -//Send the message, check for errors -if(!$mail->Send()) { - echo "Mailer Error: " . $mail->ErrorInfo; +//send the message, check for errors +if (!$mail->send()) { + echo "Mailer Error: " . $mail->ErrorInfo; } else { - echo "Message sent!"; + echo "Message sent!"; } ?> diff --git a/examples/smtp_no_auth.phps b/examples/smtp_no_auth.phps index ed89136d2..f0a88dcda 100644 --- a/examples/smtp_no_auth.phps +++ b/examples/smtp_no_auth.phps @@ -1,8 +1,8 @@ - - PHPMailer - SMTP without auth test + + PHPMailer - SMTP without auth test IsSMTP(); +$mail->isSMTP(); //Enable SMTP debugging // 0 = off (for production use) // 1 = client messages // 2 = client and server messages -$mail->SMTPDebug = 2; +$mail->SMTPDebug = 2; //Ask for HTML-friendly debug output $mail->Debugoutput = 'html'; //Set the hostname of the mail server -$mail->Host = "mail.example.com"; +$mail->Host = "mail.example.com"; //Set the SMTP port number - likely to be 25, 465 or 587 -$mail->Port = 25; +$mail->Port = 25; //Whether to use SMTP authentication -$mail->SMTPAuth = false; +$mail->SMTPAuth = false; //Set who the message is to be sent from -$mail->SetFrom('from@example.com', 'First Last'); +$mail->setFrom('from@example.com', 'First Last'); //Set an alternative reply-to address -$mail->AddReplyTo('replyto@example.com','First Last'); +$mail->addReplyTo('replyto@example.com', 'First Last'); //Set who the message is to be sent to -$mail->AddAddress('whoto@example.com', 'John Doe'); +$mail->addAddress('whoto@example.com', 'John Doe'); //Set the subject line $mail->Subject = 'PHPMailer SMTP without auth test'; -//Read an HTML message body from an external file, convert referenced images to embedded, convert HTML into a basic plain-text alternative body -$mail->MsgHTML(file_get_contents('contents.html'), dirname(__FILE__)); +//Read an HTML message body from an external file, convert referenced images to embedded, +//convert HTML into a basic plain-text alternative body +$mail->msgHTML(file_get_contents('contents.html'), dirname(__FILE__)); //Replace the plain text body with one created manually $mail->AltBody = 'This is a plain-text message body'; //Attach an image file -$mail->AddAttachment('images/phpmailer_mini.gif'); +$mail->addAttachment('images/phpmailer_mini.gif'); -//Send the message, check for errors -if(!$mail->Send()) { - echo "Mailer Error: " . $mail->ErrorInfo; +//send the message, check for errors +if (!$mail->send()) { + echo "Mailer Error: " . $mail->ErrorInfo; } else { - echo "Message sent!"; + echo "Message sent!"; } ?> diff --git a/language/phpmailer.lang-fr.php b/language/phpmailer.lang-fr.php index b8dfc7743..2d23cf511 100644 --- a/language/phpmailer.lang-fr.php +++ b/language/phpmailer.lang-fr.php @@ -1,24 +1,29 @@ Mail->Username = ""; $this->Mail->Password = ""; $this->Mail->PluginDir = $this->INCLUDE_DIR; - $this->Mail->AddReplyTo("no_reply@phpmailer.example.com", "Reply Guy"); + $this->Mail->addReplyTo("no_reply@phpmailer.example.com", "Reply Guy"); $this->Mail->Sender = "unit_test@phpmailer.example.com"; if (strlen($this->Mail->Host) > 0) { @@ -105,17 +105,17 @@ function setUp() } if (array_key_exists('mail_to', $_REQUEST)) { - $this->SetAddress($_REQUEST['mail_to'], 'Test User', 'to'); + $this->setAddress($_REQUEST['mail_to'], 'Test User', 'to'); } if (array_key_exists('mail_cc', $_REQUEST) and strlen($_REQUEST['mail_cc']) > 0) { - $this->SetAddress($_REQUEST['mail_cc'], 'Carbon User', 'cc'); + $this->setAddress($_REQUEST['mail_cc'], 'Carbon User', 'cc'); } } /** * Run after each test is completed. */ - function tearDown() + public function tearDown() { // Clean global variables $this->Mail = null; @@ -129,7 +129,7 @@ function tearDown() * @private * @returns void */ - function BuildBody() + public function buildBody() { $this->CheckChanges(); @@ -159,7 +159,7 @@ function BuildBody() } // If attachments then create an attachment list - $attachments = $this->Mail->GetAttachments(); + $attachments = $this->Mail->getAttachments(); if (count($attachments) > 0) { $ReportBody .= "Attachments:" . $eol; $ReportBody .= $bullet_start; @@ -205,34 +205,34 @@ function BuildBody() * @private * @returns void */ - function CheckChanges() + public function checkChanges() { if ($this->Mail->Priority != 3) { - $this->AddChange("Priority", $this->Mail->Priority); + $this->addChange("Priority", $this->Mail->Priority); } if ($this->Mail->Encoding != "8bit") { - $this->AddChange("Encoding", $this->Mail->Encoding); + $this->addChange("Encoding", $this->Mail->Encoding); } if ($this->Mail->CharSet != "iso-8859-1") { - $this->AddChange("CharSet", $this->Mail->CharSet); + $this->addChange("CharSet", $this->Mail->CharSet); } if ($this->Mail->Sender != "") { - $this->AddChange("Sender", $this->Mail->Sender); + $this->addChange("Sender", $this->Mail->Sender); } if ($this->Mail->WordWrap != 0) { - $this->AddChange("WordWrap", $this->Mail->WordWrap); + $this->addChange("WordWrap", $this->Mail->WordWrap); } if ($this->Mail->Mailer != "mail") { - $this->AddChange("Mailer", $this->Mail->Mailer); + $this->addChange("Mailer", $this->Mail->Mailer); } if ($this->Mail->Port != 25) { - $this->AddChange("Port", $this->Mail->Port); + $this->addChange("Port", $this->Mail->Port); } if ($this->Mail->Helo != "localhost.localdomain") { - $this->AddChange("Helo", $this->Mail->Helo); + $this->addChange("Helo", $this->Mail->Helo); } if ($this->Mail->SMTPAuth) { - $this->AddChange("SMTPAuth", "true"); + $this->addChange("SMTPAuth", "true"); } } @@ -243,7 +243,7 @@ function CheckChanges() * @param string $sNewValue * @return void */ - function AddChange($sName, $sNewValue) + public function addChange($sName, $sNewValue) { $this->ChangeLog[] = array($sName, $sNewValue); } @@ -254,7 +254,7 @@ function AddChange($sName, $sNewValue) * @param string $sValue * @return void */ - function AddNote($sValue) + public function addNote($sValue) { $this->NoteLog[] = $sValue; } @@ -267,31 +267,27 @@ function AddNote($sValue) * @param string $sType * @return boolean */ - function SetAddress($sAddress, $sName = '', $sType = 'to') + public function setAddress($sAddress, $sName = '', $sType = 'to') { switch ($sType) { case 'to': - return $this->Mail->AddAddress($sAddress, $sName); + return $this->Mail->addAddress($sAddress, $sName); case 'cc': - return $this->Mail->AddCC($sAddress, $sName); + return $this->Mail->addCC($sAddress, $sName); case "bcc": - return $this->Mail->AddBCC($sAddress, $sName); + return $this->Mail->addBCC($sAddress, $sName); } return false; } - ///////////////////////////////////////////////// - // UNIT TESTS - ///////////////////////////////////////////////// - /** * Test language files for missing and excess translations * All languages are compared with English */ - function test_Translations() + public function testTranslations() { - $this->Mail->SetLanguage('en'); - $definedStrings = $this->Mail->GetTranslations(); + $this->Mail->setLanguage('en'); + $definedStrings = $this->Mail->getTranslations(); $err = ''; foreach (new DirectoryIterator('../language') as $fileInfo) { if ($fileInfo->isDot()) { @@ -321,24 +317,24 @@ function test_Translations() * This is a sample form for setting appropriate test values through a browser * These values can also be set using a file called testbootstrap.php (not in svn) in the same folder as this script * which is probably more useful if you run these tests a lot - - -

phpmailer Unit Test

-By entering a SMTP hostname it will automatically perform tests with SMTP. - -
- -From Address: "/> -
-To Address: "/> -
-Cc Address: "/> -
-SMTP Hostname: "/> -

- - -

- - + * + * + *

phpmailer Unit Test

+ * By entering a SMTP hostname it will automatically perform tests with SMTP. + * + *
+ * + * From Address: "/> + *
+ * To Address: "/> + *
+ * Cc Address: "/> + *
+ * SMTP Hostname: "/> + *

+ * + * + *

+ * + * */ diff --git a/test/phpmailerTest.php b/test/phpmailerTest.php index b72bb12dc..2ba623e78 100644 --- a/test/phpmailerTest.php +++ b/test/phpmailerTest.php @@ -1,24 +1,28 @@ * @copyright 2004 - 2009 Andy Prevost * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License */ require 'PHPUnit/Autoload.php'; +require '../PHPMailerAutoload.php'; /** * PHPMailer - PHP email transport unit test class * Performs authentication tests */ -class phpmailerTest extends PHPUnit_Framework_TestCase +class PHPMailerTest extends PHPUnit_Framework_TestCase { /** * Holds the default phpmailer instance. @@ -56,12 +60,12 @@ class phpmailerTest extends PHPUnit_Framework_TestCase /** * Run before each test is started. */ - function setUp() + public function setUp() { if (file_exists('./testbootstrap.php')) { include './testbootstrap.php'; //Overrides go in here } - require_once $this->INCLUDE_DIR . 'class.phpmailer.php'; + //require_once $this->INCLUDE_DIR . 'class.phpmailer.php'; $this->Mail = new PHPMailer; $this->Mail->Priority = 3; @@ -93,7 +97,7 @@ function setUp() $this->Mail->Username = ''; $this->Mail->Password = ''; $this->Mail->PluginDir = $this->INCLUDE_DIR; - $this->Mail->AddReplyTo('no_reply@phpmailer.example.com', 'Reply Guy'); + $this->Mail->addReplyTo('no_reply@phpmailer.example.com', 'Reply Guy'); $this->Mail->Sender = 'unit_test@phpmailer.example.com'; if (strlen($this->Mail->Host) > 0) { @@ -104,17 +108,17 @@ function setUp() } if (array_key_exists('mail_to', $_REQUEST)) { - $this->SetAddress($_REQUEST['mail_to'], 'Test User', 'to'); + $this->setAddress($_REQUEST['mail_to'], 'Test User', 'to'); } if (array_key_exists('mail_cc', $_REQUEST) and strlen($_REQUEST['mail_cc']) > 0) { - $this->SetAddress($_REQUEST['mail_cc'], 'Carbon User', 'cc'); + $this->setAddress($_REQUEST['mail_cc'], 'Carbon User', 'cc'); } } /** * Run after each test is completed. */ - function tearDown() + public function tearDown() { // Clean global variables $this->Mail = null; @@ -129,9 +133,9 @@ function tearDown() * @private * @return void */ - function BuildBody() + public function buildBody() { - $this->CheckChanges(); + $this->checkChanges(); // Determine line endings for message if ($this->Mail->ContentType == 'text/html' || strlen($this->Mail->AltBody) > 0) { @@ -159,7 +163,7 @@ function BuildBody() } // If attachments then create an attachment list - $attachments = $this->Mail->GetAttachments(); + $attachments = $this->Mail->getAttachments(); if (count($attachments) > 0) { $ReportBody .= 'Attachments:' . $eol; $ReportBody .= $bullet_start; @@ -205,34 +209,34 @@ function BuildBody() * @private * @return void */ - function CheckChanges() + public function checkChanges() { if ($this->Mail->Priority != 3) { - $this->AddChange('Priority', $this->Mail->Priority); + $this->addChange('Priority', $this->Mail->Priority); } if ($this->Mail->Encoding != '8bit') { - $this->AddChange('Encoding', $this->Mail->Encoding); + $this->addChange('Encoding', $this->Mail->Encoding); } if ($this->Mail->CharSet != 'iso-8859-1') { - $this->AddChange('CharSet', $this->Mail->CharSet); + $this->addChange('CharSet', $this->Mail->CharSet); } if ($this->Mail->Sender != '') { - $this->AddChange('Sender', $this->Mail->Sender); + $this->addChange('Sender', $this->Mail->Sender); } if ($this->Mail->WordWrap != 0) { - $this->AddChange('WordWrap', $this->Mail->WordWrap); + $this->addChange('WordWrap', $this->Mail->WordWrap); } if ($this->Mail->Mailer != 'mail') { - $this->AddChange('Mailer', $this->Mail->Mailer); + $this->addChange('Mailer', $this->Mail->Mailer); } if ($this->Mail->Port != 25) { - $this->AddChange('Port', $this->Mail->Port); + $this->addChange('Port', $this->Mail->Port); } if ($this->Mail->Helo != 'localhost.localdomain') { - $this->AddChange('Helo', $this->Mail->Helo); + $this->addChange('Helo', $this->Mail->Helo); } if ($this->Mail->SMTPAuth) { - $this->AddChange('SMTPAuth', 'true'); + $this->addChange('SMTPAuth', 'true'); } } @@ -243,7 +247,7 @@ function CheckChanges() * @param string $sNewValue * @return void */ - function AddChange($sName, $sNewValue) + public function addChange($sName, $sNewValue) { $this->ChangeLog[] = array($sName, $sNewValue); } @@ -254,7 +258,7 @@ function AddChange($sName, $sNewValue) * @param string $sValue * @return void */ - function AddNote($sValue) + public function addNote($sValue) { $this->NoteLog[] = $sValue; } @@ -267,28 +271,24 @@ function AddNote($sValue) * @param string $sType * @return boolean */ - function SetAddress($sAddress, $sName = '', $sType = 'to') + public function setAddress($sAddress, $sName = '', $sType = 'to') { switch ($sType) { case 'to': - return $this->Mail->AddAddress($sAddress, $sName); + return $this->Mail->addAddress($sAddress, $sName); case 'cc': - return $this->Mail->AddCC($sAddress, $sName); + return $this->Mail->addCC($sAddress, $sName); case 'bcc': - return $this->Mail->AddBCC($sAddress, $sName); + return $this->Mail->addBCC($sAddress, $sName); } return false; } - ///////////////////////////////////////////////// - // UNIT TESTS - ///////////////////////////////////////////////// - /** * Test CRAM-MD5 authentication * Needs a connection to a server that supports this auth mechanism, so commented out by default */ - function testAuthCRAMMD5() + public function testAuthCRAMMD5() { $this->Mail->Host = 'hostname'; $this->Mail->Port = 587; @@ -301,9 +301,9 @@ function testAuthCRAMMD5() $this->Mail->Subject .= ': Auth CRAM-MD5'; $this->Mail->From = 'from@example.com'; $this->Mail->Sender = 'from@example.com'; - $this->Mail->ClearAllRecipients(); - $this->Mail->AddAddress('user@example.com'); - //$this->assertTrue($this->Mail->Send(), $this->Mail->ErrorInfo); + $this->Mail->clearAllRecipients(); + $this->Mail->addAddress('user@example.com'); + //$this->assertTrue($this->mail->send(), $this->mail->ErrorInfo); } /** @@ -311,7 +311,7 @@ function testAuthCRAMMD5() * Test addresses obtained from http://isemail.info * Some failing cases commented out that are apparently up for debate! */ - function testValidate() + public function testValidate() { $validaddresses = array( 'first@iana.org', @@ -451,7 +451,8 @@ function testValidate() $invalidaddresses = array( 'first.last@sub.do,com', 'first\@last@iana.org', - '123456789012345678901234567890123456789012345678901234567890@12345678901234567890123456789012345678901234 [...]', + '123456789012345678901234567890123456789012345678901234567890' . + '@12345678901234567890123456789012345678901234 [...]', 'first.last', '12345678901234567890123456789012345678901234567890123456789012345@iana.org', '.first.last@iana.org', @@ -460,10 +461,11 @@ function testValidate() '"first"last"@iana.org', '"""@iana.org', '"\"@iana.org', -// '""@iana.org', + //'""@iana.org', 'first\@last@iana.org', 'first.last@', - 'x@x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23 [...]', + 'x@x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.' . + 'x23456789.x23456789.x23456789.x23 [...]', 'first.last@[.12.34.56.78]', 'first.last@[12.34.56.789]', 'first.last@[::12.34.56.78]', @@ -494,7 +496,7 @@ function testValidate() '"Doug "Ace" L."@iana.org', 'Doug\ \"Ace\"\ L\.@iana.org', 'hello world@iana.org', -// 'helloworld@iana .org', + //'helloworld@iana .org', 'gatsby@f.sc.ot.t.f.i.tzg.era.l.d.', 'test.iana.org', 'test.@iana.org', @@ -509,7 +511,8 @@ function testValidate() 'test@.', 'test@example.', 'test@.org', - 'test@1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 [...]', + 'test@12345678901234567890123456789012345678901234567890123456789012345678901234567890' . + '12345678901234567890 [...]', 'test@[123.123.123.123', 'test@123.123.123.123]', 'NotAnEmail', @@ -522,20 +525,22 @@ function testValidate() 'Ima Fool@iana.org', 'phil.h\@\@ck@haacked.com', 'foo@[\1.2.3.4]', -// 'first."".last@iana.org', + //'first."".last@iana.org', 'first\last@iana.org', 'Abc\@def@iana.org', 'Fred\ Bloggs@iana.org', 'Joe.\Blow@iana.org', 'first.last@[IPv6:1111:2222:3333:4444:5555:6666:12.34.567.89]', '{^c\@**Dog^}@cartoon.com', -// '"foo"(yay)@(hoopla)[1.2.3.4]', + //'"foo"(yay)@(hoopla)[1.2.3.4]', 'cal(foo(bar)@iamcal.com', 'cal(foo)bar)@iamcal.com', 'cal(foo\)@iamcal.com', - 'first(12345678901234567890123456789012345678901234567890)last@(123456789012345678901234567890123456789012 [...]', + 'first(12345678901234567890123456789012345678901234567890)last@(1234567890123456789' . + '01234567890123456789012 [...]', 'first(middle)last@iana.org', - 'first(abc("def".ghi).mno)middle(abc("def".ghi).mno).last@(abc("def".ghi).mno)example(abc("def".ghi).mno). [...]', + 'first(abc("def".ghi).mno)middle(abc("def".ghi).mno).last@(abc("def".ghi).mno)example' . + '(abc("def".ghi).mno). [...]', 'a(a(b(c)d(e(f))g)(h(i)j)@iana.org', '.@', '@bar.com', @@ -585,35 +590,46 @@ function testValidate() ); $goodfails = array(); foreach ($validaddresses as $address) { - if (!PHPMailer::ValidateAddress($address)) { + if (!PHPMailer::validateAddress($address)) { $goodfails[] = $address; } } $badpasses = array(); foreach ($invalidaddresses as $address) { - if (PHPMailer::ValidateAddress($address)) { + if (PHPMailer::validateAddress($address)) { $badpasses[] = $address; } } $err = ''; if (count($goodfails) > 0) { - $err .= "Good addreses that failed validation:\n"; + $err .= "Good addresses that failed validation:\n"; $err .= implode("\n", $goodfails); } if (count($badpasses) > 0) { if (!empty($err)) { $err .= "\n\n"; } - $err .= "Bad addreses that passed validation:\n"; + $err .= "Bad addresses that passed validation:\n"; $err .= implode("\n", $badpasses); } $this->assertEmpty($err, $err); + //For coverage + $this->assertTrue(PHPMailer::validateAddress('test@example.com', 'auto')); + $this->assertFalse(PHPMailer::validateAddress('test@example.com.', 'auto')); + $this->assertTrue(PHPMailer::validateAddress('test@example.com', 'pcre')); + $this->assertFalse(PHPMailer::validateAddress('test@example.com.', 'pcre')); + $this->assertTrue(PHPMailer::validateAddress('test@example.com', 'pcre8')); + $this->assertFalse(PHPMailer::validateAddress('test@example.com.', 'pcre8')); + $this->assertTrue(PHPMailer::validateAddress('test@example.com', 'php')); + $this->assertFalse(PHPMailer::validateAddress('test@example.com.', 'php')); + $this->assertTrue(PHPMailer::validateAddress('test@example.com', 'noregex')); + $this->assertFalse(PHPMailer::validateAddress('bad', 'noregex')); } /** * Try a plain message. */ - function test_WordWrap() + public function testWordWrap() { $this->Mail->WordWrap = 40; $my_body = 'Here is the main body of this message. It should ' . @@ -625,51 +641,51 @@ function test_WordWrap() $this->Mail->Body = $my_body; $this->Mail->Subject .= ': Wordwrap'; - $this->BuildBody(); - $this->assertTrue($this->Mail->Send(), $this->Mail->ErrorInfo); + $this->buildBody(); + $this->assertTrue($this->Mail->send(), $this->Mail->ErrorInfo); } /** * Try a plain message. */ - function test_Low_Priority() + public function testLowPriority() { $this->Mail->Priority = 5; $this->Mail->Body = 'Here is the main body. There should be ' . 'a reply to address in this message.'; $this->Mail->Subject .= ': Low Priority'; - $this->Mail->AddReplyTo('nobody@nobody.com', 'Nobody (Unit Test)'); + $this->Mail->addReplyTo('nobody@nobody.com', 'Nobody (Unit Test)'); - $this->BuildBody(); - $this->assertTrue($this->Mail->Send(), $this->Mail->ErrorInfo); + $this->buildBody(); + $this->assertTrue($this->Mail->send(), $this->Mail->ErrorInfo); } /** * Simple plain file attachment test. */ - function test_Multiple_Plain_FileAttachment() + public function testMultiplePlainFileAttachment() { $this->Mail->Body = 'Here is the text body'; $this->Mail->Subject .= ': Plain + Multiple FileAttachments'; - if (!$this->Mail->AddAttachment('../examples/images/phpmailer.png')) { + if (!$this->Mail->addAttachment('../examples/images/phpmailer.png')) { $this->assertTrue(false, $this->Mail->ErrorInfo); return; } - if (!$this->Mail->AddAttachment(__FILE__, 'test.txt')) { + if (!$this->Mail->addAttachment(__FILE__, 'test.txt')) { $this->assertTrue(false, $this->Mail->ErrorInfo); return; } - $this->BuildBody(); - $this->assertTrue($this->Mail->Send(), $this->Mail->ErrorInfo); + $this->buildBody(); + $this->assertTrue($this->Mail->send(), $this->Mail->ErrorInfo); } /** * Simple plain string attachment test. */ - function test_Plain_StringAttachment() + public function testPlainStringAttachment() { $this->Mail->Body = 'Here is the text body'; $this->Mail->Subject .= ': Plain + StringAttachment'; @@ -678,40 +694,44 @@ function test_Plain_StringAttachment() "string attachment.\nThis might be taken from a " . 'database or some other such thing. '; - $this->Mail->AddStringAttachment($sAttachment, 'string_attach.txt'); + $this->Mail->addStringAttachment($sAttachment, 'string_attach.txt'); - $this->BuildBody(); - $this->assertTrue($this->Mail->Send(), $this->Mail->ErrorInfo); + $this->buildBody(); + $this->assertTrue($this->Mail->send(), $this->Mail->ErrorInfo); } /** * Plain quoted-printable message. */ - function test_Quoted_Printable() + public function testQuotedPrintable() { $this->Mail->Body = 'Here is the main body'; $this->Mail->Subject .= ': Plain + Quoted-printable'; $this->Mail->Encoding = 'quoted-printable'; - $this->BuildBody(); - $this->assertTrue($this->Mail->Send(), $this->Mail->ErrorInfo); + $this->buildBody(); + $this->assertTrue($this->Mail->send(), $this->Mail->ErrorInfo); //Check that a quoted printable encode and decode results in the same as went in $t = file_get_contents(__FILE__); //Use this file as test content $this->assertEquals( $t, - quoted_printable_decode($this->Mail->EncodeQP($t)), + quoted_printable_decode($this->Mail->encodeQP($t)), 'Quoted-Printable encoding round-trip failed' ); - $this->assertEquals($this->Mail->EncodeQP($t), $this->Mail->EncodeQPphp($t), 'Quoted-Printable BC wrapper failed'); + $this->assertEquals( + $this->Mail->encodeQP($t), + $this->Mail->encodeQPphp($t), + 'Quoted-Printable BC wrapper failed' + ); } /** * Try a plain message. */ - function test_Html() + public function testHtml() { - $this->Mail->IsHTML(true); + $this->Mail->isHTML(true); $this->Mail->Subject .= ": HTML only"; $this->Mail->Body = <<<'EOT' @@ -728,66 +748,67 @@ function test_Html() EOT; - $this->BuildBody(); - $this->assertTrue($this->Mail->Send(), $this->Mail->ErrorInfo); + $this->buildBody(); + $this->assertTrue($this->Mail->send(), $this->Mail->ErrorInfo); } /** * Test simple message builder and html2text converters */ - function test_MsgHTML() { + public function testMsgHTML() + { $message = file_get_contents('../examples/contents.html'); $this->Mail->CharSet = 'utf-8'; $this->Mail->Body = ''; $this->Mail->AltBody = ''; - $this->Mail->MsgHTML($message, '../examples'); - $this->Mail->Subject .= ': MsgHTML'; + $this->Mail->msgHTML($message, '../examples'); + $this->Mail->Subject .= ': msgHTML'; - $this->assertNotEmpty($this->Mail->Body, 'Body not set by MsgHTML'); - $this->assertNotEmpty($this->Mail->AltBody, 'AltBody not set by MsgHTML'); - $this->assertTrue($this->Mail->Send(), $this->Mail->ErrorInfo); + $this->assertNotEmpty($this->Mail->Body, 'Body not set by msgHTML'); + $this->assertNotEmpty($this->Mail->AltBody, 'AltBody not set by msgHTML'); + $this->assertTrue($this->Mail->send(), $this->Mail->ErrorInfo); //Again, using the advanced HTML to text converter $this->Mail->AltBody = ''; - $this->Mail->MsgHTML($message, '../examples', true); + $this->Mail->msgHTML($message, '../examples', true); $this->Mail->Subject .= ' + html2text advanced'; - $this->assertNotEmpty($this->Mail->AltBody, 'Advanced AltBody not set by MsgHTML'); + $this->assertNotEmpty($this->Mail->AltBody, 'Advanced AltBody not set by msgHTML'); - $this->assertTrue($this->Mail->Send(), $this->Mail->ErrorInfo); + $this->assertTrue($this->Mail->send(), $this->Mail->ErrorInfo); } /** * Simple HTML and attachment test */ - function test_HTML_Attachment() + public function testHTMLAttachment() { $this->Mail->Body = 'This is the HTML part of the email.'; $this->Mail->Subject .= ': HTML + Attachment'; - $this->Mail->IsHTML(true); + $this->Mail->isHTML(true); - if (!$this->Mail->AddAttachment(__FILE__, 'test_attach.txt')) { + if (!$this->Mail->addAttachment(__FILE__, 'test_attach.txt')) { $this->assertTrue(false, $this->Mail->ErrorInfo); return; } //Make sure that trying to attach a nonexistent file fails - $this->assertFalse($this->Mail->AddAttachment(__FILE__.md5(microtime()), 'nonexistent_file.txt')); + $this->assertFalse($this->Mail->addAttachment(__FILE__ . md5(microtime()), 'nonexistent_file.txt')); - $this->BuildBody(); - $this->assertTrue($this->Mail->Send(), $this->Mail->ErrorInfo); + $this->buildBody(); + $this->assertTrue($this->Mail->send(), $this->Mail->ErrorInfo); } /** * An embedded attachment test. */ - function test_Embedded_Image() + public function testEmbeddedImage() { $this->Mail->Body = 'Embedded Image: phpmailer' . 'Here is an image!'; $this->Mail->Subject .= ': Embedded Image'; - $this->Mail->IsHTML(true); + $this->Mail->isHTML(true); - if (!$this->Mail->AddEmbeddedImage( + if (!$this->Mail->addEmbeddedImage( '../examples/images/phpmailer.png', 'my-attach', 'phpmailer.png', @@ -799,24 +820,24 @@ function test_Embedded_Image() return; } - $this->BuildBody(); - $this->assertTrue($this->Mail->Send(), $this->Mail->ErrorInfo); + $this->buildBody(); + $this->assertTrue($this->Mail->send(), $this->Mail->ErrorInfo); //For code coverage - $this->Mail->AddEmbeddedImage('thisfiledoesntexist', 'xyz'); //Non-existent file - $this->Mail->AddEmbeddedImage(__FILE__, '123'); //Missing name + $this->Mail->addEmbeddedImage('thisfiledoesntexist', 'xyz'); //Non-existent file + $this->Mail->addEmbeddedImage(__FILE__, '123'); //Missing name } /** * An embedded attachment test. */ - function test_Multi_Embedded_Image() + public function testMultiEmbeddedImage() { $this->Mail->Body = 'Embedded Image: phpmailer' . 'Here is an image!'; $this->Mail->Subject .= ': Embedded Image + Attachment'; - $this->Mail->IsHTML(true); + $this->Mail->isHTML(true); - if (!$this->Mail->AddEmbeddedImage( + if (!$this->Mail->addEmbeddedImage( '../examples/images/phpmailer.png', 'my-attach', 'phpmailer.png', @@ -828,203 +849,206 @@ function test_Multi_Embedded_Image() return; } - if (!$this->Mail->AddAttachment(__FILE__, 'test.txt')) { + if (!$this->Mail->addAttachment(__FILE__, 'test.txt')) { $this->assertTrue(false, $this->Mail->ErrorInfo); return; } - $this->BuildBody(); - $this->assertTrue($this->Mail->Send(), $this->Mail->ErrorInfo); + $this->buildBody(); + $this->assertTrue($this->Mail->send(), $this->Mail->ErrorInfo); } /** * Simple multipart/alternative test. */ - function test_AltBody() + public function testAltBody() { $this->Mail->Body = 'This is the HTML part of the email.'; $this->Mail->AltBody = 'Here is the text body of this message. ' . 'It should be quite a few lines. It should be wrapped at the ' . '40 characters. Make sure that it is.'; $this->Mail->WordWrap = 40; - $this->AddNote('This is a mulipart alternative email'); + $this->addNote('This is a mulipart alternative email'); $this->Mail->Subject .= ': AltBody + Word Wrap'; - $this->BuildBody(); - $this->assertTrue($this->Mail->Send(), $this->Mail->ErrorInfo); + $this->buildBody(); + $this->assertTrue($this->Mail->send(), $this->Mail->ErrorInfo); } /** * Simple HTML and attachment test */ - function test_AltBody_Attachment() + public function testAltBodyAttachment() { $this->Mail->Body = 'This is the HTML part of the email.'; $this->Mail->AltBody = 'This is the text part of the email.'; $this->Mail->Subject .= ': AltBody + Attachment'; - $this->Mail->IsHTML(true); + $this->Mail->isHTML(true); - if (!$this->Mail->AddAttachment(__FILE__, 'test_attach.txt')) { + if (!$this->Mail->addAttachment(__FILE__, 'test_attach.txt')) { $this->assertTrue(false, $this->Mail->ErrorInfo); return; } - $this->BuildBody(); - $this->assertTrue($this->Mail->Send(), $this->Mail->ErrorInfo); + $this->buildBody(); + $this->assertTrue($this->Mail->send(), $this->Mail->ErrorInfo); if (is_writable('.')) { - file_put_contents('message.txt', $this->Mail->CreateHeader() . $this->Mail->CreateBody()); + file_put_contents('message.txt', $this->Mail->createHeader() . $this->Mail->createBody()); } else { $this->assertTrue(false, 'Could not write local file - check permissions'); } } - /** - * iCal event test - */ - function test_Ical() - { - $this->Mail->Body = 'This is the HTML part of the email.'; - $this->Mail->AltBody = 'This is the text part of the email.'; - $this->Mail->Subject .= ': iCal'; - $this->Mail->IsHTML(true); - $this->BuildBody(); - require_once '../extras/EasyPeasyICS.php'; - $ICS = new EasyPeasyICS("PHPMailer test calendar"); - $ICS->addEvent( - strtotime('tomorrow 10:00 Europe/Paris'), - strtotime('tomorrow 11:00 Europe/Paris'), - 'PHPMailer iCal test', - 'A test of PHPMailer iCal support', - 'https://github.com/PHPMailer/PHPMailer' - ); - $this->Mail->Ical = $ICS->render(false); - $this->assertTrue($this->Mail->Send(), $this->Mail->ErrorInfo); - $this->Mail->Body = 'Embedded Image: phpmailer' . - 'Here is an image!.'; - $this->Mail->AltBody = 'This is the text part of the email.'; - $this->Mail->Subject .= ': iCal + inline'; - $this->Mail->IsHTML(true); - $this->Mail->AddEmbeddedImage( - '../examples/images/phpmailer.png', - 'my-attach', - 'phpmailer.png', - 'base64', - 'image/png' - ); - $this->BuildBody(); - $this->assertTrue($this->Mail->Send(), $this->Mail->ErrorInfo); - } - - /** + /** + * iCal event test + */ + public function testIcal() + { + $this->Mail->Body = 'This is the HTML part of the email.'; + $this->Mail->AltBody = 'This is the text part of the email.'; + $this->Mail->Subject .= ': iCal'; + $this->Mail->isHTML(true); + $this->buildBody(); + require_once '../extras/EasyPeasyICS.php'; + $ICS = new EasyPeasyICS("PHPMailer test calendar"); + $ICS->addEvent( + strtotime('tomorrow 10:00 Europe/Paris'), + strtotime('tomorrow 11:00 Europe/Paris'), + 'PHPMailer iCal test', + 'A test of PHPMailer iCal support', + 'https://github.com/PHPMailer/PHPMailer' + ); + $this->Mail->Ical = $ICS->render(false); + $this->assertTrue($this->Mail->send(), $this->Mail->ErrorInfo); + $this->Mail->Body = 'Embedded Image: phpmailer' . + 'Here is an image!.'; + $this->Mail->AltBody = 'This is the text part of the email.'; + $this->Mail->Subject .= ': iCal + inline'; + $this->Mail->isHTML(true); + $this->Mail->addEmbeddedImage( + '../examples/images/phpmailer.png', + 'my-attach', + 'phpmailer.png', + 'base64', + 'image/png' + ); + $this->buildBody(); + $this->assertTrue($this->Mail->send(), $this->Mail->ErrorInfo); + } + + /** * Test sending multiple messages with separate connections */ - function test_MultipleSend() + public function testMultipleSend() { $this->Mail->Body = 'Sending two messages without keepalive'; - $this->BuildBody(); + $this->buildBody(); $subject = $this->Mail->Subject; $this->Mail->Subject = $subject . ': SMTP 1'; - $this->assertTrue($this->Mail->Send(), $this->Mail->ErrorInfo); + $this->assertTrue($this->Mail->send(), $this->Mail->ErrorInfo); $this->Mail->Subject = $subject . ': SMTP 2'; $this->Mail->Sender = 'blah@example.com'; - $this->assertTrue($this->Mail->Send(), $this->Mail->ErrorInfo); + $this->assertTrue($this->Mail->send(), $this->Mail->ErrorInfo); } /** * Test sending using SendMail */ - function test_SendmailSend() + public function testSendmailSend() { $this->Mail->Body = 'Sending via sendmail'; - $this->BuildBody(); + $this->buildBody(); $subject = $this->Mail->Subject; $this->Mail->Subject = $subject . ': sendmail'; - $this->Mail->IsSendmail(); - $this->assertTrue($this->Mail->Send(), $this->Mail->ErrorInfo); + $this->Mail->isSendmail(); + $this->assertTrue($this->Mail->send(), $this->Mail->ErrorInfo); } /** * Test sending using PHP mail() function */ - function test_MailSend() + public function testMailSend() { $sendmail = ini_get('sendmail_path'); if (strpos($sendmail, '/') === false) { //No path in sendmail_path ini_set('sendmail_path', '/usr/sbin/sendmail -t -i '); } $this->Mail->Body = 'Sending via mail()'; - $this->BuildBody(); + $this->buildBody(); $this->Mail->Subject = $this->Mail->Subject . ': mail()'; - $this->Mail->IsMail(); - $this->assertTrue($this->Mail->Send(), $this->Mail->ErrorInfo); + $this->Mail->isMail(); + $this->assertTrue($this->Mail->send(), $this->Mail->ErrorInfo); } /** * Test sending an empty body */ - function test_Empty_Body() + public function testEmptyBody() { - $this->BuildBody(); + $this->buildBody(); $this->Mail->Body = ''; $this->Mail->Subject = $this->Mail->Subject . ': Empty Body'; - $this->Mail->IsMail(); + $this->Mail->isMail(); $this->Mail->AllowEmpty = true; - $this->assertTrue($this->Mail->Send(), $this->Mail->ErrorInfo); + $this->assertTrue($this->Mail->send(), $this->Mail->ErrorInfo); $this->Mail->AllowEmpty = false; - $this->assertFalse($this->Mail->Send(), $this->Mail->ErrorInfo); + $this->assertFalse($this->Mail->send(), $this->Mail->ErrorInfo); } /** * Test keepalive (sending multiple messages in a single connection) */ - function test_SmtpKeepAlive() + public function testSmtpKeepAlive() { $this->Mail->Body = 'This was done using the SMTP keep-alive.'; - $this->BuildBody(); + $this->buildBody(); $subject = $this->Mail->Subject; $this->Mail->SMTPKeepAlive = true; $this->Mail->Subject = $subject . ': SMTP keep-alive 1'; - $this->assertTrue($this->Mail->Send(), $this->Mail->ErrorInfo); + $this->assertTrue($this->Mail->send(), $this->Mail->ErrorInfo); $this->Mail->Subject = $subject . ': SMTP keep-alive 2'; - $this->assertTrue($this->Mail->Send(), $this->Mail->ErrorInfo); - $this->Mail->SmtpClose(); + $this->assertTrue($this->Mail->send(), $this->Mail->ErrorInfo); + $this->Mail->smtpClose(); } /** * Test SMTP host connections */ - function test_SmtpConnect() + public function testSmtpConnect() { - $this->assertTrue($this->Mail->SmtpConnect(), 'SMTP single connect failed'); - $this->Mail->SmtpClose(); - $this->Mail->Host = "localhost:12345;10.10.10.10:54321"; - $this->assertFalse($this->Mail->SmtpConnect(), 'SMTP bad multi-connect succeeded'); - $this->Mail->SmtpClose(); - $this->Mail->Host = "localhost:12345;10.10.10.10:54321;".$_REQUEST['mail_host']; - $this->assertTrue($this->Mail->SmtpConnect(), 'SMTP multi-connect failed'); - $this->Mail->SmtpClose(); - $this->Mail->Host = $_REQUEST['mail_host']; - //Need to pick a harmless option so as not cause problems of its own! socket:bind doesn't work with Travis-CI - $this->assertTrue($this->Mail->SmtpConnect(array('ssl' => array('verify_depth' => 10))), 'SMTP connect with options failed'); + $this->assertTrue($this->Mail->smtpConnect(), 'SMTP single connect failed'); + $this->Mail->smtpClose(); + $this->Mail->Host = "localhost:12345;10.10.10.10:54321"; + $this->assertFalse($this->Mail->smtpConnect(), 'SMTP bad multi-connect succeeded'); + $this->Mail->smtpClose(); + $this->Mail->Host = "localhost:12345;10.10.10.10:54321;" . $_REQUEST['mail_host']; + $this->assertTrue($this->Mail->smtpConnect(), 'SMTP multi-connect failed'); + $this->Mail->smtpClose(); + $this->Mail->Host = $_REQUEST['mail_host']; + //Need to pick a harmless option so as not cause problems of its own! socket:bind doesn't work with Travis-CI + $this->assertTrue( + $this->Mail->smtpConnect(array('ssl' => array('verify_depth' => 10))), + 'SMTP connect with options failed' + ); } /** * Tests this denial of service attack: * http://www.cybsec.com/vuln/PHPMailer-DOS.pdf */ - function test_DenialOfServiceAttack() + public function testDenialOfServiceAttack() { $this->Mail->Body = 'This should no longer cause a denial of service.'; - $this->BuildBody(); + $this->buildBody(); $this->Mail->Subject = substr(str_repeat('0123456789', 100), 0, 998); - $this->assertTrue($this->Mail->Send(), $this->Mail->ErrorInfo); + $this->assertTrue($this->Mail->send(), $this->Mail->ErrorInfo); } /** @@ -1032,117 +1056,125 @@ function test_DenialOfServiceAttack() * https://sourceforge.net/p/phpmailer/bugs/383/ * According to the ticket, this should get stuck in a loop, though I can't make it happen. */ - function test_DenialOfServiceAttack2() + public function testDenialOfServiceAttack2() { //Encoding name longer than 68 chars $this->Mail->Encoding = '1234567890123456789012345678901234567890123456789012345678901234567890'; - //Call WrapText with a zero length value - $t = $this->Mail->WrapText(str_repeat('This should no longer cause a denial of service. ', 30), 0); + //Call wrapText with a zero length value + $this->Mail->wrapText(str_repeat('This should no longer cause a denial of service. ', 30), 0); } /** * Test error handling */ - function test_Error() + public function testError() { $this->Mail->Subject .= ': This should be sent'; - $this->BuildBody(); - $this->Mail->ClearAllRecipients(); // no addresses should cause an error - $this->assertTrue($this->Mail->IsError() == false, 'Error found'); - $this->assertTrue($this->Mail->Send() == false, 'Send succeeded'); - $this->assertTrue($this->Mail->IsError(), 'No error found'); + $this->buildBody(); + $this->Mail->clearAllRecipients(); // no addresses should cause an error + $this->assertTrue($this->Mail->isError() == false, 'Error found'); + $this->assertTrue($this->Mail->send() == false, 'send succeeded'); + $this->assertTrue($this->Mail->isError(), 'No error found'); $this->assertEquals('You must provide at least one recipient email address.', $this->Mail->ErrorInfo); - $this->Mail->AddAddress($_REQUEST['mail_to']); - $this->assertTrue($this->Mail->Send(), 'Send failed'); + $this->Mail->addAddress($_REQUEST['mail_to']); + $this->assertTrue($this->Mail->send(), 'send failed'); } /** * Test addressing */ - function test_Addressing() + public function testAddressing() { - $this->assertFalse($this->Mail->AddAddress(''), 'Empty address accepted'); - $this->assertFalse($this->Mail->AddAddress('', 'Nobody'), 'Empty address with name accepted'); - $this->assertFalse($this->Mail->AddAddress('a@example..com'), 'Invalid address accepted'); - $this->assertTrue($this->Mail->AddAddress('a@example.com'), 'Addressing failed'); - $this->assertFalse($this->Mail->AddAddress('a@example.com'), 'Duplicate addressing failed'); - $this->assertTrue($this->Mail->AddCC('b@example.com'), 'CC addressing failed'); - $this->assertFalse($this->Mail->AddCC('b@example.com'), 'CC duplicate addressing failed'); - $this->assertFalse($this->Mail->AddCC('a@example.com'), 'CC duplicate addressing failed (2)'); - $this->assertTrue($this->Mail->AddBCC('c@example.com'), 'BCC addressing failed'); - $this->assertFalse($this->Mail->AddBCC('c@example.com'), 'BCC duplicate addressing failed'); - $this->assertFalse($this->Mail->AddBCC('a@example.com'), 'BCC duplicate addressing failed (2)'); - $this->assertTrue($this->Mail->AddReplyTo('a@example.com'), 'Replyto Addressing failed'); - $this->assertFalse($this->Mail->AddReplyTo('a@example..com'), 'Invalid Replyto address accepted'); - $this->Mail->ClearAddresses(); - $this->Mail->ClearCCs(); - $this->Mail->ClearBCCs(); - $this->Mail->ClearReplyTos(); + $this->assertFalse($this->Mail->addAddress(''), 'Empty address accepted'); + $this->assertFalse($this->Mail->addAddress('', 'Nobody'), 'Empty address with name accepted'); + $this->assertFalse($this->Mail->addAddress('a@example..com'), 'Invalid address accepted'); + $this->assertTrue($this->Mail->addAddress('a@example.com'), 'Addressing failed'); + $this->assertFalse($this->Mail->addAddress('a@example.com'), 'Duplicate addressing failed'); + $this->assertTrue($this->Mail->addCC('b@example.com'), 'CC addressing failed'); + $this->assertFalse($this->Mail->addCC('b@example.com'), 'CC duplicate addressing failed'); + $this->assertFalse($this->Mail->addCC('a@example.com'), 'CC duplicate addressing failed (2)'); + $this->assertTrue($this->Mail->addBCC('c@example.com'), 'BCC addressing failed'); + $this->assertFalse($this->Mail->addBCC('c@example.com'), 'BCC duplicate addressing failed'); + $this->assertFalse($this->Mail->addBCC('a@example.com'), 'BCC duplicate addressing failed (2)'); + $this->assertTrue($this->Mail->addReplyTo('a@example.com'), 'Replyto Addressing failed'); + $this->assertFalse($this->Mail->addReplyTo('a@example..com'), 'Invalid Replyto address accepted'); + $this->assertTrue($this->Mail->setFrom('a@example.com', 'some name'), 'setFrom failed'); + $this->assertFalse($this->Mail->setFrom('a@example.com.', 'some name'), 'setFrom accepted invalid address'); + $this->Mail->Sender = ''; + $this->Mail->setFrom('a@example.com', 'some name', true); + $this->assertEquals($this->Mail->Sender, 'a@example.com', 'setFrom failed to set sender'); + $this->Mail->Sender = ''; + $this->Mail->setFrom('a@example.com', 'some name', false); + $this->assertEquals($this->Mail->Sender, '', 'setFrom should not have set sender'); + $this->Mail->clearCCs(); + $this->Mail->clearBCCs(); + $this->Mail->clearReplyTos(); } /** * Test address escaping */ - function test_AddressEscaping() + public function testAddressEscaping() { $this->Mail->Subject .= ': Address escaping'; - $this->Mail->ClearAddresses(); - $this->Mail->AddAddress('foo@example.com', 'Tim "The Book" O\'Reilly'); + $this->Mail->clearAddresses(); + $this->Mail->addAddress('foo@example.com', 'Tim "The Book" O\'Reilly'); $this->Mail->Body = 'Test correct escaping of quotes in addresses.'; - $this->BuildBody(); - $this->Mail->PreSend(); - $b = $this->Mail->GetSentMIMEMessage(); - $this->assertTrue((strpos($b, 'To: "Tim \"The Book\" O\'Reilly" ') !==false)); + $this->buildBody(); + $this->Mail->preSend(); + $b = $this->Mail->getSentMIMEMessage(); + $this->assertTrue((strpos($b, 'To: "Tim \"The Book\" O\'Reilly" ') !== false)); } /** * Test BCC-only addressing */ - function test_BCCAddressing() + public function testBCCAddressing() { $this->Mail->Subject .= ': BCC-only addressing'; - $this->BuildBody(); - $this->Mail->ClearAllRecipients(); - $this->assertTrue($this->Mail->AddBCC('a@example.com'), 'BCC addressing failed'); - $this->assertTrue($this->Mail->Send(), 'Send failed'); + $this->buildBody(); + $this->Mail->clearAllRecipients(); + $this->assertTrue($this->Mail->addBCC('a@example.com'), 'BCC addressing failed'); + $this->assertTrue($this->Mail->send(), 'send failed'); } /** * Encoding tests */ - function test_Encodings() + public function testEncodings() { $this->Mail->CharSet = 'iso-8859-1'; $this->assertEquals( '=A1Hola!_Se=F1or!', - $this->Mail->EncodeQ("\xa1Hola! Se\xf1or!", 'text'), + $this->Mail->encodeQ("\xa1Hola! Se\xf1or!", 'text'), 'Q Encoding (text) failed' ); $this->assertEquals( '=A1Hola!_Se=F1or!', - $this->Mail->EncodeQ("\xa1Hola! Se\xf1or!", 'comment'), + $this->Mail->encodeQ("\xa1Hola! Se\xf1or!", 'comment'), 'Q Encoding (comment) failed' ); $this->assertEquals( '=A1Hola!_Se=F1or!', - $this->Mail->EncodeQ("\xa1Hola! Se\xf1or!", 'phrase'), + $this->Mail->encodeQ("\xa1Hola! Se\xf1or!", 'phrase'), 'Q Encoding (phrase) failed' ); $this->Mail->CharSet = 'UTF-8'; $this->assertEquals( '=C2=A1Hola!_Se=C3=B1or!', - $this->Mail->EncodeQ("\xc2\xa1Hola! Se\xc3\xb1or!", 'text'), + $this->Mail->encodeQ("\xc2\xa1Hola! Se\xc3\xb1or!", 'text'), 'Q Encoding (text) failed' ); } /** - * Signing tests + * S/MIME Signing tests */ - function test_Signing() + public function testSigning() { + $this->Mail->Subject .= ': S/MIME signing'; $this->Mail->Body = 'This message is S/MIME signed.'; - $this->BuildBody(); + $this->buildBody(); $dn = array( 'countryName' => 'UK', @@ -1170,49 +1202,77 @@ function test_Signing() openssl_pkey_export($pk, $pkeyout, $password); file_put_contents($keyfile, $pkeyout); - $this->Mail->Sign( + $this->Mail->sign( $certfile, $keyfile, $password ); - $this->assertTrue($this->Mail->Send(), 'S/MIME signing failed'); + $this->assertTrue($this->Mail->send(), 'S/MIME signing failed'); unlink($certfile); unlink($keyfile); } + /** + * DKIM Signing tests + */ + public function testDKIM() + { + $this->Mail->Subject .= ': DKIM signing'; + $this->Mail->Body = 'This message is DKIM signed.'; + $this->buildBody(); + //$this->Mail->SMTPDebug = 2; + $privatekeyfile = 'dkim_private.key'; + //Make a new key pair + //(2048 bits is the recommended minimum key length - + //gmail won't accept less than 1024 bits) + $pk = openssl_pkey_new( + array( + 'private_key_bits' => 2048, + 'private_key_type' => OPENSSL_KEYTYPE_RSA + ) + ); + openssl_pkey_export_to_file($pk, $privatekeyfile); + $this->Mail->DKIM_domain = 'example.com'; + $this->Mail->DKIM_private = $privatekeyfile; + $this->Mail->DKIM_selector = 'phpmailer'; + $this->Mail->DKIM_passphrase = ''; //key is not encrypted + $this->assertTrue($this->Mail->send(), 'DKIM signed mail failed'); + unlink($privatekeyfile); + } + /** * Test line break reformatting */ - function test_LineBreaks() + public function testLineBreaks() { - $unixsrc = "Hello\nWorld\nAgain\n"; - $macsrc = "Hello\rWorld\rAgain\r"; - $windowssrc = "Hello\r\nWorld\r\nAgain\r\n"; - $mixedsrc = "Hello\nWorld\rAgain\r\n"; - $target = "Hello\r\nWorld\r\nAgain\r\n"; - $this->assertEquals($target, PHPMailer::NormalizeBreaks($unixsrc), 'UNIX break reformatting failed'); - $this->assertEquals($target, PHPMailer::NormalizeBreaks($macsrc), 'Mac break reformatting failed'); - $this->assertEquals($target, PHPMailer::NormalizeBreaks($windowssrc), 'Windows break reformatting failed'); - $this->assertEquals($target, PHPMailer::NormalizeBreaks($mixedsrc), 'Mixed break reformatting failed'); + $unixsrc = "hello\nWorld\nAgain\n"; + $macsrc = "hello\rWorld\rAgain\r"; + $windowssrc = "hello\r\nWorld\r\nAgain\r\n"; + $mixedsrc = "hello\nWorld\rAgain\r\n"; + $target = "hello\r\nWorld\r\nAgain\r\n"; + $this->assertEquals($target, PHPMailer::normalizeBreaks($unixsrc), 'UNIX break reformatting failed'); + $this->assertEquals($target, PHPMailer::normalizeBreaks($macsrc), 'Mac break reformatting failed'); + $this->assertEquals($target, PHPMailer::normalizeBreaks($windowssrc), 'Windows break reformatting failed'); + $this->assertEquals($target, PHPMailer::normalizeBreaks($mixedsrc), 'Mixed break reformatting failed'); } /** * Miscellaneous calls to improve test coverage and some small tests */ - function test_Miscellaneous() + public function testMiscellaneous() { $this->assertEquals('application/pdf', PHPMailer::_mime_types('pdf'), 'MIME TYPE lookup failed'); - $this->Mail->AddCustomHeader('SomeHeader: Some Value'); - $this->Mail->ClearCustomHeaders(); - $this->Mail->ClearAttachments(); - $this->Mail->IsHTML(false); - $this->Mail->IsSMTP(); - $this->Mail->IsMail(); - $this->Mail->IsSendMail(); - $this->Mail->IsQmail(); - $this->Mail->SetLanguage('fr'); + $this->Mail->addCustomHeader('SomeHeader: Some Value'); + $this->Mail->clearCustomHeaders(); + $this->Mail->clearAttachments(); + $this->Mail->isHTML(false); + $this->Mail->isSMTP(); + $this->Mail->isMail(); + $this->Mail->isSendmail(); + $this->Mail->isQmail(); + $this->Mail->setLanguage('fr'); $this->Mail->Sender = ''; - $this->Mail->CreateHeader(); + $this->Mail->createHeader(); $this->assertFalse($this->Mail->set('x', 'y'), 'Invalid property set succeeded'); $this->assertTrue($this->Mail->set('Timeout', 11), 'Valid property set failed'); //Test pathinfo @@ -1222,7 +1282,11 @@ function test_Miscellaneous() $this->assertEquals($q['basename'], '飛兒樂 團光茫.mp3', 'UNIX basename not matched'); $this->assertEquals($q['extension'], 'mp3', 'UNIX extension not matched'); $this->assertEquals($q['filename'], '飛兒樂 團光茫', 'UNIX filename not matched'); - $this->assertEquals(PHPMailer::mb_pathinfo($a, PATHINFO_DIRNAME), '/mnt/files', 'Dirname path element not matched'); + $this->assertEquals( + PHPMailer::mb_pathinfo($a, PATHINFO_DIRNAME), + '/mnt/files', + 'Dirname path element not matched' + ); $this->assertEquals(PHPMailer::mb_pathinfo($a, 'filename'), '飛兒樂 團光茫', 'Filename path element not matched'); $a = 'c:\mnt\files\飛兒樂 團光茫.mp3'; $q = PHPMailer::mb_pathinfo($a); @@ -1237,24 +1301,24 @@ function test_Miscellaneous() * This is a sample form for setting appropriate test values through a browser * These values can also be set using a file called testbootstrap.php (not in svn) in the same folder as this script * which is probably more useful if you run these tests a lot - - -

phpmailer Unit Test

-By entering a SMTP hostname it will automatically perform tests with SMTP. - -
- -From Address: "/> -
-To Address: "/> -
-Cc Address: "/> -
-SMTP Hostname: "/> -

- - -

- - + * + * + *

phpmailer Unit Test

+ * By entering a SMTP hostname it will automatically perform tests with SMTP. + * + *
+ * + * From Address: "/> + *
+ * To Address: "/> + *
+ * Cc Address: "/> + *
+ * SMTP Hostname: "/> + *

+ * + * + *

+ * + * */ diff --git a/test/test_callback.php b/test/test_callback.php index 7d3e42abe..3ac16702f 100644 --- a/test/test_callback.php +++ b/test/test_callback.php @@ -1,6 +1,6 @@ -PHPMailer Lite - DKIM and Callback Function test + PHPMailer Lite - DKIM and Callback Function test @@ -18,58 +18,63 @@ * string $body the email body * @return boolean */ -function callbackAction ($result, $to, $cc, $bcc, $subject, $body) { - /* - this callback example echos the results to the screen - implement to - post to databases, build CSV log files, etc., with minor changes - */ - $to = cleanEmails($to,'to'); - $cc = cleanEmails($cc[0],'cc'); - $bcc = cleanEmails($bcc[0],'cc'); - echo $result . "\tTo: " . $to['Name'] . "\tTo: " . $to['Email'] . "\tCc: " . $cc['Name'] . "\tCc: " . $cc['Email'] . "\tBcc: " . $bcc['Name'] . "\tBcc: " . $bcc['Email'] . "\t" . $subject . "
\n"; - return true; +function callbackAction($result, $to, $cc, $bcc, $subject, $body) +{ + /* + this callback example echos the results to the screen - implement to + post to databases, build CSV log files, etc., with minor changes + */ + $to = cleanEmails($to, 'to'); + $cc = cleanEmails($cc[0], 'cc'); + $bcc = cleanEmails($bcc[0], 'cc'); + echo $result . "\tTo: " . $to['Name'] . "\tTo: " . $to['Email'] . "\tCc: " . $cc['Name'] . + "\tCc: " . $cc['Email'] . "\tBcc: " . $bcc['Name'] . "\tBcc: " . $bcc['Email'] . + "\t" . $subject . "\n\n". $body . "\n"; + return true; } require_once '../class.phpmailer.php'; $mail = new PHPMailer(); try { - $mail->IsMail(); - $mail->SetFrom('you@example.com', 'Your Name'); - $mail->AddAddress('another@example.com', 'John Doe'); - $mail->Subject = 'PHPMailer Lite Test Subject via Mail()'; - $mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically - $mail->MsgHTML(file_get_contents('../examples/contents.html')); - $mail->AddAttachment('../examples/images/phpmailer.png'); // attachment - $mail->AddAttachment('../examples/images/phpmailer_mini.gif'); // attachment - $mail->action_function = 'callbackAction'; - $mail->Send(); - echo "Message Sent OK

\n"; + $mail->isMail(); + $mail->setFrom('you@example.com', 'Your Name'); + $mail->addAddress('another@example.com', 'John Doe'); + $mail->Subject = 'PHPMailer Lite Test Subject via mail()'; + // optional - msgHTML will create an alternate automatically + $mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; + $mail->msgHTML(file_get_contents('../examples/contents.html')); + $mail->addAttachment('../examples/images/phpmailer.png'); // attachment + $mail->addAttachment('../examples/images/phpmailer_mini.gif'); // attachment + $mail->action_function = 'callbackAction'; + $mail->send(); + echo "Message Sent OK

\n"; } catch (phpmailerException $e) { - echo $e->errorMessage(); //Pretty error messages from PHPMailer + echo $e->errorMessage(); //Pretty error messages from PHPMailer } catch (Exception $e) { - echo $e->getMessage(); //Boring error messages from anything else! + echo $e->getMessage(); //Boring error messages from anything else! } -function cleanEmails($str,$type) { - if ($type == 'cc') { - $addy['Email'] = $str[0]; - $addy['Name'] = $str[1]; +function cleanEmails($str, $type) +{ + if ($type == 'cc') { + $addy['Email'] = $str[0]; + $addy['Name'] = $str[1]; + return $addy; + } + if (!strstr($str, ' <')) { + $addy['Name'] = ''; + $addy['Email'] = $addy; + return $addy; + } + $addyArr = explode(' <', $str); + if (substr($addyArr[1], -1) == '>') { + $addyArr[1] = substr($addyArr[1], 0, -1); + } + $addy['Name'] = $addyArr[0]; + $addy['Email'] = $addyArr[1]; + $addy['Email'] = str_replace('@', '@', $addy['Email']); return $addy; - } - if (!strstr($str, ' <')) { - $addy['Name'] = ''; - $addy['Email'] = $addy; - return $addy; - } - $addyArr = explode(' <', $str); - if (substr($addyArr[1],-1) == '>') { - $addyArr[1] = substr($addyArr[1],0,-1); - } - $addy['Name'] = $addyArr[0]; - $addy['Email'] = $addyArr[1]; - $addy['Email'] = str_replace('@', '@', $addy['Email']); - return $addy; } ?>