├── .gitignore ├── LICENSE ├── PHPMailer.php ├── Plugin.php ├── README.md ├── templateGuest.html └── templateHost.html /.gitignore: -------------------------------------------------------------------------------- 1 | debug.log -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 AlanDecode 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /PHPMailer.php: -------------------------------------------------------------------------------- 1 | 9 | * @author Jim Jagielski (jimjag) 10 | * @author Andy Prevost (codeworxtech) 11 | * @author Brent R. Matzelle (original founder) 12 | * @copyright 2014 Marcus Bointon 13 | * @copyright 2010 - 2012 Jim Jagielski 14 | * @copyright 2004 - 2009 Andy Prevost 15 | * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License 16 | * @note This program is distributed in the hope that it will be useful - WITHOUT 17 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 18 | * FITNESS FOR A PARTICULAR PURPOSE. 19 | */ 20 | /** 21 | * PHPMailer RFC821 SMTP email transport class. 22 | * Implements RFC 821 SMTP commands and provides some utility methods for sending mail to an SMTP server. 23 | * @package PHPMailer 24 | * @author Chris Ryan 25 | * @author Marcus Bointon 26 | */ 27 | class SMTP 28 | { 29 | /** 30 | * The PHPMailer SMTP version number. 31 | * @var string 32 | */ 33 | const VERSION = '5.2.22'; 34 | /** 35 | * SMTP line break constant. 36 | * @var string 37 | */ 38 | const CRLF = "\r\n"; 39 | /** 40 | * The SMTP port to use if one is not specified. 41 | * @var integer 42 | */ 43 | const DEFAULT_SMTP_PORT = 25; 44 | /** 45 | * The maximum line length allowed by RFC 2822 section 2.1.1 46 | * @var integer 47 | */ 48 | const MAX_LINE_LENGTH = 998; 49 | /** 50 | * Debug level for no output 51 | */ 52 | const DEBUG_OFF = 0; 53 | /** 54 | * Debug level to show client -> server messages 55 | */ 56 | const DEBUG_CLIENT = 1; 57 | /** 58 | * Debug level to show client -> server and server -> client messages 59 | */ 60 | const DEBUG_SERVER = 2; 61 | /** 62 | * Debug level to show connection status, client -> server and server -> client messages 63 | */ 64 | const DEBUG_CONNECTION = 3; 65 | /** 66 | * Debug level to show all messages 67 | */ 68 | const DEBUG_LOWLEVEL = 4; 69 | /** 70 | * The PHPMailer SMTP Version number. 71 | * @var string 72 | * @deprecated Use the `VERSION` constant instead 73 | * @see SMTP::VERSION 74 | */ 75 | public $Version = '5.2.22'; 76 | /** 77 | * SMTP server port number. 78 | * @var integer 79 | * @deprecated This is only ever used as a default value, so use the `DEFAULT_SMTP_PORT` constant instead 80 | * @see SMTP::DEFAULT_SMTP_PORT 81 | */ 82 | public $SMTP_PORT = 25; 83 | /** 84 | * SMTP reply line ending. 85 | * @var string 86 | * @deprecated Use the `CRLF` constant instead 87 | * @see SMTP::CRLF 88 | */ 89 | public $CRLF = "\r\n"; 90 | /** 91 | * Debug output level. 92 | * Options: 93 | * * self::DEBUG_OFF (`0`) No debug output, default 94 | * * self::DEBUG_CLIENT (`1`) Client commands 95 | * * self::DEBUG_SERVER (`2`) Client commands and server responses 96 | * * self::DEBUG_CONNECTION (`3`) As DEBUG_SERVER plus connection status 97 | * * self::DEBUG_LOWLEVEL (`4`) Low-level data output, all messages 98 | * @var integer 99 | */ 100 | public $do_debug = self::DEBUG_OFF; 101 | /** 102 | * How to handle debug output. 103 | * Options: 104 | * * `echo` Output plain-text as-is, appropriate for CLI 105 | * * `html` Output escaped, line breaks converted to `
`, appropriate for browser output 106 | * * `error_log` Output to error log as configured in php.ini 107 | * 108 | * Alternatively, you can provide a callable expecting two params: a message string and the debug level: 109 | * 110 | * $smtp->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";}; 111 | * 112 | * @var string|callable 113 | */ 114 | public $Debugoutput = 'echo'; 115 | /** 116 | * Whether to use VERP. 117 | * @link http://en.wikipedia.org/wiki/Variable_envelope_return_path 118 | * @link http://www.postfix.org/VERP_README.html Info on VERP 119 | * @var boolean 120 | */ 121 | public $do_verp = false; 122 | /** 123 | * The timeout value for connection, in seconds. 124 | * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2 125 | * This needs to be quite high to function correctly with hosts using greetdelay as an anti-spam measure. 126 | * @link http://tools.ietf.org/html/rfc2821#section-4.5.3.2 127 | * @var integer 128 | */ 129 | public $Timeout = 300; 130 | /** 131 | * How long to wait for commands to complete, in seconds. 132 | * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2 133 | * @var integer 134 | */ 135 | public $Timelimit = 300; 136 | /** 137 | * @var array patterns to extract smtp transaction id from smtp reply 138 | * Only first capture group will be use, use non-capturing group to deal with it 139 | * Extend this class to override this property to fulfil your needs. 140 | */ 141 | protected $smtp_transaction_id_patterns = array( 142 | 'exim' => '/[0-9]{3} OK id=(.*)/', 143 | 'sendmail' => '/[0-9]{3} 2.0.0 (.*) Message/', 144 | 'postfix' => '/[0-9]{3} 2.0.0 Ok: queued as (.*)/' 145 | ); 146 | /** 147 | * The socket for the server connection. 148 | * @var resource 149 | */ 150 | protected $smtp_conn; 151 | /** 152 | * Error information, if any, for the last SMTP command. 153 | * @var array 154 | */ 155 | protected $error = array( 156 | 'error' => '', 157 | 'detail' => '', 158 | 'smtp_code' => '', 159 | 'smtp_code_ex' => '' 160 | ); 161 | /** 162 | * The reply the server sent to us for HELO. 163 | * If null, no HELO string has yet been received. 164 | * @var string|null 165 | */ 166 | protected $helo_rply = null; 167 | /** 168 | * The set of SMTP extensions sent in reply to EHLO command. 169 | * Indexes of the array are extension names. 170 | * Value at index 'HELO' or 'EHLO' (according to command that was sent) 171 | * represents the server name. In case of HELO it is the only element of the array. 172 | * Other values can be boolean TRUE or an array containing extension options. 173 | * If null, no HELO/EHLO string has yet been received. 174 | * @var array|null 175 | */ 176 | protected $server_caps = null; 177 | /** 178 | * The most recent reply received from the server. 179 | * @var string 180 | */ 181 | protected $last_reply = ''; 182 | /** 183 | * Output debugging info via a user-selected method. 184 | * @see SMTP::$Debugoutput 185 | * @see SMTP::$do_debug 186 | * @param string $str Debug string to output 187 | * @param integer $level The debug level of this message; see DEBUG_* constants 188 | * @return void 189 | */ 190 | protected function edebug($str, $level = 0) 191 | { 192 | if ($level > $this->do_debug) { 193 | return; 194 | } 195 | //Avoid clash with built-in function names 196 | if (!in_array($this->Debugoutput, array('error_log', 'html', 'echo')) and is_callable($this->Debugoutput)) { 197 | call_user_func($this->Debugoutput, $str, $level); 198 | return; 199 | } 200 | switch ($this->Debugoutput) { 201 | case 'error_log': 202 | //Don't output, just log 203 | error_log($str); 204 | break; 205 | case 'html': 206 | //Cleans up output a bit for a better looking, HTML-safe output 207 | echo htmlentities( 208 | preg_replace('/[\r\n]+/', '', $str), 209 | ENT_QUOTES, 210 | 'UTF-8' 211 | ) 212 | . "
\n"; 213 | break; 214 | case 'echo': 215 | default: 216 | //Normalize line breaks 217 | $str = preg_replace('/(\r\n|\r|\n)/ms', "\n", $str); 218 | echo gmdate('Y-m-d H:i:s') . "\t" . str_replace( 219 | "\n", 220 | "\n \t ", 221 | trim($str) 222 | )."\n"; 223 | } 224 | } 225 | /** 226 | * Connect to an SMTP server. 227 | * @param string $host SMTP server IP or host name 228 | * @param integer $port The port number to connect to 229 | * @param integer $timeout How long to wait for the connection to open 230 | * @param array $options An array of options for stream_context_create() 231 | * @access public 232 | * @return boolean 233 | */ 234 | public function connect($host, $port = null, $timeout = 30, $options = array()) 235 | { 236 | static $streamok; 237 | //This is enabled by default since 5.0.0 but some providers disable it 238 | //Check this once and cache the result 239 | if (is_null($streamok)) { 240 | $streamok = function_exists('stream_socket_client'); 241 | } 242 | // Clear errors to avoid confusion 243 | $this->setError(''); 244 | // Make sure we are __not__ connected 245 | if ($this->connected()) { 246 | // Already connected, generate error 247 | $this->setError('Already connected to a server'); 248 | return false; 249 | } 250 | if (empty($port)) { 251 | $port = self::DEFAULT_SMTP_PORT; 252 | } 253 | // Connect to the SMTP server 254 | $this->edebug( 255 | "Connection: opening to $host:$port, timeout=$timeout, options=".var_export($options, true), 256 | self::DEBUG_CONNECTION 257 | ); 258 | $errno = 0; 259 | $errstr = ''; 260 | if ($streamok) { 261 | $socket_context = stream_context_create($options); 262 | set_error_handler(array($this, 'errorHandler')); 263 | $this->smtp_conn = stream_socket_client( 264 | $host . ":" . $port, 265 | $errno, 266 | $errstr, 267 | $timeout, 268 | STREAM_CLIENT_CONNECT, 269 | $socket_context 270 | ); 271 | restore_error_handler(); 272 | } else { 273 | //Fall back to fsockopen which should work in more places, but is missing some features 274 | $this->edebug( 275 | "Connection: stream_socket_client not available, falling back to fsockopen", 276 | self::DEBUG_CONNECTION 277 | ); 278 | set_error_handler(array($this, 'errorHandler')); 279 | $this->smtp_conn = fsockopen( 280 | $host, 281 | $port, 282 | $errno, 283 | $errstr, 284 | $timeout 285 | ); 286 | restore_error_handler(); 287 | } 288 | // Verify we connected properly 289 | if (!is_resource($this->smtp_conn)) { 290 | $this->setError( 291 | 'Failed to connect to server', 292 | $errno, 293 | $errstr 294 | ); 295 | $this->edebug( 296 | 'SMTP ERROR: ' . $this->error['error'] 297 | . ": $errstr ($errno)", 298 | self::DEBUG_CLIENT 299 | ); 300 | return false; 301 | } 302 | $this->edebug('Connection: opened', self::DEBUG_CONNECTION); 303 | // SMTP server can take longer to respond, give longer timeout for first read 304 | // Windows does not have support for this timeout function 305 | if (substr(PHP_OS, 0, 3) != 'WIN') { 306 | $max = ini_get('max_execution_time'); 307 | // Don't bother if unlimited 308 | if ($max != 0 && $timeout > $max) { 309 | @set_time_limit($timeout); 310 | } 311 | stream_set_timeout($this->smtp_conn, $timeout, 0); 312 | } 313 | // Get any announcement 314 | $announce = $this->get_lines(); 315 | $this->edebug('SERVER -> CLIENT: ' . $announce, self::DEBUG_SERVER); 316 | return true; 317 | } 318 | /** 319 | * Initiate a TLS (encrypted) session. 320 | * @access public 321 | * @return boolean 322 | */ 323 | public function startTLS() 324 | { 325 | if (!$this->sendCommand('STARTTLS', 'STARTTLS', 220)) { 326 | return false; 327 | } 328 | //Allow the best TLS version(s) we can 329 | $crypto_method = STREAM_CRYPTO_METHOD_TLS_CLIENT; 330 | //PHP 5.6.7 dropped inclusion of TLS 1.1 and 1.2 in STREAM_CRYPTO_METHOD_TLS_CLIENT 331 | //so add them back in manually if we can 332 | if (defined('STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT')) { 333 | $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT; 334 | $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT; 335 | } 336 | // Begin encrypted connection 337 | if (!stream_socket_enable_crypto( 338 | $this->smtp_conn, 339 | true, 340 | $crypto_method 341 | )) { 342 | return false; 343 | } 344 | return true; 345 | } 346 | /** 347 | * Perform SMTP authentication. 348 | * Must be run after hello(). 349 | * @see hello() 350 | * @param string $username The user name 351 | * @param string $password The password 352 | * @param string $authtype The auth type (PLAIN, LOGIN, CRAM-MD5) 353 | * @param string $realm The auth realm for NTLM 354 | * @param string $workstation The auth workstation for NTLM 355 | * @param null|OAuth $OAuth An optional OAuth instance (@see PHPMailerOAuth) 356 | * @return bool True if successfully authenticated.* @access public 357 | */ 358 | public function authenticate( 359 | $username, 360 | $password, 361 | $authtype = null, 362 | $realm = '', 363 | $workstation = '', 364 | $OAuth = null 365 | ) { 366 | if (!$this->server_caps) { 367 | $this->setError('Authentication is not allowed before HELO/EHLO'); 368 | return false; 369 | } 370 | if (array_key_exists('EHLO', $this->server_caps)) { 371 | // SMTP extensions are available. Let's try to find a proper authentication method 372 | if (!array_key_exists('AUTH', $this->server_caps)) { 373 | $this->setError('Authentication is not allowed at this stage'); 374 | // 'at this stage' means that auth may be allowed after the stage changes 375 | // e.g. after STARTTLS 376 | return false; 377 | } 378 | self::edebug('Auth method requested: ' . ($authtype ? $authtype : 'UNKNOWN'), self::DEBUG_LOWLEVEL); 379 | self::edebug( 380 | 'Auth methods available on the server: ' . implode(',', $this->server_caps['AUTH']), 381 | self::DEBUG_LOWLEVEL 382 | ); 383 | if (empty($authtype)) { 384 | foreach (array('CRAM-MD5', 'LOGIN', 'PLAIN') as $method) { 385 | if (in_array($method, $this->server_caps['AUTH'])) { 386 | $authtype = $method; 387 | break; 388 | } 389 | } 390 | if (empty($authtype)) { 391 | $this->setError('No supported authentication methods found'); 392 | return false; 393 | } 394 | self::edebug('Auth method selected: '.$authtype, self::DEBUG_LOWLEVEL); 395 | } 396 | if (!in_array($authtype, $this->server_caps['AUTH'])) { 397 | $this->setError("The requested authentication method \"$authtype\" is not supported by the server"); 398 | return false; 399 | } 400 | } elseif (empty($authtype)) { 401 | $authtype = 'LOGIN'; 402 | } 403 | switch ($authtype) { 404 | case 'PLAIN': 405 | // Start authentication 406 | if (!$this->sendCommand('AUTH', 'AUTH PLAIN', 334)) { 407 | return false; 408 | } 409 | // Send encoded username and password 410 | if (!$this->sendCommand( 411 | 'User & Password', 412 | base64_encode("\0" . $username . "\0" . $password), 413 | 235 414 | ) 415 | ) { 416 | return false; 417 | } 418 | break; 419 | case 'LOGIN': 420 | // Start authentication 421 | if (!$this->sendCommand('AUTH', 'AUTH LOGIN', 334)) { 422 | return false; 423 | } 424 | if (!$this->sendCommand("Username", base64_encode($username), 334)) { 425 | return false; 426 | } 427 | if (!$this->sendCommand("Password", base64_encode($password), 235)) { 428 | return false; 429 | } 430 | break; 431 | case 'CRAM-MD5': 432 | // Start authentication 433 | if (!$this->sendCommand('AUTH CRAM-MD5', 'AUTH CRAM-MD5', 334)) { 434 | return false; 435 | } 436 | // Get the challenge 437 | $challenge = base64_decode(substr($this->last_reply, 4)); 438 | // Build the response 439 | $response = $username . ' ' . $this->hmac($challenge, $password); 440 | // send encoded credentials 441 | return $this->sendCommand('Username', base64_encode($response), 235); 442 | default: 443 | $this->setError("Authentication method \"$authtype\" is not supported"); 444 | return false; 445 | } 446 | return true; 447 | } 448 | /** 449 | * Calculate an MD5 HMAC hash. 450 | * Works like hash_hmac('md5', $data, $key) 451 | * in case that function is not available 452 | * @param string $data The data to hash 453 | * @param string $key The key to hash with 454 | * @access protected 455 | * @return string 456 | */ 457 | protected function hmac($data, $key) 458 | { 459 | if (function_exists('hash_hmac')) { 460 | return hash_hmac('md5', $data, $key); 461 | } 462 | // The following borrowed from 463 | // http://php.net/manual/en/function.mhash.php#27225 464 | // RFC 2104 HMAC implementation for php. 465 | // Creates an md5 HMAC. 466 | // Eliminates the need to install mhash to compute a HMAC 467 | // by Lance Rushing 468 | $bytelen = 64; // byte length for md5 469 | if (strlen($key) > $bytelen) { 470 | $key = pack('H*', md5($key)); 471 | } 472 | $key = str_pad($key, $bytelen, chr(0x00)); 473 | $ipad = str_pad('', $bytelen, chr(0x36)); 474 | $opad = str_pad('', $bytelen, chr(0x5c)); 475 | $k_ipad = $key ^ $ipad; 476 | $k_opad = $key ^ $opad; 477 | return md5($k_opad . pack('H*', md5($k_ipad . $data))); 478 | } 479 | /** 480 | * Check connection state. 481 | * @access public 482 | * @return boolean True if connected. 483 | */ 484 | public function connected() 485 | { 486 | if (is_resource($this->smtp_conn)) { 487 | $sock_status = stream_get_meta_data($this->smtp_conn); 488 | if ($sock_status['eof']) { 489 | // The socket is valid but we are not connected 490 | $this->edebug( 491 | 'SMTP NOTICE: EOF caught while checking if connected', 492 | self::DEBUG_CLIENT 493 | ); 494 | $this->close(); 495 | return false; 496 | } 497 | return true; // everything looks good 498 | } 499 | return false; 500 | } 501 | /** 502 | * Close the socket and clean up the state of the class. 503 | * Don't use this function without first trying to use QUIT. 504 | * @see quit() 505 | * @access public 506 | * @return void 507 | */ 508 | public function close() 509 | { 510 | $this->setError(''); 511 | $this->server_caps = null; 512 | $this->helo_rply = null; 513 | if (is_resource($this->smtp_conn)) { 514 | // close the connection and cleanup 515 | fclose($this->smtp_conn); 516 | $this->smtp_conn = null; //Makes for cleaner serialization 517 | $this->edebug('Connection: closed', self::DEBUG_CONNECTION); 518 | } 519 | } 520 | /** 521 | * Send an SMTP DATA command. 522 | * Issues a data command and sends the msg_data to the server, 523 | * finializing the mail transaction. $msg_data is the message 524 | * that is to be send with the headers. Each header needs to be 525 | * on a single line followed by a with the message headers 526 | * and the message body being separated by and additional . 527 | * Implements rfc 821: DATA 528 | * @param string $msg_data Message data to send 529 | * @access public 530 | * @return boolean 531 | */ 532 | public function data($msg_data) 533 | { 534 | //This will use the standard timelimit 535 | if (!$this->sendCommand('DATA', 'DATA', 354)) { 536 | return false; 537 | } 538 | /* The server is ready to accept data! 539 | * According to rfc821 we should not send more than 1000 characters on a single line (including the CRLF) 540 | * so we will break the data up into lines by \r and/or \n then if needed we will break each of those into 541 | * smaller lines to fit within the limit. 542 | * We will also look for lines that start with a '.' and prepend an additional '.'. 543 | * NOTE: this does not count towards line-length limit. 544 | */ 545 | // Normalize line breaks before exploding 546 | $lines = explode("\n", str_replace(array("\r\n", "\r"), "\n", $msg_data)); 547 | /* To distinguish between a complete RFC822 message and a plain message body, we check if the first field 548 | * of the first line (':' separated) does not contain a space then it _should_ be a header and we will 549 | * process all lines before a blank line as headers. 550 | */ 551 | $field = substr($lines[0], 0, strpos($lines[0], ':')); 552 | $in_headers = false; 553 | if (!empty($field) && strpos($field, ' ') === false) { 554 | $in_headers = true; 555 | } 556 | foreach ($lines as $line) { 557 | $lines_out = array(); 558 | if ($in_headers and $line == '') { 559 | $in_headers = false; 560 | } 561 | //Break this line up into several smaller lines if it's too long 562 | //Micro-optimisation: isset($str[$len]) is faster than (strlen($str) > $len), 563 | while (isset($line[self::MAX_LINE_LENGTH])) { 564 | //Working backwards, try to find a space within the last MAX_LINE_LENGTH chars of the line to break on 565 | //so as to avoid breaking in the middle of a word 566 | $pos = strrpos(substr($line, 0, self::MAX_LINE_LENGTH), ' '); 567 | //Deliberately matches both false and 0 568 | if (!$pos) { 569 | //No nice break found, add a hard break 570 | $pos = self::MAX_LINE_LENGTH - 1; 571 | $lines_out[] = substr($line, 0, $pos); 572 | $line = substr($line, $pos); 573 | } else { 574 | //Break at the found point 575 | $lines_out[] = substr($line, 0, $pos); 576 | //Move along by the amount we dealt with 577 | $line = substr($line, $pos + 1); 578 | } 579 | //If processing headers add a LWSP-char to the front of new line RFC822 section 3.1.1 580 | if ($in_headers) { 581 | $line = "\t" . $line; 582 | } 583 | } 584 | $lines_out[] = $line; 585 | //Send the lines to the server 586 | foreach ($lines_out as $line_out) { 587 | //RFC2821 section 4.5.2 588 | if (!empty($line_out) and $line_out[0] == '.') { 589 | $line_out = '.' . $line_out; 590 | } 591 | $this->client_send($line_out . self::CRLF); 592 | } 593 | } 594 | //Message data has been sent, complete the command 595 | //Increase timelimit for end of DATA command 596 | $savetimelimit = $this->Timelimit; 597 | $this->Timelimit = $this->Timelimit * 2; 598 | $result = $this->sendCommand('DATA END', '.', 250); 599 | //Restore timelimit 600 | $this->Timelimit = $savetimelimit; 601 | return $result; 602 | } 603 | /** 604 | * Send an SMTP HELO or EHLO command. 605 | * Used to identify the sending server to the receiving server. 606 | * This makes sure that client and server are in a known state. 607 | * Implements RFC 821: HELO 608 | * and RFC 2821 EHLO. 609 | * @param string $host The host name or IP to connect to 610 | * @access public 611 | * @return boolean 612 | */ 613 | public function hello($host = '') 614 | { 615 | //Try extended hello first (RFC 2821) 616 | return (boolean)($this->sendHello('EHLO', $host) or $this->sendHello('HELO', $host)); 617 | } 618 | /** 619 | * Send an SMTP HELO or EHLO command. 620 | * Low-level implementation used by hello() 621 | * @see hello() 622 | * @param string $hello The HELO string 623 | * @param string $host The hostname to say we are 624 | * @access protected 625 | * @return boolean 626 | */ 627 | protected function sendHello($hello, $host) 628 | { 629 | $noerror = $this->sendCommand($hello, $hello . ' ' . $host, 250); 630 | $this->helo_rply = $this->last_reply; 631 | if ($noerror) { 632 | $this->parseHelloFields($hello); 633 | } else { 634 | $this->server_caps = null; 635 | } 636 | return $noerror; 637 | } 638 | /** 639 | * Parse a reply to HELO/EHLO command to discover server extensions. 640 | * In case of HELO, the only parameter that can be discovered is a server name. 641 | * @access protected 642 | * @param string $type - 'HELO' or 'EHLO' 643 | */ 644 | protected function parseHelloFields($type) 645 | { 646 | $this->server_caps = array(); 647 | $lines = explode("\n", $this->helo_rply); 648 | foreach ($lines as $n => $s) { 649 | //First 4 chars contain response code followed by - or space 650 | $s = trim(substr($s, 4)); 651 | if (empty($s)) { 652 | continue; 653 | } 654 | $fields = explode(' ', $s); 655 | if (!empty($fields)) { 656 | if (!$n) { 657 | $name = $type; 658 | $fields = $fields[0]; 659 | } else { 660 | $name = array_shift($fields); 661 | switch ($name) { 662 | case 'SIZE': 663 | $fields = ($fields ? $fields[0] : 0); 664 | break; 665 | case 'AUTH': 666 | if (!is_array($fields)) { 667 | $fields = array(); 668 | } 669 | break; 670 | default: 671 | $fields = true; 672 | } 673 | } 674 | $this->server_caps[$name] = $fields; 675 | } 676 | } 677 | } 678 | /** 679 | * Send an SMTP MAIL command. 680 | * Starts a mail transaction from the email address specified in 681 | * $from. Returns true if successful or false otherwise. If True 682 | * the mail transaction is started and then one or more recipient 683 | * commands may be called followed by a data command. 684 | * Implements rfc 821: MAIL FROM: 685 | * @param string $from Source address of this message 686 | * @access public 687 | * @return boolean 688 | */ 689 | public function mail($from) 690 | { 691 | $useVerp = ($this->do_verp ? ' XVERP' : ''); 692 | return $this->sendCommand( 693 | 'MAIL FROM', 694 | 'MAIL FROM:<' . $from . '>' . $useVerp, 695 | 250 696 | ); 697 | } 698 | /** 699 | * Send an SMTP QUIT command. 700 | * Closes the socket if there is no error or the $close_on_error argument is true. 701 | * Implements from rfc 821: QUIT 702 | * @param boolean $close_on_error Should the connection close if an error occurs? 703 | * @access public 704 | * @return boolean 705 | */ 706 | public function quit($close_on_error = true) 707 | { 708 | $noerror = $this->sendCommand('QUIT', 'QUIT', 221); 709 | $err = $this->error; //Save any error 710 | if ($noerror or $close_on_error) { 711 | $this->close(); 712 | $this->error = $err; //Restore any error from the quit command 713 | } 714 | return $noerror; 715 | } 716 | /** 717 | * Send an SMTP RCPT command. 718 | * Sets the TO argument to $toaddr. 719 | * Returns true if the recipient was accepted false if it was rejected. 720 | * Implements from rfc 821: RCPT TO: 721 | * @param string $address The address the message is being sent to 722 | * @access public 723 | * @return boolean 724 | */ 725 | public function recipient($address) 726 | { 727 | return $this->sendCommand( 728 | 'RCPT TO', 729 | 'RCPT TO:<' . $address . '>', 730 | array(250, 251) 731 | ); 732 | } 733 | /** 734 | * Send an SMTP RSET command. 735 | * Abort any transaction that is currently in progress. 736 | * Implements rfc 821: RSET 737 | * @access public 738 | * @return boolean True on success. 739 | */ 740 | public function reset() 741 | { 742 | return $this->sendCommand('RSET', 'RSET', 250); 743 | } 744 | /** 745 | * Send a command to an SMTP server and check its return code. 746 | * @param string $command The command name - not sent to the server 747 | * @param string $commandstring The actual command to send 748 | * @param integer|array $expect One or more expected integer success codes 749 | * @access protected 750 | * @return boolean True on success. 751 | */ 752 | protected function sendCommand($command, $commandstring, $expect) 753 | { 754 | if (!$this->connected()) { 755 | $this->setError("Called $command without being connected"); 756 | return false; 757 | } 758 | //Reject line breaks in all commands 759 | if (strpos($commandstring, "\n") !== false or strpos($commandstring, "\r") !== false) { 760 | $this->setError("Command '$command' contained line breaks"); 761 | return false; 762 | } 763 | $this->client_send($commandstring . self::CRLF); 764 | $this->last_reply = $this->get_lines(); 765 | // Fetch SMTP code and possible error code explanation 766 | $matches = array(); 767 | if (preg_match("/^([0-9]{3})[ -](?:([0-9]\\.[0-9]\\.[0-9]) )?/", $this->last_reply, $matches)) { 768 | $code = $matches[1]; 769 | $code_ex = (count($matches) > 2 ? $matches[2] : null); 770 | // Cut off error code from each response line 771 | $detail = preg_replace( 772 | "/{$code}[ -]".($code_ex ? str_replace('.', '\\.', $code_ex).' ' : '')."/m", 773 | '', 774 | $this->last_reply 775 | ); 776 | } else { 777 | // Fall back to simple parsing if regex fails 778 | $code = substr($this->last_reply, 0, 3); 779 | $code_ex = null; 780 | $detail = substr($this->last_reply, 4); 781 | } 782 | $this->edebug('SERVER -> CLIENT: ' . $this->last_reply, self::DEBUG_SERVER); 783 | if (!in_array($code, (array)$expect)) { 784 | $this->setError( 785 | "$command command failed", 786 | $detail, 787 | $code, 788 | $code_ex 789 | ); 790 | $this->edebug( 791 | 'SMTP ERROR: ' . $this->error['error'] . ': ' . $this->last_reply, 792 | self::DEBUG_CLIENT 793 | ); 794 | return false; 795 | } 796 | $this->setError(''); 797 | return true; 798 | } 799 | /** 800 | * Send an SMTP SAML command. 801 | * Starts a mail transaction from the email address specified in $from. 802 | * Returns true if successful or false otherwise. If True 803 | * the mail transaction is started and then one or more recipient 804 | * commands may be called followed by a data command. This command 805 | * will send the message to the users terminal if they are logged 806 | * in and send them an email. 807 | * Implements rfc 821: SAML FROM: 808 | * @param string $from The address the message is from 809 | * @access public 810 | * @return boolean 811 | */ 812 | public function sendAndMail($from) 813 | { 814 | return $this->sendCommand('SAML', "SAML FROM:$from", 250); 815 | } 816 | /** 817 | * Send an SMTP VRFY command. 818 | * @param string $name The name to verify 819 | * @access public 820 | * @return boolean 821 | */ 822 | public function verify($name) 823 | { 824 | return $this->sendCommand('VRFY', "VRFY $name", array(250, 251)); 825 | } 826 | /** 827 | * Send an SMTP NOOP command. 828 | * Used to keep keep-alives alive, doesn't actually do anything 829 | * @access public 830 | * @return boolean 831 | */ 832 | public function noop() 833 | { 834 | return $this->sendCommand('NOOP', 'NOOP', 250); 835 | } 836 | /** 837 | * Send an SMTP TURN command. 838 | * This is an optional command for SMTP that this class does not support. 839 | * This method is here to make the RFC821 Definition complete for this class 840 | * and _may_ be implemented in future 841 | * Implements from rfc 821: TURN 842 | * @access public 843 | * @return boolean 844 | */ 845 | public function turn() 846 | { 847 | $this->setError('The SMTP TURN command is not implemented'); 848 | $this->edebug('SMTP NOTICE: ' . $this->error['error'], self::DEBUG_CLIENT); 849 | return false; 850 | } 851 | /** 852 | * Send raw data to the server. 853 | * @param string $data The data to send 854 | * @access public 855 | * @return integer|boolean The number of bytes sent to the server or false on error 856 | */ 857 | public function client_send($data) 858 | { 859 | $this->edebug("CLIENT -> SERVER: $data", self::DEBUG_CLIENT); 860 | return fwrite($this->smtp_conn, $data); 861 | } 862 | /** 863 | * Get the latest error. 864 | * @access public 865 | * @return array 866 | */ 867 | public function getError() 868 | { 869 | return $this->error; 870 | } 871 | /** 872 | * Get SMTP extensions available on the server 873 | * @access public 874 | * @return array|null 875 | */ 876 | public function getServerExtList() 877 | { 878 | return $this->server_caps; 879 | } 880 | /** 881 | * A multipurpose method 882 | * The method works in three ways, dependent on argument value and current state 883 | * 1. HELO/EHLO was not sent - returns null and set up $this->error 884 | * 2. HELO was sent 885 | * $name = 'HELO': returns server name 886 | * $name = 'EHLO': returns boolean false 887 | * $name = any string: returns null and set up $this->error 888 | * 3. EHLO was sent 889 | * $name = 'HELO'|'EHLO': returns server name 890 | * $name = any string: if extension $name exists, returns boolean True 891 | * or its options. Otherwise returns boolean False 892 | * In other words, one can use this method to detect 3 conditions: 893 | * - null returned: handshake was not or we don't know about ext (refer to $this->error) 894 | * - false returned: the requested feature exactly not exists 895 | * - positive value returned: the requested feature exists 896 | * @param string $name Name of SMTP extension or 'HELO'|'EHLO' 897 | * @return mixed 898 | */ 899 | public function getServerExt($name) 900 | { 901 | if (!$this->server_caps) { 902 | $this->setError('No HELO/EHLO was sent'); 903 | return null; 904 | } 905 | // the tight logic knot ;) 906 | if (!array_key_exists($name, $this->server_caps)) { 907 | if ($name == 'HELO') { 908 | return $this->server_caps['EHLO']; 909 | } 910 | if ($name == 'EHLO' || array_key_exists('EHLO', $this->server_caps)) { 911 | return false; 912 | } 913 | $this->setError('HELO handshake was used. Client knows nothing about server extensions'); 914 | return null; 915 | } 916 | return $this->server_caps[$name]; 917 | } 918 | /** 919 | * Get the last reply from the server. 920 | * @access public 921 | * @return string 922 | */ 923 | public function getLastReply() 924 | { 925 | return $this->last_reply; 926 | } 927 | /** 928 | * Read the SMTP server's response. 929 | * Either before eof or socket timeout occurs on the operation. 930 | * With SMTP we can tell if we have more lines to read if the 931 | * 4th character is '-' symbol. If it is a space then we don't 932 | * need to read anything else. 933 | * @access protected 934 | * @return string 935 | */ 936 | protected function get_lines() 937 | { 938 | // If the connection is bad, give up straight away 939 | if (!is_resource($this->smtp_conn)) { 940 | return ''; 941 | } 942 | $data = ''; 943 | $endtime = 0; 944 | stream_set_timeout($this->smtp_conn, $this->Timeout); 945 | if ($this->Timelimit > 0) { 946 | $endtime = time() + $this->Timelimit; 947 | } 948 | while (is_resource($this->smtp_conn) && !feof($this->smtp_conn)) { 949 | $str = @fgets($this->smtp_conn, 515); 950 | $this->edebug("SMTP -> get_lines(): \$data is \"$data\"", self::DEBUG_LOWLEVEL); 951 | $this->edebug("SMTP -> get_lines(): \$str is \"$str\"", self::DEBUG_LOWLEVEL); 952 | $data .= $str; 953 | // If 4th character is a space, we are done reading, break the loop, micro-optimisation over strlen 954 | if ((isset($str[3]) and $str[3] == ' ')) { 955 | break; 956 | } 957 | // Timed-out? Log and break 958 | $info = stream_get_meta_data($this->smtp_conn); 959 | if ($info['timed_out']) { 960 | $this->edebug( 961 | 'SMTP -> get_lines(): timed-out (' . $this->Timeout . ' sec)', 962 | self::DEBUG_LOWLEVEL 963 | ); 964 | break; 965 | } 966 | // Now check if reads took too long 967 | if ($endtime and time() > $endtime) { 968 | $this->edebug( 969 | 'SMTP -> get_lines(): timelimit reached ('. 970 | $this->Timelimit . ' sec)', 971 | self::DEBUG_LOWLEVEL 972 | ); 973 | break; 974 | } 975 | } 976 | return $data; 977 | } 978 | /** 979 | * Enable or disable VERP address generation. 980 | * @param boolean $enabled 981 | */ 982 | public function setVerp($enabled = false) 983 | { 984 | $this->do_verp = $enabled; 985 | } 986 | /** 987 | * Get VERP address generation mode. 988 | * @return boolean 989 | */ 990 | public function getVerp() 991 | { 992 | return $this->do_verp; 993 | } 994 | /** 995 | * Set error messages and codes. 996 | * @param string $message The error message 997 | * @param string $detail Further detail on the error 998 | * @param string $smtp_code An associated SMTP error code 999 | * @param string $smtp_code_ex Extended SMTP code 1000 | */ 1001 | protected function setError($message, $detail = '', $smtp_code = '', $smtp_code_ex = '') 1002 | { 1003 | $this->error = array( 1004 | 'error' => $message, 1005 | 'detail' => $detail, 1006 | 'smtp_code' => $smtp_code, 1007 | 'smtp_code_ex' => $smtp_code_ex 1008 | ); 1009 | } 1010 | /** 1011 | * Set debug output method. 1012 | * @param string|callable $method The name of the mechanism to use for debugging output, or a callable to handle it. 1013 | */ 1014 | public function setDebugOutput($method = 'echo') 1015 | { 1016 | $this->Debugoutput = $method; 1017 | } 1018 | /** 1019 | * Get debug output method. 1020 | * @return string 1021 | */ 1022 | public function getDebugOutput() 1023 | { 1024 | return $this->Debugoutput; 1025 | } 1026 | /** 1027 | * Set debug output level. 1028 | * @param integer $level 1029 | */ 1030 | public function setDebugLevel($level = 0) 1031 | { 1032 | $this->do_debug = $level; 1033 | } 1034 | /** 1035 | * Get debug output level. 1036 | * @return integer 1037 | */ 1038 | public function getDebugLevel() 1039 | { 1040 | return $this->do_debug; 1041 | } 1042 | /** 1043 | * Set SMTP timeout. 1044 | * @param integer $timeout 1045 | */ 1046 | public function setTimeout($timeout = 0) 1047 | { 1048 | $this->Timeout = $timeout; 1049 | } 1050 | /** 1051 | * Get SMTP timeout. 1052 | * @return integer 1053 | */ 1054 | public function getTimeout() 1055 | { 1056 | return $this->Timeout; 1057 | } 1058 | /** 1059 | * Reports an error number and string. 1060 | * @param integer $errno The error number returned by PHP. 1061 | * @param string $errmsg The error message returned by PHP. 1062 | */ 1063 | protected function errorHandler($errno, $errmsg) 1064 | { 1065 | $notice = 'Connection: Failed to connect to server.'; 1066 | $this->setError( 1067 | $notice, 1068 | $errno, 1069 | $errmsg 1070 | ); 1071 | $this->edebug( 1072 | $notice . ' Error number ' . $errno . '. "Error notice: ' . $errmsg, 1073 | self::DEBUG_CONNECTION 1074 | ); 1075 | } 1076 | /** 1077 | * Will return the ID of the last smtp transaction based on a list of patterns provided 1078 | * in SMTP::$smtp_transaction_id_patterns. 1079 | * If no reply has been received yet, it will return null. 1080 | * If no pattern has been matched, it will return false. 1081 | * @return bool|null|string 1082 | */ 1083 | public function getLastTransactionID() 1084 | { 1085 | $reply = $this->getLastReply(); 1086 | if (empty($reply)) { 1087 | return null; 1088 | } 1089 | foreach($this->smtp_transaction_id_patterns as $smtp_transaction_id_pattern) { 1090 | if(preg_match($smtp_transaction_id_pattern, $reply, $matches)) { 1091 | return $matches[1]; 1092 | } 1093 | } 1094 | return false; 1095 | } 1096 | } 1097 | 1098 | /** 1099 | * PHPMailer - PHP email creation and transport class. 1100 | * PHP Version 5 1101 | * @package PHPMailer 1102 | * @link https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project 1103 | * @author Marcus Bointon (Synchro/coolbru) 1104 | * @author Jim Jagielski (jimjag) 1105 | * @author Andy Prevost (codeworxtech) 1106 | * @author Brent R. Matzelle (original founder) 1107 | * @copyright 2012 - 2014 Marcus Bointon 1108 | * @copyright 2010 - 2012 Jim Jagielski 1109 | * @copyright 2004 - 2009 Andy Prevost 1110 | * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License 1111 | * @note This program is distributed in the hope that it will be useful - WITHOUT 1112 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 1113 | * FITNESS FOR A PARTICULAR PURPOSE. 1114 | */ 1115 | /** 1116 | * PHPMailer - PHP email creation and transport class. 1117 | * @package PHPMailer 1118 | * @author Marcus Bointon (Synchro/coolbru) 1119 | * @author Jim Jagielski (jimjag) 1120 | * @author Andy Prevost (codeworxtech) 1121 | * @author Brent R. Matzelle (original founder) 1122 | */ 1123 | class PHPMailer 1124 | { 1125 | /** 1126 | * The PHPMailer Version number. 1127 | * @var string 1128 | */ 1129 | public $Version = '5.2.22'; 1130 | /** 1131 | * Email priority. 1132 | * Options: null (default), 1 = High, 3 = Normal, 5 = low. 1133 | * When null, the header is not set at all. 1134 | * @var integer 1135 | */ 1136 | public $Priority = null; 1137 | /** 1138 | * The character set of the message. 1139 | * @var string 1140 | */ 1141 | public $CharSet = 'iso-8859-1'; 1142 | /** 1143 | * The MIME Content-type of the message. 1144 | * @var string 1145 | */ 1146 | public $ContentType = 'text/plain'; 1147 | /** 1148 | * The message encoding. 1149 | * Options: "8bit", "7bit", "binary", "base64", and "quoted-printable". 1150 | * @var string 1151 | */ 1152 | public $Encoding = '8bit'; 1153 | /** 1154 | * Holds the most recent mailer error message. 1155 | * @var string 1156 | */ 1157 | public $ErrorInfo = ''; 1158 | /** 1159 | * The From email address for the message. 1160 | * @var string 1161 | */ 1162 | public $From = 'root@localhost'; 1163 | /** 1164 | * The From name of the message. 1165 | * @var string 1166 | */ 1167 | public $FromName = 'Root User'; 1168 | /** 1169 | * The Sender email (Return-Path) of the message. 1170 | * If not empty, will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode. 1171 | * @var string 1172 | */ 1173 | public $Sender = ''; 1174 | /** 1175 | * The Return-Path of the message. 1176 | * If empty, it will be set to either From or Sender. 1177 | * @var string 1178 | * @deprecated Email senders should never set a return-path header; 1179 | * it's the receiver's job (RFC5321 section 4.4), so this no longer does anything. 1180 | * @link https://tools.ietf.org/html/rfc5321#section-4.4 RFC5321 reference 1181 | */ 1182 | public $ReturnPath = ''; 1183 | /** 1184 | * The Subject of the message. 1185 | * @var string 1186 | */ 1187 | public $Subject = ''; 1188 | /** 1189 | * An HTML or plain text message body. 1190 | * If HTML then call isHTML(true). 1191 | * @var string 1192 | */ 1193 | public $Body = ''; 1194 | /** 1195 | * The plain-text message body. 1196 | * This body can be read by mail clients that do not have HTML email 1197 | * capability such as mutt & Eudora. 1198 | * Clients that can read HTML will view the normal Body. 1199 | * @var string 1200 | */ 1201 | public $AltBody = ''; 1202 | /** 1203 | * An iCal message part body. 1204 | * Only supported in simple alt or alt_inline message types 1205 | * To generate iCal events, use the bundled extras/EasyPeasyICS.php class or iCalcreator 1206 | * @link http://sprain.ch/blog/downloads/php-class-easypeasyics-create-ical-files-with-php/ 1207 | * @link http://kigkonsult.se/iCalcreator/ 1208 | * @var string 1209 | */ 1210 | public $Ical = ''; 1211 | /** 1212 | * The complete compiled MIME message body. 1213 | * @access protected 1214 | * @var string 1215 | */ 1216 | protected $MIMEBody = ''; 1217 | /** 1218 | * The complete compiled MIME message headers. 1219 | * @var string 1220 | * @access protected 1221 | */ 1222 | protected $MIMEHeader = ''; 1223 | /** 1224 | * Extra headers that createHeader() doesn't fold in. 1225 | * @var string 1226 | * @access protected 1227 | */ 1228 | protected $mailHeader = ''; 1229 | /** 1230 | * Word-wrap the message body to this number of chars. 1231 | * Set to 0 to not wrap. A useful value here is 78, for RFC2822 section 2.1.1 compliance. 1232 | * @var integer 1233 | */ 1234 | public $WordWrap = 0; 1235 | /** 1236 | * Which method to use to send mail. 1237 | * Options: "mail", "sendmail", or "smtp". 1238 | * @var string 1239 | */ 1240 | public $Mailer = 'mail'; 1241 | /** 1242 | * The path to the sendmail program. 1243 | * @var string 1244 | */ 1245 | public $Sendmail = '/usr/sbin/sendmail'; 1246 | /** 1247 | * Whether mail() uses a fully sendmail-compatible MTA. 1248 | * One which supports sendmail's "-oi -f" options. 1249 | * @var boolean 1250 | */ 1251 | public $UseSendmailOptions = true; 1252 | /** 1253 | * Path to PHPMailer plugins. 1254 | * Useful if the SMTP class is not in the PHP include path. 1255 | * @var string 1256 | * @deprecated Should not be needed now there is an autoloader. 1257 | */ 1258 | public $PluginDir = ''; 1259 | /** 1260 | * The email address that a reading confirmation should be sent to, also known as read receipt. 1261 | * @var string 1262 | */ 1263 | public $ConfirmReadingTo = ''; 1264 | /** 1265 | * The hostname to use in the Message-ID header and as default HELO string. 1266 | * If empty, PHPMailer attempts to find one with, in order, 1267 | * $_SERVER['SERVER_NAME'], gethostname(), php_uname('n'), or the value 1268 | * 'localhost.localdomain'. 1269 | * @var string 1270 | */ 1271 | public $Hostname = ''; 1272 | /** 1273 | * An ID to be used in the Message-ID header. 1274 | * If empty, a unique id will be generated. 1275 | * You can set your own, but it must be in the format "", 1276 | * as defined in RFC5322 section 3.6.4 or it will be ignored. 1277 | * @see https://tools.ietf.org/html/rfc5322#section-3.6.4 1278 | * @var string 1279 | */ 1280 | public $MessageID = ''; 1281 | /** 1282 | * The message Date to be used in the Date header. 1283 | * If empty, the current date will be added. 1284 | * @var string 1285 | */ 1286 | public $MessageDate = ''; 1287 | /** 1288 | * SMTP hosts. 1289 | * Either a single hostname or multiple semicolon-delimited hostnames. 1290 | * You can also specify a different port 1291 | * for each host by using this format: [hostname:port] 1292 | * (e.g. "smtp1.example.com:25;smtp2.example.com"). 1293 | * You can also specify encryption type, for example: 1294 | * (e.g. "tls://smtp1.example.com:587;ssl://smtp2.example.com:465"). 1295 | * Hosts will be tried in order. 1296 | * @var string 1297 | */ 1298 | public $Host = 'localhost'; 1299 | /** 1300 | * The default SMTP server port. 1301 | * @var integer 1302 | * @TODO Why is this needed when the SMTP class takes care of it? 1303 | */ 1304 | public $Port = 25; 1305 | /** 1306 | * The SMTP HELO of the message. 1307 | * Default is $Hostname. If $Hostname is empty, PHPMailer attempts to find 1308 | * one with the same method described above for $Hostname. 1309 | * @var string 1310 | * @see PHPMailer::$Hostname 1311 | */ 1312 | public $Helo = ''; 1313 | /** 1314 | * What kind of encryption to use on the SMTP connection. 1315 | * Options: '', 'ssl' or 'tls' 1316 | * @var string 1317 | */ 1318 | public $SMTPSecure = ''; 1319 | /** 1320 | * Whether to enable TLS encryption automatically if a server supports it, 1321 | * even if `SMTPSecure` is not set to 'tls'. 1322 | * Be aware that in PHP >= 5.6 this requires that the server's certificates are valid. 1323 | * @var boolean 1324 | */ 1325 | public $SMTPAutoTLS = true; 1326 | /** 1327 | * Whether to use SMTP authentication. 1328 | * Uses the Username and Password properties. 1329 | * @var boolean 1330 | * @see PHPMailer::$Username 1331 | * @see PHPMailer::$Password 1332 | */ 1333 | public $SMTPAuth = false; 1334 | /** 1335 | * Options array passed to stream_context_create when connecting via SMTP. 1336 | * @var array 1337 | */ 1338 | public $SMTPOptions = array(); 1339 | /** 1340 | * SMTP username. 1341 | * @var string 1342 | */ 1343 | public $Username = ''; 1344 | /** 1345 | * SMTP password. 1346 | * @var string 1347 | */ 1348 | public $Password = ''; 1349 | /** 1350 | * SMTP auth type. 1351 | * Options are CRAM-MD5, LOGIN, PLAIN, attempted in that order if not specified 1352 | * @var string 1353 | */ 1354 | public $AuthType = ''; 1355 | /** 1356 | * SMTP realm. 1357 | * Used for NTLM auth 1358 | * @var string 1359 | */ 1360 | public $Realm = ''; 1361 | /** 1362 | * SMTP workstation. 1363 | * Used for NTLM auth 1364 | * @var string 1365 | */ 1366 | public $Workstation = ''; 1367 | /** 1368 | * The SMTP server timeout in seconds. 1369 | * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2 1370 | * @var integer 1371 | */ 1372 | public $Timeout = 300; 1373 | /** 1374 | * SMTP class debug output mode. 1375 | * Debug output level. 1376 | * Options: 1377 | * * `0` No output 1378 | * * `1` Commands 1379 | * * `2` Data and commands 1380 | * * `3` As 2 plus connection status 1381 | * * `4` Low-level data output 1382 | * @var integer 1383 | * @see SMTP::$do_debug 1384 | */ 1385 | public $SMTPDebug = 0; 1386 | /** 1387 | * How to handle debug output. 1388 | * Options: 1389 | * * `echo` Output plain-text as-is, appropriate for CLI 1390 | * * `html` Output escaped, line breaks converted to `
`, appropriate for browser output 1391 | * * `error_log` Output to error log as configured in php.ini 1392 | * 1393 | * Alternatively, you can provide a callable expecting two params: a message string and the debug level: 1394 | * 1395 | * $mail->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";}; 1396 | * 1397 | * @var string|callable 1398 | * @see SMTP::$Debugoutput 1399 | */ 1400 | public $Debugoutput = 'echo'; 1401 | /** 1402 | * Whether to keep SMTP connection open after each message. 1403 | * If this is set to true then to close the connection 1404 | * requires an explicit call to smtpClose(). 1405 | * @var boolean 1406 | */ 1407 | public $SMTPKeepAlive = false; 1408 | /** 1409 | * Whether to split multiple to addresses into multiple messages 1410 | * or send them all in one message. 1411 | * Only supported in `mail` and `sendmail` transports, not in SMTP. 1412 | * @var boolean 1413 | */ 1414 | public $SingleTo = false; 1415 | /** 1416 | * Storage for addresses when SingleTo is enabled. 1417 | * @var array 1418 | * @TODO This should really not be public 1419 | */ 1420 | public $SingleToArray = array(); 1421 | /** 1422 | * Whether to generate VERP addresses on send. 1423 | * Only applicable when sending via SMTP. 1424 | * @link https://en.wikipedia.org/wiki/Variable_envelope_return_path 1425 | * @link http://www.postfix.org/VERP_README.html Postfix VERP info 1426 | * @var boolean 1427 | */ 1428 | public $do_verp = false; 1429 | /** 1430 | * Whether to allow sending messages with an empty body. 1431 | * @var boolean 1432 | */ 1433 | public $AllowEmpty = false; 1434 | /** 1435 | * The default line ending. 1436 | * @note The default remains "\n". We force CRLF where we know 1437 | * it must be used via self::CRLF. 1438 | * @var string 1439 | */ 1440 | public $LE = "\n"; 1441 | /** 1442 | * DKIM selector. 1443 | * @var string 1444 | */ 1445 | public $DKIM_selector = ''; 1446 | /** 1447 | * DKIM Identity. 1448 | * Usually the email address used as the source of the email. 1449 | * @var string 1450 | */ 1451 | public $DKIM_identity = ''; 1452 | /** 1453 | * DKIM passphrase. 1454 | * Used if your key is encrypted. 1455 | * @var string 1456 | */ 1457 | public $DKIM_passphrase = ''; 1458 | /** 1459 | * DKIM signing domain name. 1460 | * @example 'example.com' 1461 | * @var string 1462 | */ 1463 | public $DKIM_domain = ''; 1464 | /** 1465 | * DKIM private key file path. 1466 | * @var string 1467 | */ 1468 | public $DKIM_private = ''; 1469 | /** 1470 | * DKIM private key string. 1471 | * If set, takes precedence over `$DKIM_private`. 1472 | * @var string 1473 | */ 1474 | public $DKIM_private_string = ''; 1475 | /** 1476 | * Callback Action function name. 1477 | * 1478 | * The function that handles the result of the send email action. 1479 | * It is called out by send() for each email sent. 1480 | * 1481 | * Value can be any php callable: http://www.php.net/is_callable 1482 | * 1483 | * Parameters: 1484 | * boolean $result result of the send action 1485 | * string $to email address of the recipient 1486 | * string $cc cc email addresses 1487 | * string $bcc bcc email addresses 1488 | * string $subject the subject 1489 | * string $body the email body 1490 | * string $from email address of sender 1491 | * @var string 1492 | */ 1493 | public $action_function = ''; 1494 | /** 1495 | * What to put in the X-Mailer header. 1496 | * Options: An empty string for PHPMailer default, whitespace for none, or a string to use 1497 | * @var string 1498 | */ 1499 | public $XMailer = ''; 1500 | /** 1501 | * Which validator to use by default when validating email addresses. 1502 | * May be a callable to inject your own validator, but there are several built-in validators. 1503 | * @see PHPMailer::validateAddress() 1504 | * @var string|callable 1505 | * @static 1506 | */ 1507 | public static $validator = 'auto'; 1508 | /** 1509 | * An instance of the SMTP sender class. 1510 | * @var SMTP 1511 | * @access protected 1512 | */ 1513 | protected $smtp = null; 1514 | /** 1515 | * The array of 'to' names and addresses. 1516 | * @var array 1517 | * @access protected 1518 | */ 1519 | protected $to = array(); 1520 | /** 1521 | * The array of 'cc' names and addresses. 1522 | * @var array 1523 | * @access protected 1524 | */ 1525 | protected $cc = array(); 1526 | /** 1527 | * The array of 'bcc' names and addresses. 1528 | * @var array 1529 | * @access protected 1530 | */ 1531 | protected $bcc = array(); 1532 | /** 1533 | * The array of reply-to names and addresses. 1534 | * @var array 1535 | * @access protected 1536 | */ 1537 | protected $ReplyTo = array(); 1538 | /** 1539 | * An array of all kinds of addresses. 1540 | * Includes all of $to, $cc, $bcc 1541 | * @var array 1542 | * @access protected 1543 | * @see PHPMailer::$to @see PHPMailer::$cc @see PHPMailer::$bcc 1544 | */ 1545 | protected $all_recipients = array(); 1546 | /** 1547 | * An array of names and addresses queued for validation. 1548 | * In send(), valid and non duplicate entries are moved to $all_recipients 1549 | * and one of $to, $cc, or $bcc. 1550 | * This array is used only for addresses with IDN. 1551 | * @var array 1552 | * @access protected 1553 | * @see PHPMailer::$to @see PHPMailer::$cc @see PHPMailer::$bcc 1554 | * @see PHPMailer::$all_recipients 1555 | */ 1556 | protected $RecipientsQueue = array(); 1557 | /** 1558 | * An array of reply-to names and addresses queued for validation. 1559 | * In send(), valid and non duplicate entries are moved to $ReplyTo. 1560 | * This array is used only for addresses with IDN. 1561 | * @var array 1562 | * @access protected 1563 | * @see PHPMailer::$ReplyTo 1564 | */ 1565 | protected $ReplyToQueue = array(); 1566 | /** 1567 | * The array of attachments. 1568 | * @var array 1569 | * @access protected 1570 | */ 1571 | protected $attachment = array(); 1572 | /** 1573 | * The array of custom headers. 1574 | * @var array 1575 | * @access protected 1576 | */ 1577 | protected $CustomHeader = array(); 1578 | /** 1579 | * The most recent Message-ID (including angular brackets). 1580 | * @var string 1581 | * @access protected 1582 | */ 1583 | protected $lastMessageID = ''; 1584 | /** 1585 | * The message's MIME type. 1586 | * @var string 1587 | * @access protected 1588 | */ 1589 | protected $message_type = ''; 1590 | /** 1591 | * The array of MIME boundary strings. 1592 | * @var array 1593 | * @access protected 1594 | */ 1595 | protected $boundary = array(); 1596 | /** 1597 | * The array of available languages. 1598 | * @var array 1599 | * @access protected 1600 | */ 1601 | protected $language = array(); 1602 | /** 1603 | * The number of errors encountered. 1604 | * @var integer 1605 | * @access protected 1606 | */ 1607 | protected $error_count = 0; 1608 | /** 1609 | * The S/MIME certificate file path. 1610 | * @var string 1611 | * @access protected 1612 | */ 1613 | protected $sign_cert_file = ''; 1614 | /** 1615 | * The S/MIME key file path. 1616 | * @var string 1617 | * @access protected 1618 | */ 1619 | protected $sign_key_file = ''; 1620 | /** 1621 | * The optional S/MIME extra certificates ("CA Chain") file path. 1622 | * @var string 1623 | * @access protected 1624 | */ 1625 | protected $sign_extracerts_file = ''; 1626 | /** 1627 | * The S/MIME password for the key. 1628 | * Used only if the key is encrypted. 1629 | * @var string 1630 | * @access protected 1631 | */ 1632 | protected $sign_key_pass = ''; 1633 | /** 1634 | * Whether to throw exceptions for errors. 1635 | * @var boolean 1636 | * @access protected 1637 | */ 1638 | protected $exceptions = false; 1639 | /** 1640 | * Unique ID used for message ID and boundaries. 1641 | * @var string 1642 | * @access protected 1643 | */ 1644 | protected $uniqueid = ''; 1645 | /** 1646 | * Error severity: message only, continue processing. 1647 | */ 1648 | const STOP_MESSAGE = 0; 1649 | /** 1650 | * Error severity: message, likely ok to continue processing. 1651 | */ 1652 | const STOP_CONTINUE = 1; 1653 | /** 1654 | * Error severity: message, plus full stop, critical error reached. 1655 | */ 1656 | const STOP_CRITICAL = 2; 1657 | /** 1658 | * SMTP RFC standard line ending. 1659 | */ 1660 | const CRLF = "\r\n"; 1661 | /** 1662 | * The maximum line length allowed by RFC 2822 section 2.1.1 1663 | * @var integer 1664 | */ 1665 | const MAX_LINE_LENGTH = 998; 1666 | /** 1667 | * Constructor. 1668 | * @param boolean $exceptions Should we throw external exceptions? 1669 | */ 1670 | public function __construct($exceptions = null) 1671 | { 1672 | if ($exceptions !== null) { 1673 | $this->exceptions = (boolean)$exceptions; 1674 | } 1675 | } 1676 | /** 1677 | * Destructor. 1678 | */ 1679 | public function __destruct() 1680 | { 1681 | //Close any open SMTP connection nicely 1682 | $this->smtpClose(); 1683 | } 1684 | /** 1685 | * Call mail() in a safe_mode-aware fashion. 1686 | * Also, unless sendmail_path points to sendmail (or something that 1687 | * claims to be sendmail), don't pass params (not a perfect fix, 1688 | * but it will do) 1689 | * @param string $to To 1690 | * @param string $subject Subject 1691 | * @param string $body Message Body 1692 | * @param string $header Additional Header(s) 1693 | * @param string $params Params 1694 | * @access private 1695 | * @return boolean 1696 | */ 1697 | private function mailPassthru($to, $subject, $body, $header, $params) 1698 | { 1699 | //Check overloading of mail function to avoid double-encoding 1700 | if (ini_get('mbstring.func_overload') & 1) { 1701 | $subject = $this->secureHeader($subject); 1702 | } else { 1703 | $subject = $this->encodeHeader($this->secureHeader($subject)); 1704 | } 1705 | //Can't use additional_parameters in safe_mode, calling mail() with null params breaks 1706 | //@link http://php.net/manual/en/function.mail.php 1707 | if (ini_get('safe_mode') or !$this->UseSendmailOptions or is_null($params)) { 1708 | $result = @mail($to, $subject, $body, $header); 1709 | } else { 1710 | $result = @mail($to, $subject, $body, $header, $params); 1711 | } 1712 | return $result; 1713 | } 1714 | /** 1715 | * Output debugging info via user-defined method. 1716 | * Only generates output if SMTP debug output is enabled (@see SMTP::$do_debug). 1717 | * @see PHPMailer::$Debugoutput 1718 | * @see PHPMailer::$SMTPDebug 1719 | * @param string $str 1720 | */ 1721 | protected function edebug($str) 1722 | { 1723 | if ($this->SMTPDebug <= 0) { 1724 | return; 1725 | } 1726 | //Avoid clash with built-in function names 1727 | if (!in_array($this->Debugoutput, array('error_log', 'html', 'echo')) and is_callable($this->Debugoutput)) { 1728 | call_user_func($this->Debugoutput, $str, $this->SMTPDebug); 1729 | return; 1730 | } 1731 | switch ($this->Debugoutput) { 1732 | case 'error_log': 1733 | //Don't output, just log 1734 | error_log($str); 1735 | break; 1736 | case 'html': 1737 | //Cleans up output a bit for a better looking, HTML-safe output 1738 | echo htmlentities( 1739 | preg_replace('/[\r\n]+/', '', $str), 1740 | ENT_QUOTES, 1741 | 'UTF-8' 1742 | ) 1743 | . "
\n"; 1744 | break; 1745 | case 'echo': 1746 | default: 1747 | //Normalize line breaks 1748 | $str = preg_replace('/\r\n?/ms', "\n", $str); 1749 | echo gmdate('Y-m-d H:i:s') . "\t" . str_replace( 1750 | "\n", 1751 | "\n \t ", 1752 | trim($str) 1753 | ) . "\n"; 1754 | } 1755 | } 1756 | /** 1757 | * Sets message type to HTML or plain. 1758 | * @param boolean $isHtml True for HTML mode. 1759 | * @return void 1760 | */ 1761 | public function isHTML($isHtml = true) 1762 | { 1763 | if ($isHtml) { 1764 | $this->ContentType = 'text/html'; 1765 | } else { 1766 | $this->ContentType = 'text/plain'; 1767 | } 1768 | } 1769 | /** 1770 | * Send messages using SMTP. 1771 | * @return void 1772 | */ 1773 | public function isSMTP() 1774 | { 1775 | $this->Mailer = 'smtp'; 1776 | } 1777 | /** 1778 | * Send messages using PHP's mail() function. 1779 | * @return void 1780 | */ 1781 | public function isMail() 1782 | { 1783 | $this->Mailer = 'mail'; 1784 | } 1785 | /** 1786 | * Send messages using $Sendmail. 1787 | * @return void 1788 | */ 1789 | public function isSendmail() 1790 | { 1791 | $ini_sendmail_path = ini_get('sendmail_path'); 1792 | if (!stristr($ini_sendmail_path, 'sendmail')) { 1793 | $this->Sendmail = '/usr/sbin/sendmail'; 1794 | } else { 1795 | $this->Sendmail = $ini_sendmail_path; 1796 | } 1797 | $this->Mailer = 'sendmail'; 1798 | } 1799 | /** 1800 | * Send messages using qmail. 1801 | * @return void 1802 | */ 1803 | public function isQmail() 1804 | { 1805 | $ini_sendmail_path = ini_get('sendmail_path'); 1806 | if (!stristr($ini_sendmail_path, 'qmail')) { 1807 | $this->Sendmail = '/var/qmail/bin/qmail-inject'; 1808 | } else { 1809 | $this->Sendmail = $ini_sendmail_path; 1810 | } 1811 | $this->Mailer = 'qmail'; 1812 | } 1813 | /** 1814 | * Add a "To" address. 1815 | * @param string $address The email address to send to 1816 | * @param string $name 1817 | * @return boolean true on success, false if address already used or invalid in some way 1818 | */ 1819 | public function addAddress($address, $name = '') 1820 | { 1821 | return $this->addOrEnqueueAnAddress('to', $address, $name); 1822 | } 1823 | /** 1824 | * Add a "CC" address. 1825 | * @note: This function works with the SMTP mailer on win32, not with the "mail" mailer. 1826 | * @param string $address The email address to send to 1827 | * @param string $name 1828 | * @return boolean true on success, false if address already used or invalid in some way 1829 | */ 1830 | public function addCC($address, $name = '') 1831 | { 1832 | return $this->addOrEnqueueAnAddress('cc', $address, $name); 1833 | } 1834 | /** 1835 | * Add a "BCC" address. 1836 | * @note: This function works with the SMTP mailer on win32, not with the "mail" mailer. 1837 | * @param string $address The email address to send to 1838 | * @param string $name 1839 | * @return boolean true on success, false if address already used or invalid in some way 1840 | */ 1841 | public function addBCC($address, $name = '') 1842 | { 1843 | return $this->addOrEnqueueAnAddress('bcc', $address, $name); 1844 | } 1845 | /** 1846 | * Add a "Reply-To" address. 1847 | * @param string $address The email address to reply to 1848 | * @param string $name 1849 | * @return boolean true on success, false if address already used or invalid in some way 1850 | */ 1851 | public function addReplyTo($address, $name = '') 1852 | { 1853 | return $this->addOrEnqueueAnAddress('Reply-To', $address, $name); 1854 | } 1855 | /** 1856 | * Add an address to one of the recipient arrays or to the ReplyTo array. Because PHPMailer 1857 | * can't validate addresses with an IDN without knowing the PHPMailer::$CharSet (that can still 1858 | * be modified after calling this function), addition of such addresses is delayed until send(). 1859 | * Addresses that have been added already return false, but do not throw exceptions. 1860 | * @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo' 1861 | * @param string $address The email address to send, resp. to reply to 1862 | * @param string $name 1863 | * @throws phpmailerException 1864 | * @return boolean true on success, false if address already used or invalid in some way 1865 | * @access protected 1866 | */ 1867 | protected function addOrEnqueueAnAddress($kind, $address, $name) 1868 | { 1869 | $address = trim($address); 1870 | $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim 1871 | if (($pos = strrpos($address, '@')) === false) { 1872 | // At-sign is misssing. 1873 | $error_message = $this->lang('invalid_address') . " (addAnAddress $kind): $address"; 1874 | $this->setError($error_message); 1875 | $this->edebug($error_message); 1876 | if ($this->exceptions) { 1877 | throw new phpmailerException($error_message); 1878 | } 1879 | return false; 1880 | } 1881 | $params = array($kind, $address, $name); 1882 | // Enqueue addresses with IDN until we know the PHPMailer::$CharSet. 1883 | if ($this->has8bitChars(substr($address, ++$pos)) and $this->idnSupported()) { 1884 | if ($kind != 'Reply-To') { 1885 | if (!array_key_exists($address, $this->RecipientsQueue)) { 1886 | $this->RecipientsQueue[$address] = $params; 1887 | return true; 1888 | } 1889 | } else { 1890 | if (!array_key_exists($address, $this->ReplyToQueue)) { 1891 | $this->ReplyToQueue[$address] = $params; 1892 | return true; 1893 | } 1894 | } 1895 | return false; 1896 | } 1897 | // Immediately add standard addresses without IDN. 1898 | return call_user_func_array(array($this, 'addAnAddress'), $params); 1899 | } 1900 | /** 1901 | * Add an address to one of the recipient arrays or to the ReplyTo array. 1902 | * Addresses that have been added already return false, but do not throw exceptions. 1903 | * @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo' 1904 | * @param string $address The email address to send, resp. to reply to 1905 | * @param string $name 1906 | * @throws phpmailerException 1907 | * @return boolean true on success, false if address already used or invalid in some way 1908 | * @access protected 1909 | */ 1910 | protected function addAnAddress($kind, $address, $name = '') 1911 | { 1912 | if (!in_array($kind, array('to', 'cc', 'bcc', 'Reply-To'))) { 1913 | $error_message = $this->lang('Invalid recipient kind: ') . $kind; 1914 | $this->setError($error_message); 1915 | $this->edebug($error_message); 1916 | if ($this->exceptions) { 1917 | throw new phpmailerException($error_message); 1918 | } 1919 | return false; 1920 | } 1921 | if (!$this->validateAddress($address)) { 1922 | $error_message = $this->lang('invalid_address') . " (addAnAddress $kind): $address"; 1923 | $this->setError($error_message); 1924 | $this->edebug($error_message); 1925 | if ($this->exceptions) { 1926 | throw new phpmailerException($error_message); 1927 | } 1928 | return false; 1929 | } 1930 | if ($kind != 'Reply-To') { 1931 | if (!array_key_exists(strtolower($address), $this->all_recipients)) { 1932 | array_push($this->$kind, array($address, $name)); 1933 | $this->all_recipients[strtolower($address)] = true; 1934 | return true; 1935 | } 1936 | } else { 1937 | if (!array_key_exists(strtolower($address), $this->ReplyTo)) { 1938 | $this->ReplyTo[strtolower($address)] = array($address, $name); 1939 | return true; 1940 | } 1941 | } 1942 | return false; 1943 | } 1944 | /** 1945 | * Parse and validate a string containing one or more RFC822-style comma-separated email addresses 1946 | * of the form "display name
" into an array of name/address pairs. 1947 | * Uses the imap_rfc822_parse_adrlist function if the IMAP extension is available. 1948 | * Note that quotes in the name part are removed. 1949 | * @param string $addrstr The address list string 1950 | * @param bool $useimap Whether to use the IMAP extension to parse the list 1951 | * @return array 1952 | * @link http://www.andrew.cmu.edu/user/agreen1/testing/mrbs/web/Mail/RFC822.php A more careful implementation 1953 | */ 1954 | public function parseAddresses($addrstr, $useimap = true) 1955 | { 1956 | $addresses = array(); 1957 | if ($useimap and function_exists('imap_rfc822_parse_adrlist')) { 1958 | //Use this built-in parser if it's available 1959 | $list = imap_rfc822_parse_adrlist($addrstr, ''); 1960 | foreach ($list as $address) { 1961 | if ($address->host != '.SYNTAX-ERROR.') { 1962 | if ($this->validateAddress($address->mailbox . '@' . $address->host)) { 1963 | $addresses[] = array( 1964 | 'name' => (property_exists($address, 'personal') ? $address->personal : ''), 1965 | 'address' => $address->mailbox . '@' . $address->host 1966 | ); 1967 | } 1968 | } 1969 | } 1970 | } else { 1971 | //Use this simpler parser 1972 | $list = explode(',', $addrstr); 1973 | foreach ($list as $address) { 1974 | $address = trim($address); 1975 | //Is there a separate name part? 1976 | if (strpos($address, '<') === false) { 1977 | //No separate name, just use the whole thing 1978 | if ($this->validateAddress($address)) { 1979 | $addresses[] = array( 1980 | 'name' => '', 1981 | 'address' => $address 1982 | ); 1983 | } 1984 | } else { 1985 | list($name, $email) = explode('<', $address); 1986 | $email = trim(str_replace('>', '', $email)); 1987 | if ($this->validateAddress($email)) { 1988 | $addresses[] = array( 1989 | 'name' => trim(str_replace(array('"', "'"), '', $name)), 1990 | 'address' => $email 1991 | ); 1992 | } 1993 | } 1994 | } 1995 | } 1996 | return $addresses; 1997 | } 1998 | /** 1999 | * Set the From and FromName properties. 2000 | * @param string $address 2001 | * @param string $name 2002 | * @param boolean $auto Whether to also set the Sender address, defaults to true 2003 | * @throws phpmailerException 2004 | * @return boolean 2005 | */ 2006 | public function setFrom($address, $name = '', $auto = true) 2007 | { 2008 | $address = trim($address); 2009 | $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim 2010 | // Don't validate now addresses with IDN. Will be done in send(). 2011 | if (($pos = strrpos($address, '@')) === false or 2012 | (!$this->has8bitChars(substr($address, ++$pos)) or !$this->idnSupported()) and 2013 | !$this->validateAddress($address)) { 2014 | $error_message = $this->lang('invalid_address') . " (setFrom) $address"; 2015 | $this->setError($error_message); 2016 | $this->edebug($error_message); 2017 | if ($this->exceptions) { 2018 | throw new phpmailerException($error_message); 2019 | } 2020 | return false; 2021 | } 2022 | $this->From = $address; 2023 | $this->FromName = $name; 2024 | if ($auto) { 2025 | if (empty($this->Sender)) { 2026 | $this->Sender = $address; 2027 | } 2028 | } 2029 | return true; 2030 | } 2031 | /** 2032 | * Return the Message-ID header of the last email. 2033 | * Technically this is the value from the last time the headers were created, 2034 | * but it's also the message ID of the last sent message except in 2035 | * pathological cases. 2036 | * @return string 2037 | */ 2038 | public function getLastMessageID() 2039 | { 2040 | return $this->lastMessageID; 2041 | } 2042 | /** 2043 | * Check that a string looks like an email address. 2044 | * @param string $address The email address to check 2045 | * @param string|callable $patternselect A selector for the validation pattern to use : 2046 | * * `auto` Pick best pattern automatically; 2047 | * * `pcre8` Use the squiloople.com pattern, requires PCRE > 8.0, PHP >= 5.3.2, 5.2.14; 2048 | * * `pcre` Use old PCRE implementation; 2049 | * * `php` Use PHP built-in FILTER_VALIDATE_EMAIL; 2050 | * * `html5` Use the pattern given by the HTML5 spec for 'email' type form input elements. 2051 | * * `noregex` Don't use a regex: super fast, really dumb. 2052 | * Alternatively you may pass in a callable to inject your own validator, for example: 2053 | * PHPMailer::validateAddress('user@example.com', function($address) { 2054 | * return (strpos($address, '@') !== false); 2055 | * }); 2056 | * You can also set the PHPMailer::$validator static to a callable, allowing built-in methods to use your validator. 2057 | * @return boolean 2058 | * @static 2059 | * @access public 2060 | */ 2061 | public static function validateAddress($address, $patternselect = null) 2062 | { 2063 | if (is_null($patternselect)) { 2064 | $patternselect = self::$validator; 2065 | } 2066 | if (is_callable($patternselect)) { 2067 | return call_user_func($patternselect, $address); 2068 | } 2069 | //Reject line breaks in addresses; it's valid RFC5322, but not RFC5321 2070 | if (strpos($address, "\n") !== false or strpos($address, "\r") !== false) { 2071 | return false; 2072 | } 2073 | if (!$patternselect or $patternselect == 'auto') { 2074 | //Check this constant first so it works when extension_loaded() is disabled by safe mode 2075 | //Constant was added in PHP 5.2.4 2076 | if (defined('PCRE_VERSION')) { 2077 | //This pattern can get stuck in a recursive loop in PCRE <= 8.0.2 2078 | if (version_compare(PCRE_VERSION, '8.0.3') >= 0) { 2079 | $patternselect = 'pcre8'; 2080 | } else { 2081 | $patternselect = 'pcre'; 2082 | } 2083 | } elseif (function_exists('extension_loaded') and extension_loaded('pcre')) { 2084 | //Fall back to older PCRE 2085 | $patternselect = 'pcre'; 2086 | } else { 2087 | //Filter_var appeared in PHP 5.2.0 and does not require the PCRE extension 2088 | if (version_compare(PHP_VERSION, '5.2.0') >= 0) { 2089 | $patternselect = 'php'; 2090 | } else { 2091 | $patternselect = 'noregex'; 2092 | } 2093 | } 2094 | } 2095 | switch ($patternselect) { 2096 | case 'pcre8': 2097 | /** 2098 | * Uses the same RFC5322 regex on which FILTER_VALIDATE_EMAIL is based, but allows dotless domains. 2099 | * @link http://squiloople.com/2009/12/20/email-address-validation/ 2100 | * @copyright 2009-2010 Michael Rushton 2101 | * Feel free to use and redistribute this code. But please keep this copyright notice. 2102 | */ 2103 | return (boolean)preg_match( 2104 | '/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)' . 2105 | '((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)' . 2106 | '(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)' . 2107 | '([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*' . 2108 | '(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)' . 2109 | '(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}' . 2110 | '|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:' . 2111 | '|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}' . 2112 | '|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD', 2113 | $address 2114 | ); 2115 | case 'pcre': 2116 | //An older regex that doesn't need a recent PCRE 2117 | return (boolean)preg_match( 2118 | '/^(?!(?>"?(?>\\\[ -~]|[^"])"?){255,})(?!(?>"?(?>\\\[ -~]|[^"])"?){65,}@)(?>' . 2119 | '[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*")' . 2120 | '(?>\.(?>[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*"))*' . 2121 | '@(?>(?![a-z0-9-]{64,})(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>\.(?![a-z0-9-]{64,})' . 2122 | '(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)){0,126}|\[(?:(?>IPv6:(?>(?>[a-f0-9]{1,4})(?>:' . 2123 | '[a-f0-9]{1,4}){7}|(?!(?:.*[a-f0-9][:\]]){8,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?' . 2124 | '::(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?))|(?>(?>IPv6:(?>[a-f0-9]{1,4}(?>:' . 2125 | '[a-f0-9]{1,4}){5}:|(?!(?:.*[a-f0-9]:){6,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4})?' . 2126 | '::(?>(?:[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4}):)?))?(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}' . 2127 | '|[1-9]?[0-9])(?>\.(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}))\])$/isD', 2128 | $address 2129 | ); 2130 | case 'html5': 2131 | /** 2132 | * This is the pattern used in the HTML5 spec for validation of 'email' type form input elements. 2133 | * @link http://www.whatwg.org/specs/web-apps/current-work/#e-mail-state-(type=email) 2134 | */ 2135 | return (boolean)preg_match( 2136 | '/^[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}' . 2137 | '[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/sD', 2138 | $address 2139 | ); 2140 | case 'noregex': 2141 | //No PCRE! Do something _very_ approximate! 2142 | //Check the address is 3 chars or longer and contains an @ that's not the first or last char 2143 | return (strlen($address) >= 3 2144 | and strpos($address, '@') >= 1 2145 | and strpos($address, '@') != strlen($address) - 1); 2146 | case 'php': 2147 | default: 2148 | return (boolean)filter_var($address, FILTER_VALIDATE_EMAIL); 2149 | } 2150 | } 2151 | /** 2152 | * Tells whether IDNs (Internationalized Domain Names) are supported or not. This requires the 2153 | * "intl" and "mbstring" PHP extensions. 2154 | * @return bool "true" if required functions for IDN support are present 2155 | */ 2156 | public function idnSupported() 2157 | { 2158 | // @TODO: Write our own "idn_to_ascii" function for PHP <= 5.2. 2159 | return function_exists('idn_to_ascii') and function_exists('mb_convert_encoding'); 2160 | } 2161 | /** 2162 | * Converts IDN in given email address to its ASCII form, also known as punycode, if possible. 2163 | * Important: Address must be passed in same encoding as currently set in PHPMailer::$CharSet. 2164 | * This function silently returns unmodified address if: 2165 | * - No conversion is necessary (i.e. domain name is not an IDN, or is already in ASCII form) 2166 | * - Conversion to punycode is impossible (e.g. required PHP functions are not available) 2167 | * or fails for any reason (e.g. domain has characters not allowed in an IDN) 2168 | * @see PHPMailer::$CharSet 2169 | * @param string $address The email address to convert 2170 | * @return string The encoded address in ASCII form 2171 | */ 2172 | public function punyencodeAddress($address) 2173 | { 2174 | // Verify we have required functions, CharSet, and at-sign. 2175 | if ($this->idnSupported() and 2176 | !empty($this->CharSet) and 2177 | ($pos = strrpos($address, '@')) !== false) { 2178 | $domain = substr($address, ++$pos); 2179 | // Verify CharSet string is a valid one, and domain properly encoded in this CharSet. 2180 | if ($this->has8bitChars($domain) and @mb_check_encoding($domain, $this->CharSet)) { 2181 | $domain = mb_convert_encoding($domain, 'UTF-8', $this->CharSet); 2182 | if (($punycode = defined('INTL_IDNA_VARIANT_UTS46') ? 2183 | idn_to_ascii($domain, 0, INTL_IDNA_VARIANT_UTS46) : 2184 | idn_to_ascii($domain)) !== false) { 2185 | return substr($address, 0, $pos) . $punycode; 2186 | } 2187 | } 2188 | } 2189 | return $address; 2190 | } 2191 | /** 2192 | * Create a message and send it. 2193 | * Uses the sending method specified by $Mailer. 2194 | * @throws phpmailerException 2195 | * @return boolean false on error - See the ErrorInfo property for details of the error. 2196 | */ 2197 | public function send() 2198 | { 2199 | try { 2200 | if (!$this->preSend()) { 2201 | return false; 2202 | } 2203 | return $this->postSend(); 2204 | } catch (phpmailerException $exc) { 2205 | $this->mailHeader = ''; 2206 | $this->setError($exc->getMessage()); 2207 | if ($this->exceptions) { 2208 | throw $exc; 2209 | } 2210 | return false; 2211 | } 2212 | } 2213 | /** 2214 | * Prepare a message for sending. 2215 | * @throws phpmailerException 2216 | * @return boolean 2217 | */ 2218 | public function preSend() 2219 | { 2220 | try { 2221 | $this->error_count = 0; // Reset errors 2222 | $this->mailHeader = ''; 2223 | // Dequeue recipient and Reply-To addresses with IDN 2224 | foreach (array_merge($this->RecipientsQueue, $this->ReplyToQueue) as $params) { 2225 | $params[1] = $this->punyencodeAddress($params[1]); 2226 | call_user_func_array(array($this, 'addAnAddress'), $params); 2227 | } 2228 | if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) { 2229 | throw new phpmailerException($this->lang('provide_address'), self::STOP_CRITICAL); 2230 | } 2231 | // Validate From, Sender, and ConfirmReadingTo addresses 2232 | foreach (array('From', 'Sender', 'ConfirmReadingTo') as $address_kind) { 2233 | $this->$address_kind = trim($this->$address_kind); 2234 | if (empty($this->$address_kind)) { 2235 | continue; 2236 | } 2237 | $this->$address_kind = $this->punyencodeAddress($this->$address_kind); 2238 | if (!$this->validateAddress($this->$address_kind)) { 2239 | $error_message = $this->lang('invalid_address') . ' (punyEncode) ' . $this->$address_kind; 2240 | $this->setError($error_message); 2241 | $this->edebug($error_message); 2242 | if ($this->exceptions) { 2243 | throw new phpmailerException($error_message); 2244 | } 2245 | return false; 2246 | } 2247 | } 2248 | // Set whether the message is multipart/alternative 2249 | if ($this->alternativeExists()) { 2250 | $this->ContentType = 'multipart/alternative'; 2251 | } 2252 | $this->setMessageType(); 2253 | // Refuse to send an empty message unless we are specifically allowing it 2254 | if (!$this->AllowEmpty and empty($this->Body)) { 2255 | throw new phpmailerException($this->lang('empty_message'), self::STOP_CRITICAL); 2256 | } 2257 | // Create body before headers in case body makes changes to headers (e.g. altering transfer encoding) 2258 | $this->MIMEHeader = ''; 2259 | $this->MIMEBody = $this->createBody(); 2260 | // createBody may have added some headers, so retain them 2261 | $tempheaders = $this->MIMEHeader; 2262 | $this->MIMEHeader = $this->createHeader(); 2263 | $this->MIMEHeader .= $tempheaders; 2264 | // To capture the complete message when using mail(), create 2265 | // an extra header list which createHeader() doesn't fold in 2266 | if ($this->Mailer == 'mail') { 2267 | if (count($this->to) > 0) { 2268 | $this->mailHeader .= $this->addrAppend('To', $this->to); 2269 | } else { 2270 | $this->mailHeader .= $this->headerLine('To', 'undisclosed-recipients:;'); 2271 | } 2272 | $this->mailHeader .= $this->headerLine( 2273 | 'Subject', 2274 | $this->encodeHeader($this->secureHeader(trim($this->Subject))) 2275 | ); 2276 | } 2277 | // Sign with DKIM if enabled 2278 | if (!empty($this->DKIM_domain) 2279 | && !empty($this->DKIM_selector) 2280 | && (!empty($this->DKIM_private_string) 2281 | || (!empty($this->DKIM_private) && file_exists($this->DKIM_private)) 2282 | ) 2283 | ) { 2284 | $header_dkim = $this->DKIM_Add( 2285 | $this->MIMEHeader . $this->mailHeader, 2286 | $this->encodeHeader($this->secureHeader($this->Subject)), 2287 | $this->MIMEBody 2288 | ); 2289 | $this->MIMEHeader = rtrim($this->MIMEHeader, "\r\n ") . self::CRLF . 2290 | str_replace("\r\n", "\n", $header_dkim) . self::CRLF; 2291 | } 2292 | return true; 2293 | } catch (phpmailerException $exc) { 2294 | $this->setError($exc->getMessage()); 2295 | if ($this->exceptions) { 2296 | throw $exc; 2297 | } 2298 | return false; 2299 | } 2300 | } 2301 | /** 2302 | * Actually send a message. 2303 | * Send the email via the selected mechanism 2304 | * @throws phpmailerException 2305 | * @return boolean 2306 | */ 2307 | public function postSend() 2308 | { 2309 | try { 2310 | // Choose the mailer and send through it 2311 | switch ($this->Mailer) { 2312 | case 'sendmail': 2313 | case 'qmail': 2314 | return $this->sendmailSend($this->MIMEHeader, $this->MIMEBody); 2315 | case 'smtp': 2316 | return $this->smtpSend($this->MIMEHeader, $this->MIMEBody); 2317 | case 'mail': 2318 | return $this->mailSend($this->MIMEHeader, $this->MIMEBody); 2319 | default: 2320 | $sendMethod = $this->Mailer.'Send'; 2321 | if (method_exists($this, $sendMethod)) { 2322 | return $this->$sendMethod($this->MIMEHeader, $this->MIMEBody); 2323 | } 2324 | return $this->mailSend($this->MIMEHeader, $this->MIMEBody); 2325 | } 2326 | } catch (phpmailerException $exc) { 2327 | $this->setError($exc->getMessage()); 2328 | $this->edebug($exc->getMessage()); 2329 | if ($this->exceptions) { 2330 | throw $exc; 2331 | } 2332 | } 2333 | return false; 2334 | } 2335 | /** 2336 | * Send mail using the $Sendmail program. 2337 | * @param string $header The message headers 2338 | * @param string $body The message body 2339 | * @see PHPMailer::$Sendmail 2340 | * @throws phpmailerException 2341 | * @access protected 2342 | * @return boolean 2343 | */ 2344 | protected function sendmailSend($header, $body) 2345 | { 2346 | // CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped. 2347 | if (!empty($this->Sender) and self::isShellSafe($this->Sender)) { 2348 | if ($this->Mailer == 'qmail') { 2349 | $sendmailFmt = '%s -f%s'; 2350 | } else { 2351 | $sendmailFmt = '%s -oi -f%s -t'; 2352 | } 2353 | } else { 2354 | if ($this->Mailer == 'qmail') { 2355 | $sendmailFmt = '%s'; 2356 | } else { 2357 | $sendmailFmt = '%s -oi -t'; 2358 | } 2359 | } 2360 | // TODO: If possible, this should be changed to escapeshellarg. Needs thorough testing. 2361 | $sendmail = sprintf($sendmailFmt, escapeshellcmd($this->Sendmail), $this->Sender); 2362 | if ($this->SingleTo) { 2363 | foreach ($this->SingleToArray as $toAddr) { 2364 | if (!@$mail = popen($sendmail, 'w')) { 2365 | throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); 2366 | } 2367 | fputs($mail, 'To: ' . $toAddr . "\n"); 2368 | fputs($mail, $header); 2369 | fputs($mail, $body); 2370 | $result = pclose($mail); 2371 | $this->doCallback( 2372 | ($result == 0), 2373 | array($toAddr), 2374 | $this->cc, 2375 | $this->bcc, 2376 | $this->Subject, 2377 | $body, 2378 | $this->From 2379 | ); 2380 | if ($result != 0) { 2381 | throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); 2382 | } 2383 | } 2384 | } else { 2385 | if (!@$mail = popen($sendmail, 'w')) { 2386 | throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); 2387 | } 2388 | fputs($mail, $header); 2389 | fputs($mail, $body); 2390 | $result = pclose($mail); 2391 | $this->doCallback( 2392 | ($result == 0), 2393 | $this->to, 2394 | $this->cc, 2395 | $this->bcc, 2396 | $this->Subject, 2397 | $body, 2398 | $this->From 2399 | ); 2400 | if ($result != 0) { 2401 | throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); 2402 | } 2403 | } 2404 | return true; 2405 | } 2406 | /** 2407 | * Fix CVE-2016-10033 and CVE-2016-10045 by disallowing potentially unsafe shell characters. 2408 | * 2409 | * Note that escapeshellarg and escapeshellcmd are inadequate for our purposes, especially on Windows. 2410 | * @param string $string The string to be validated 2411 | * @see https://github.com/PHPMailer/PHPMailer/issues/924 CVE-2016-10045 bug report 2412 | * @access protected 2413 | * @return boolean 2414 | */ 2415 | protected static function isShellSafe($string) 2416 | { 2417 | // Future-proof 2418 | if (escapeshellcmd($string) !== $string 2419 | or !in_array(escapeshellarg($string), array("'$string'", "\"$string\"")) 2420 | ) { 2421 | return false; 2422 | } 2423 | $length = strlen($string); 2424 | for ($i = 0; $i < $length; $i++) { 2425 | $c = $string[$i]; 2426 | // All other characters have a special meaning in at least one common shell, including = and +. 2427 | // Full stop (.) has a special meaning in cmd.exe, but its impact should be negligible here. 2428 | // Note that this does permit non-Latin alphanumeric characters based on the current locale. 2429 | if (!ctype_alnum($c) && strpos('@_-.', $c) === false) { 2430 | return false; 2431 | } 2432 | } 2433 | return true; 2434 | } 2435 | /** 2436 | * Send mail using the PHP mail() function. 2437 | * @param string $header The message headers 2438 | * @param string $body The message body 2439 | * @link http://www.php.net/manual/en/book.mail.php 2440 | * @throws phpmailerException 2441 | * @access protected 2442 | * @return boolean 2443 | */ 2444 | protected function mailSend($header, $body) 2445 | { 2446 | $toArr = array(); 2447 | foreach ($this->to as $toaddr) { 2448 | $toArr[] = $this->addrFormat($toaddr); 2449 | } 2450 | $to = implode(', ', $toArr); 2451 | $params = null; 2452 | //This sets the SMTP envelope sender which gets turned into a return-path header by the receiver 2453 | if (!empty($this->Sender) and $this->validateAddress($this->Sender)) { 2454 | // CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped. 2455 | if (self::isShellSafe($this->Sender)) { 2456 | $params = sprintf('-f%s', $this->Sender); 2457 | } 2458 | } 2459 | if (!empty($this->Sender) and !ini_get('safe_mode') and $this->validateAddress($this->Sender)) { 2460 | $old_from = ini_get('sendmail_from'); 2461 | ini_set('sendmail_from', $this->Sender); 2462 | } 2463 | $result = false; 2464 | if ($this->SingleTo and count($toArr) > 1) { 2465 | foreach ($toArr as $toAddr) { 2466 | $result = $this->mailPassthru($toAddr, $this->Subject, $body, $header, $params); 2467 | $this->doCallback($result, array($toAddr), $this->cc, $this->bcc, $this->Subject, $body, $this->From); 2468 | } 2469 | } else { 2470 | $result = $this->mailPassthru($to, $this->Subject, $body, $header, $params); 2471 | $this->doCallback($result, $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From); 2472 | } 2473 | if (isset($old_from)) { 2474 | ini_set('sendmail_from', $old_from); 2475 | } 2476 | if (!$result) { 2477 | throw new phpmailerException($this->lang('instantiate'), self::STOP_CRITICAL); 2478 | } 2479 | return true; 2480 | } 2481 | /** 2482 | * Get an instance to use for SMTP operations. 2483 | * Override this function to load your own SMTP implementation 2484 | * @return SMTP 2485 | */ 2486 | public function getSMTPInstance() 2487 | { 2488 | if (!is_object($this->smtp)) { 2489 | $this->smtp = new SMTP; 2490 | } 2491 | return $this->smtp; 2492 | } 2493 | /** 2494 | * Send mail via SMTP. 2495 | * Returns false if there is a bad MAIL FROM, RCPT, or DATA input. 2496 | * Uses the PHPMailerSMTP class by default. 2497 | * @see PHPMailer::getSMTPInstance() to use a different class. 2498 | * @param string $header The message headers 2499 | * @param string $body The message body 2500 | * @throws phpmailerException 2501 | * @uses SMTP 2502 | * @access protected 2503 | * @return boolean 2504 | */ 2505 | protected function smtpSend($header, $body) 2506 | { 2507 | $bad_rcpt = array(); 2508 | if (!$this->smtpConnect($this->SMTPOptions)) { 2509 | throw new phpmailerException($this->lang('smtp_connect_failed'), self::STOP_CRITICAL); 2510 | } 2511 | if (!empty($this->Sender) and $this->validateAddress($this->Sender)) { 2512 | $smtp_from = $this->Sender; 2513 | } else { 2514 | $smtp_from = $this->From; 2515 | } 2516 | if (!$this->smtp->mail($smtp_from)) { 2517 | $this->setError($this->lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp->getError())); 2518 | throw new phpmailerException($this->ErrorInfo, self::STOP_CRITICAL); 2519 | } 2520 | // Attempt to send to all recipients 2521 | foreach (array($this->to, $this->cc, $this->bcc) as $togroup) { 2522 | foreach ($togroup as $to) { 2523 | if (!$this->smtp->recipient($to[0])) { 2524 | $error = $this->smtp->getError(); 2525 | $bad_rcpt[] = array('to' => $to[0], 'error' => $error['detail']); 2526 | $isSent = false; 2527 | } else { 2528 | $isSent = true; 2529 | } 2530 | $this->doCallback($isSent, array($to[0]), array(), array(), $this->Subject, $body, $this->From); 2531 | } 2532 | } 2533 | // Only send the DATA command if we have viable recipients 2534 | if ((count($this->all_recipients) > count($bad_rcpt)) and !$this->smtp->data($header . $body)) { 2535 | throw new phpmailerException($this->lang('data_not_accepted'), self::STOP_CRITICAL); 2536 | } 2537 | if ($this->SMTPKeepAlive) { 2538 | $this->smtp->reset(); 2539 | } else { 2540 | $this->smtp->quit(); 2541 | $this->smtp->close(); 2542 | } 2543 | //Create error message for any bad addresses 2544 | if (count($bad_rcpt) > 0) { 2545 | $errstr = ''; 2546 | foreach ($bad_rcpt as $bad) { 2547 | $errstr .= $bad['to'] . ': ' . $bad['error']; 2548 | } 2549 | throw new phpmailerException( 2550 | $this->lang('recipients_failed') . $errstr, 2551 | self::STOP_CONTINUE 2552 | ); 2553 | } 2554 | return true; 2555 | } 2556 | /** 2557 | * Initiate a connection to an SMTP server. 2558 | * Returns false if the operation failed. 2559 | * @param array $options An array of options compatible with stream_context_create() 2560 | * @uses SMTP 2561 | * @access public 2562 | * @throws phpmailerException 2563 | * @return boolean 2564 | */ 2565 | public function smtpConnect($options = null) 2566 | { 2567 | if (is_null($this->smtp)) { 2568 | $this->smtp = $this->getSMTPInstance(); 2569 | } 2570 | //If no options are provided, use whatever is set in the instance 2571 | if (is_null($options)) { 2572 | $options = $this->SMTPOptions; 2573 | } 2574 | // Already connected? 2575 | if ($this->smtp->connected()) { 2576 | return true; 2577 | } 2578 | $this->smtp->setTimeout($this->Timeout); 2579 | $this->smtp->setDebugLevel($this->SMTPDebug); 2580 | $this->smtp->setDebugOutput($this->Debugoutput); 2581 | $this->smtp->setVerp($this->do_verp); 2582 | $hosts = explode(';', $this->Host); 2583 | $lastexception = null; 2584 | foreach ($hosts as $hostentry) { 2585 | $hostinfo = array(); 2586 | if (!preg_match('/^((ssl|tls):\/\/)*([a-zA-Z0-9\.-]*):?([0-9]*)$/', trim($hostentry), $hostinfo)) { 2587 | // Not a valid host entry 2588 | continue; 2589 | } 2590 | // $hostinfo[2]: optional ssl or tls prefix 2591 | // $hostinfo[3]: the hostname 2592 | // $hostinfo[4]: optional port number 2593 | // The host string prefix can temporarily override the current setting for SMTPSecure 2594 | // If it's not specified, the default value is used 2595 | $prefix = ''; 2596 | $secure = $this->SMTPSecure; 2597 | $tls = ($this->SMTPSecure == 'tls'); 2598 | if ('ssl' == $hostinfo[2] or ('' == $hostinfo[2] and 'ssl' == $this->SMTPSecure)) { 2599 | $prefix = 'ssl://'; 2600 | $tls = false; // Can't have SSL and TLS at the same time 2601 | $secure = 'ssl'; 2602 | } elseif ($hostinfo[2] == 'tls') { 2603 | $tls = true; 2604 | // tls doesn't use a prefix 2605 | $secure = 'tls'; 2606 | } 2607 | //Do we need the OpenSSL extension? 2608 | $sslext = defined('OPENSSL_ALGO_SHA1'); 2609 | if ('tls' === $secure or 'ssl' === $secure) { 2610 | //Check for an OpenSSL constant rather than using extension_loaded, which is sometimes disabled 2611 | if (!$sslext) { 2612 | throw new phpmailerException($this->lang('extension_missing').'openssl', self::STOP_CRITICAL); 2613 | } 2614 | } 2615 | $host = $hostinfo[3]; 2616 | $port = $this->Port; 2617 | $tport = (integer)$hostinfo[4]; 2618 | if ($tport > 0 and $tport < 65536) { 2619 | $port = $tport; 2620 | } 2621 | if ($this->smtp->connect($prefix . $host, $port, $this->Timeout, $options)) { 2622 | try { 2623 | if ($this->Helo) { 2624 | $hello = $this->Helo; 2625 | } else { 2626 | $hello = $this->serverHostname(); 2627 | } 2628 | $this->smtp->hello($hello); 2629 | //Automatically enable TLS encryption if: 2630 | // * it's not disabled 2631 | // * we have openssl extension 2632 | // * we are not already using SSL 2633 | // * the server offers STARTTLS 2634 | if ($this->SMTPAutoTLS and $sslext and $secure != 'ssl' and $this->smtp->getServerExt('STARTTLS')) { 2635 | $tls = true; 2636 | } 2637 | if ($tls) { 2638 | if (!$this->smtp->startTLS()) { 2639 | throw new phpmailerException($this->lang('connect_host')); 2640 | } 2641 | // We must resend EHLO after TLS negotiation 2642 | $this->smtp->hello($hello); 2643 | } 2644 | if ($this->SMTPAuth) { 2645 | if (!$this->smtp->authenticate( 2646 | $this->Username, 2647 | $this->Password, 2648 | $this->AuthType, 2649 | $this->Realm, 2650 | $this->Workstation 2651 | ) 2652 | ) { 2653 | throw new phpmailerException($this->lang('authenticate')); 2654 | } 2655 | } 2656 | return true; 2657 | } catch (phpmailerException $exc) { 2658 | $lastexception = $exc; 2659 | $this->edebug($exc->getMessage()); 2660 | // We must have connected, but then failed TLS or Auth, so close connection nicely 2661 | $this->smtp->quit(); 2662 | } 2663 | } 2664 | } 2665 | // If we get here, all connection attempts have failed, so close connection hard 2666 | $this->smtp->close(); 2667 | // As we've caught all exceptions, just report whatever the last one was 2668 | if ($this->exceptions and !is_null($lastexception)) { 2669 | throw $lastexception; 2670 | } 2671 | return false; 2672 | } 2673 | /** 2674 | * Close the active SMTP session if one exists. 2675 | * @return void 2676 | */ 2677 | public function smtpClose() 2678 | { 2679 | if (is_a($this->smtp, 'SMTP')) { 2680 | if ($this->smtp->connected()) { 2681 | $this->smtp->quit(); 2682 | $this->smtp->close(); 2683 | } 2684 | } 2685 | } 2686 | /** 2687 | * Set the language for error messages. 2688 | * Returns false if it cannot load the language file. 2689 | * The default language is English. 2690 | * @param string $langcode ISO 639-1 2-character language code (e.g. French is "fr") 2691 | * @param string $lang_path Path to the language file directory, with trailing separator (slash) 2692 | * @return boolean 2693 | * @access public 2694 | */ 2695 | public function setLanguage($langcode = 'en', $lang_path = '') 2696 | { 2697 | // Backwards compatibility for renamed language codes 2698 | $renamed_langcodes = array( 2699 | 'br' => 'pt_br', 2700 | 'cz' => 'cs', 2701 | 'dk' => 'da', 2702 | 'no' => 'nb', 2703 | 'se' => 'sv', 2704 | ); 2705 | if (isset($renamed_langcodes[$langcode])) { 2706 | $langcode = $renamed_langcodes[$langcode]; 2707 | } 2708 | // Define full set of translatable strings in English 2709 | $PHPMAILER_LANG = array( 2710 | 'authenticate' => 'SMTP Error: Could not authenticate.', 2711 | 'connect_host' => 'SMTP Error: Could not connect to SMTP host.', 2712 | 'data_not_accepted' => 'SMTP Error: data not accepted.', 2713 | 'empty_message' => 'Message body empty', 2714 | 'encoding' => 'Unknown encoding: ', 2715 | 'execute' => 'Could not execute: ', 2716 | 'file_access' => 'Could not access file: ', 2717 | 'file_open' => 'File Error: Could not open file: ', 2718 | 'from_failed' => 'The following From address failed: ', 2719 | 'instantiate' => 'Could not instantiate mail function.', 2720 | 'invalid_address' => 'Invalid address: ', 2721 | 'mailer_not_supported' => ' mailer is not supported.', 2722 | 'provide_address' => 'You must provide at least one recipient email address.', 2723 | 'recipients_failed' => 'SMTP Error: The following recipients failed: ', 2724 | 'signing' => 'Signing Error: ', 2725 | 'smtp_connect_failed' => 'SMTP connect() failed.', 2726 | 'smtp_error' => 'SMTP server error: ', 2727 | 'variable_set' => 'Cannot set or reset variable: ', 2728 | 'extension_missing' => 'Extension missing: ' 2729 | ); 2730 | if (empty($lang_path)) { 2731 | // Calculate an absolute path so it can work if CWD is not here 2732 | $lang_path = dirname(__FILE__). DIRECTORY_SEPARATOR . 'language'. DIRECTORY_SEPARATOR; 2733 | } 2734 | //Validate $langcode 2735 | if (!preg_match('/^[a-z]{2}(?:_[a-zA-Z]{2})?$/', $langcode)) { 2736 | $langcode = 'en'; 2737 | } 2738 | $foundlang = true; 2739 | $lang_file = $lang_path . 'phpmailer.lang-' . $langcode . '.php'; 2740 | // There is no English translation file 2741 | if ($langcode != 'en') { 2742 | // Make sure language file path is readable 2743 | if (!is_readable($lang_file)) { 2744 | $foundlang = false; 2745 | } else { 2746 | // Overwrite language-specific strings. 2747 | // This way we'll never have missing translation keys. 2748 | $foundlang = include $lang_file; 2749 | } 2750 | } 2751 | $this->language = $PHPMAILER_LANG; 2752 | return (boolean)$foundlang; // Returns false if language not found 2753 | } 2754 | /** 2755 | * Get the array of strings for the current language. 2756 | * @return array 2757 | */ 2758 | public function getTranslations() 2759 | { 2760 | return $this->language; 2761 | } 2762 | /** 2763 | * Create recipient headers. 2764 | * @access public 2765 | * @param string $type 2766 | * @param array $addr An array of recipient, 2767 | * where each recipient is a 2-element indexed array with element 0 containing an address 2768 | * and element 1 containing a name, like: 2769 | * array(array('joe@example.com', 'Joe User'), array('zoe@example.com', 'Zoe User')) 2770 | * @return string 2771 | */ 2772 | public function addrAppend($type, $addr) 2773 | { 2774 | $addresses = array(); 2775 | foreach ($addr as $address) { 2776 | $addresses[] = $this->addrFormat($address); 2777 | } 2778 | return $type . ': ' . implode(', ', $addresses) . $this->LE; 2779 | } 2780 | /** 2781 | * Format an address for use in a message header. 2782 | * @access public 2783 | * @param array $addr A 2-element indexed array, element 0 containing an address, element 1 containing a name 2784 | * like array('joe@example.com', 'Joe User') 2785 | * @return string 2786 | */ 2787 | public function addrFormat($addr) 2788 | { 2789 | if (empty($addr[1])) { // No name provided 2790 | return $this->secureHeader($addr[0]); 2791 | } else { 2792 | return $this->encodeHeader($this->secureHeader($addr[1]), 'phrase') . ' <' . $this->secureHeader( 2793 | $addr[0] 2794 | ) . '>'; 2795 | } 2796 | } 2797 | /** 2798 | * Word-wrap message. 2799 | * For use with mailers that do not automatically perform wrapping 2800 | * and for quoted-printable encoded messages. 2801 | * Original written by philippe. 2802 | * @param string $message The message to wrap 2803 | * @param integer $length The line length to wrap to 2804 | * @param boolean $qp_mode Whether to run in Quoted-Printable mode 2805 | * @access public 2806 | * @return string 2807 | */ 2808 | public function wrapText($message, $length, $qp_mode = false) 2809 | { 2810 | if ($qp_mode) { 2811 | $soft_break = sprintf(' =%s', $this->LE); 2812 | } else { 2813 | $soft_break = $this->LE; 2814 | } 2815 | // If utf-8 encoding is used, we will need to make sure we don't 2816 | // split multibyte characters when we wrap 2817 | $is_utf8 = (strtolower($this->CharSet) == 'utf-8'); 2818 | $lelen = strlen($this->LE); 2819 | $crlflen = strlen(self::CRLF); 2820 | $message = $this->fixEOL($message); 2821 | //Remove a trailing line break 2822 | if (substr($message, -$lelen) == $this->LE) { 2823 | $message = substr($message, 0, -$lelen); 2824 | } 2825 | //Split message into lines 2826 | $lines = explode($this->LE, $message); 2827 | //Message will be rebuilt in here 2828 | $message = ''; 2829 | foreach ($lines as $line) { 2830 | $words = explode(' ', $line); 2831 | $buf = ''; 2832 | $firstword = true; 2833 | foreach ($words as $word) { 2834 | if ($qp_mode and (strlen($word) > $length)) { 2835 | $space_left = $length - strlen($buf) - $crlflen; 2836 | if (!$firstword) { 2837 | if ($space_left > 20) { 2838 | $len = $space_left; 2839 | if ($is_utf8) { 2840 | $len = $this->utf8CharBoundary($word, $len); 2841 | } elseif (substr($word, $len - 1, 1) == '=') { 2842 | $len--; 2843 | } elseif (substr($word, $len - 2, 1) == '=') { 2844 | $len -= 2; 2845 | } 2846 | $part = substr($word, 0, $len); 2847 | $word = substr($word, $len); 2848 | $buf .= ' ' . $part; 2849 | $message .= $buf . sprintf('=%s', self::CRLF); 2850 | } else { 2851 | $message .= $buf . $soft_break; 2852 | } 2853 | $buf = ''; 2854 | } 2855 | while (strlen($word) > 0) { 2856 | if ($length <= 0) { 2857 | break; 2858 | } 2859 | $len = $length; 2860 | if ($is_utf8) { 2861 | $len = $this->utf8CharBoundary($word, $len); 2862 | } elseif (substr($word, $len - 1, 1) == '=') { 2863 | $len--; 2864 | } elseif (substr($word, $len - 2, 1) == '=') { 2865 | $len -= 2; 2866 | } 2867 | $part = substr($word, 0, $len); 2868 | $word = substr($word, $len); 2869 | if (strlen($word) > 0) { 2870 | $message .= $part . sprintf('=%s', self::CRLF); 2871 | } else { 2872 | $buf = $part; 2873 | } 2874 | } 2875 | } else { 2876 | $buf_o = $buf; 2877 | if (!$firstword) { 2878 | $buf .= ' '; 2879 | } 2880 | $buf .= $word; 2881 | if (strlen($buf) > $length and $buf_o != '') { 2882 | $message .= $buf_o . $soft_break; 2883 | $buf = $word; 2884 | } 2885 | } 2886 | $firstword = false; 2887 | } 2888 | $message .= $buf . self::CRLF; 2889 | } 2890 | return $message; 2891 | } 2892 | /** 2893 | * Find the last character boundary prior to $maxLength in a utf-8 2894 | * quoted-printable encoded string. 2895 | * Original written by Colin Brown. 2896 | * @access public 2897 | * @param string $encodedText utf-8 QP text 2898 | * @param integer $maxLength Find the last character boundary prior to this length 2899 | * @return integer 2900 | */ 2901 | public function utf8CharBoundary($encodedText, $maxLength) 2902 | { 2903 | $foundSplitPos = false; 2904 | $lookBack = 3; 2905 | while (!$foundSplitPos) { 2906 | $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack); 2907 | $encodedCharPos = strpos($lastChunk, '='); 2908 | if (false !== $encodedCharPos) { 2909 | // Found start of encoded character byte within $lookBack block. 2910 | // Check the encoded byte value (the 2 chars after the '=') 2911 | $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2); 2912 | $dec = hexdec($hex); 2913 | if ($dec < 128) { 2914 | // Single byte character. 2915 | // If the encoded char was found at pos 0, it will fit 2916 | // otherwise reduce maxLength to start of the encoded char 2917 | if ($encodedCharPos > 0) { 2918 | $maxLength = $maxLength - ($lookBack - $encodedCharPos); 2919 | } 2920 | $foundSplitPos = true; 2921 | } elseif ($dec >= 192) { 2922 | // First byte of a multi byte character 2923 | // Reduce maxLength to split at start of character 2924 | $maxLength = $maxLength - ($lookBack - $encodedCharPos); 2925 | $foundSplitPos = true; 2926 | } elseif ($dec < 192) { 2927 | // Middle byte of a multi byte character, look further back 2928 | $lookBack += 3; 2929 | } 2930 | } else { 2931 | // No encoded character found 2932 | $foundSplitPos = true; 2933 | } 2934 | } 2935 | return $maxLength; 2936 | } 2937 | /** 2938 | * Apply word wrapping to the message body. 2939 | * Wraps the message body to the number of chars set in the WordWrap property. 2940 | * You should only do this to plain-text bodies as wrapping HTML tags may break them. 2941 | * This is called automatically by createBody(), so you don't need to call it yourself. 2942 | * @access public 2943 | * @return void 2944 | */ 2945 | public function setWordWrap() 2946 | { 2947 | if ($this->WordWrap < 1) { 2948 | return; 2949 | } 2950 | switch ($this->message_type) { 2951 | case 'alt': 2952 | case 'alt_inline': 2953 | case 'alt_attach': 2954 | case 'alt_inline_attach': 2955 | $this->AltBody = $this->wrapText($this->AltBody, $this->WordWrap); 2956 | break; 2957 | default: 2958 | $this->Body = $this->wrapText($this->Body, $this->WordWrap); 2959 | break; 2960 | } 2961 | } 2962 | /** 2963 | * Assemble message headers. 2964 | * @access public 2965 | * @return string The assembled headers 2966 | */ 2967 | public function createHeader() 2968 | { 2969 | $result = ''; 2970 | if ($this->MessageDate == '') { 2971 | $this->MessageDate = self::rfcDate(); 2972 | } 2973 | $result .= $this->headerLine('Date', $this->MessageDate); 2974 | // To be created automatically by mail() 2975 | if ($this->SingleTo) { 2976 | if ($this->Mailer != 'mail') { 2977 | foreach ($this->to as $toaddr) { 2978 | $this->SingleToArray[] = $this->addrFormat($toaddr); 2979 | } 2980 | } 2981 | } else { 2982 | if (count($this->to) > 0) { 2983 | if ($this->Mailer != 'mail') { 2984 | $result .= $this->addrAppend('To', $this->to); 2985 | } 2986 | } elseif (count($this->cc) == 0) { 2987 | $result .= $this->headerLine('To', 'undisclosed-recipients:;'); 2988 | } 2989 | } 2990 | $result .= $this->addrAppend('From', array(array(trim($this->From), $this->FromName))); 2991 | // sendmail and mail() extract Cc from the header before sending 2992 | if (count($this->cc) > 0) { 2993 | $result .= $this->addrAppend('Cc', $this->cc); 2994 | } 2995 | // sendmail and mail() extract Bcc from the header before sending 2996 | if (( 2997 | $this->Mailer == 'sendmail' or $this->Mailer == 'qmail' or $this->Mailer == 'mail' 2998 | ) 2999 | and count($this->bcc) > 0 3000 | ) { 3001 | $result .= $this->addrAppend('Bcc', $this->bcc); 3002 | } 3003 | if (count($this->ReplyTo) > 0) { 3004 | $result .= $this->addrAppend('Reply-To', $this->ReplyTo); 3005 | } 3006 | // mail() sets the subject itself 3007 | if ($this->Mailer != 'mail') { 3008 | $result .= $this->headerLine('Subject', $this->encodeHeader($this->secureHeader($this->Subject))); 3009 | } 3010 | // Only allow a custom message ID if it conforms to RFC 5322 section 3.6.4 3011 | // https://tools.ietf.org/html/rfc5322#section-3.6.4 3012 | if ('' != $this->MessageID and preg_match('/^<.*@.*>$/', $this->MessageID)) { 3013 | $this->lastMessageID = $this->MessageID; 3014 | } else { 3015 | $this->lastMessageID = sprintf('<%s@%s>', $this->uniqueid, $this->serverHostname()); 3016 | } 3017 | $result .= $this->headerLine('Message-ID', $this->lastMessageID); 3018 | if (!is_null($this->Priority)) { 3019 | $result .= $this->headerLine('X-Priority', $this->Priority); 3020 | } 3021 | if ($this->XMailer == '') { 3022 | $result .= $this->headerLine( 3023 | 'X-Mailer', 3024 | 'PHPMailer ' . $this->Version . ' (https://github.com/PHPMailer/PHPMailer)' 3025 | ); 3026 | } else { 3027 | $myXmailer = trim($this->XMailer); 3028 | if ($myXmailer) { 3029 | $result .= $this->headerLine('X-Mailer', $myXmailer); 3030 | } 3031 | } 3032 | if ($this->ConfirmReadingTo != '') { 3033 | $result .= $this->headerLine('Disposition-Notification-To', '<' . $this->ConfirmReadingTo . '>'); 3034 | } 3035 | // Add custom headers 3036 | foreach ($this->CustomHeader as $header) { 3037 | $result .= $this->headerLine( 3038 | trim($header[0]), 3039 | $this->encodeHeader(trim($header[1])) 3040 | ); 3041 | } 3042 | if (!$this->sign_key_file) { 3043 | $result .= $this->headerLine('MIME-Version', '1.0'); 3044 | $result .= $this->getMailMIME(); 3045 | } 3046 | return $result; 3047 | } 3048 | /** 3049 | * Get the message MIME type headers. 3050 | * @access public 3051 | * @return string 3052 | */ 3053 | public function getMailMIME() 3054 | { 3055 | $result = ''; 3056 | $ismultipart = true; 3057 | switch ($this->message_type) { 3058 | case 'inline': 3059 | $result .= $this->headerLine('Content-Type', 'multipart/related;'); 3060 | $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"'); 3061 | break; 3062 | case 'attach': 3063 | case 'inline_attach': 3064 | case 'alt_attach': 3065 | case 'alt_inline_attach': 3066 | $result .= $this->headerLine('Content-Type', 'multipart/mixed;'); 3067 | $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"'); 3068 | break; 3069 | case 'alt': 3070 | case 'alt_inline': 3071 | $result .= $this->headerLine('Content-Type', 'multipart/alternative;'); 3072 | $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"'); 3073 | break; 3074 | default: 3075 | // Catches case 'plain': and case '': 3076 | $result .= $this->textLine('Content-Type: ' . $this->ContentType . '; charset=' . $this->CharSet); 3077 | $ismultipart = false; 3078 | break; 3079 | } 3080 | // RFC1341 part 5 says 7bit is assumed if not specified 3081 | if ($this->Encoding != '7bit') { 3082 | // RFC 2045 section 6.4 says multipart MIME parts may only use 7bit, 8bit or binary CTE 3083 | if ($ismultipart) { 3084 | if ($this->Encoding == '8bit') { 3085 | $result .= $this->headerLine('Content-Transfer-Encoding', '8bit'); 3086 | } 3087 | // The only remaining alternatives are quoted-printable and base64, which are both 7bit compatible 3088 | } else { 3089 | $result .= $this->headerLine('Content-Transfer-Encoding', $this->Encoding); 3090 | } 3091 | } 3092 | if ($this->Mailer != 'mail') { 3093 | $result .= $this->LE; 3094 | } 3095 | return $result; 3096 | } 3097 | /** 3098 | * Returns the whole MIME message. 3099 | * Includes complete headers and body. 3100 | * Only valid post preSend(). 3101 | * @see PHPMailer::preSend() 3102 | * @access public 3103 | * @return string 3104 | */ 3105 | public function getSentMIMEMessage() 3106 | { 3107 | return rtrim($this->MIMEHeader . $this->mailHeader, "\n\r") . self::CRLF . self::CRLF . $this->MIMEBody; 3108 | } 3109 | /** 3110 | * Create unique ID 3111 | * @return string 3112 | */ 3113 | protected function generateId() { 3114 | return md5(uniqid(time())); 3115 | } 3116 | /** 3117 | * Assemble the message body. 3118 | * Returns an empty string on failure. 3119 | * @access public 3120 | * @throws phpmailerException 3121 | * @return string The assembled message body 3122 | */ 3123 | public function createBody() 3124 | { 3125 | $body = ''; 3126 | //Create unique IDs and preset boundaries 3127 | $this->uniqueid = $this->generateId(); 3128 | $this->boundary[1] = 'b1_' . $this->uniqueid; 3129 | $this->boundary[2] = 'b2_' . $this->uniqueid; 3130 | $this->boundary[3] = 'b3_' . $this->uniqueid; 3131 | if ($this->sign_key_file) { 3132 | $body .= $this->getMailMIME() . $this->LE; 3133 | } 3134 | $this->setWordWrap(); 3135 | $bodyEncoding = $this->Encoding; 3136 | $bodyCharSet = $this->CharSet; 3137 | //Can we do a 7-bit downgrade? 3138 | if ($bodyEncoding == '8bit' and !$this->has8bitChars($this->Body)) { 3139 | $bodyEncoding = '7bit'; 3140 | //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit 3141 | $bodyCharSet = 'us-ascii'; 3142 | } 3143 | //If lines are too long, and we're not already using an encoding that will shorten them, 3144 | //change to quoted-printable transfer encoding for the body part only 3145 | if ('base64' != $this->Encoding and self::hasLineLongerThanMax($this->Body)) { 3146 | $bodyEncoding = 'quoted-printable'; 3147 | } 3148 | $altBodyEncoding = $this->Encoding; 3149 | $altBodyCharSet = $this->CharSet; 3150 | //Can we do a 7-bit downgrade? 3151 | if ($altBodyEncoding == '8bit' and !$this->has8bitChars($this->AltBody)) { 3152 | $altBodyEncoding = '7bit'; 3153 | //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit 3154 | $altBodyCharSet = 'us-ascii'; 3155 | } 3156 | //If lines are too long, and we're not already using an encoding that will shorten them, 3157 | //change to quoted-printable transfer encoding for the alt body part only 3158 | if ('base64' != $altBodyEncoding and self::hasLineLongerThanMax($this->AltBody)) { 3159 | $altBodyEncoding = 'quoted-printable'; 3160 | } 3161 | //Use this as a preamble in all multipart message types 3162 | $mimepre = "This is a multi-part message in MIME format." . $this->LE . $this->LE; 3163 | switch ($this->message_type) { 3164 | case 'inline': 3165 | $body .= $mimepre; 3166 | $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding); 3167 | $body .= $this->encodeString($this->Body, $bodyEncoding); 3168 | $body .= $this->LE . $this->LE; 3169 | $body .= $this->attachAll('inline', $this->boundary[1]); 3170 | break; 3171 | case 'attach': 3172 | $body .= $mimepre; 3173 | $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding); 3174 | $body .= $this->encodeString($this->Body, $bodyEncoding); 3175 | $body .= $this->LE . $this->LE; 3176 | $body .= $this->attachAll('attachment', $this->boundary[1]); 3177 | break; 3178 | case 'inline_attach': 3179 | $body .= $mimepre; 3180 | $body .= $this->textLine('--' . $this->boundary[1]); 3181 | $body .= $this->headerLine('Content-Type', 'multipart/related;'); 3182 | $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"'); 3183 | $body .= $this->LE; 3184 | $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, '', $bodyEncoding); 3185 | $body .= $this->encodeString($this->Body, $bodyEncoding); 3186 | $body .= $this->LE . $this->LE; 3187 | $body .= $this->attachAll('inline', $this->boundary[2]); 3188 | $body .= $this->LE; 3189 | $body .= $this->attachAll('attachment', $this->boundary[1]); 3190 | break; 3191 | case 'alt': 3192 | $body .= $mimepre; 3193 | $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, 'text/plain', $altBodyEncoding); 3194 | $body .= $this->encodeString($this->AltBody, $altBodyEncoding); 3195 | $body .= $this->LE . $this->LE; 3196 | $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, 'text/html', $bodyEncoding); 3197 | $body .= $this->encodeString($this->Body, $bodyEncoding); 3198 | $body .= $this->LE . $this->LE; 3199 | if (!empty($this->Ical)) { 3200 | $body .= $this->getBoundary($this->boundary[1], '', 'text/calendar; method=REQUEST', ''); 3201 | $body .= $this->encodeString($this->Ical, $this->Encoding); 3202 | $body .= $this->LE . $this->LE; 3203 | } 3204 | $body .= $this->endBoundary($this->boundary[1]); 3205 | break; 3206 | case 'alt_inline': 3207 | $body .= $mimepre; 3208 | $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, 'text/plain', $altBodyEncoding); 3209 | $body .= $this->encodeString($this->AltBody, $altBodyEncoding); 3210 | $body .= $this->LE . $this->LE; 3211 | $body .= $this->textLine('--' . $this->boundary[1]); 3212 | $body .= $this->headerLine('Content-Type', 'multipart/related;'); 3213 | $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"'); 3214 | $body .= $this->LE; 3215 | $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, 'text/html', $bodyEncoding); 3216 | $body .= $this->encodeString($this->Body, $bodyEncoding); 3217 | $body .= $this->LE . $this->LE; 3218 | $body .= $this->attachAll('inline', $this->boundary[2]); 3219 | $body .= $this->LE; 3220 | $body .= $this->endBoundary($this->boundary[1]); 3221 | break; 3222 | case 'alt_attach': 3223 | $body .= $mimepre; 3224 | $body .= $this->textLine('--' . $this->boundary[1]); 3225 | $body .= $this->headerLine('Content-Type', 'multipart/alternative;'); 3226 | $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"'); 3227 | $body .= $this->LE; 3228 | $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, 'text/plain', $altBodyEncoding); 3229 | $body .= $this->encodeString($this->AltBody, $altBodyEncoding); 3230 | $body .= $this->LE . $this->LE; 3231 | $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, 'text/html', $bodyEncoding); 3232 | $body .= $this->encodeString($this->Body, $bodyEncoding); 3233 | $body .= $this->LE . $this->LE; 3234 | $body .= $this->endBoundary($this->boundary[2]); 3235 | $body .= $this->LE; 3236 | $body .= $this->attachAll('attachment', $this->boundary[1]); 3237 | break; 3238 | case 'alt_inline_attach': 3239 | $body .= $mimepre; 3240 | $body .= $this->textLine('--' . $this->boundary[1]); 3241 | $body .= $this->headerLine('Content-Type', 'multipart/alternative;'); 3242 | $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"'); 3243 | $body .= $this->LE; 3244 | $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, 'text/plain', $altBodyEncoding); 3245 | $body .= $this->encodeString($this->AltBody, $altBodyEncoding); 3246 | $body .= $this->LE . $this->LE; 3247 | $body .= $this->textLine('--' . $this->boundary[2]); 3248 | $body .= $this->headerLine('Content-Type', 'multipart/related;'); 3249 | $body .= $this->textLine("\tboundary=\"" . $this->boundary[3] . '"'); 3250 | $body .= $this->LE; 3251 | $body .= $this->getBoundary($this->boundary[3], $bodyCharSet, 'text/html', $bodyEncoding); 3252 | $body .= $this->encodeString($this->Body, $bodyEncoding); 3253 | $body .= $this->LE . $this->LE; 3254 | $body .= $this->attachAll('inline', $this->boundary[3]); 3255 | $body .= $this->LE; 3256 | $body .= $this->endBoundary($this->boundary[2]); 3257 | $body .= $this->LE; 3258 | $body .= $this->attachAll('attachment', $this->boundary[1]); 3259 | break; 3260 | default: 3261 | // Catch case 'plain' and case '', applies to simple `text/plain` and `text/html` body content types 3262 | //Reset the `Encoding` property in case we changed it for line length reasons 3263 | $this->Encoding = $bodyEncoding; 3264 | $body .= $this->encodeString($this->Body, $this->Encoding); 3265 | break; 3266 | } 3267 | if ($this->isError()) { 3268 | $body = ''; 3269 | } elseif ($this->sign_key_file) { 3270 | try { 3271 | if (!defined('PKCS7_TEXT')) { 3272 | throw new phpmailerException($this->lang('extension_missing') . 'openssl'); 3273 | } 3274 | // @TODO would be nice to use php://temp streams here, but need to wrap for PHP < 5.1 3275 | $file = tempnam(sys_get_temp_dir(), 'mail'); 3276 | if (false === file_put_contents($file, $body)) { 3277 | throw new phpmailerException($this->lang('signing') . ' Could not write temp file'); 3278 | } 3279 | $signed = tempnam(sys_get_temp_dir(), 'signed'); 3280 | //Workaround for PHP bug https://bugs.php.net/bug.php?id=69197 3281 | if (empty($this->sign_extracerts_file)) { 3282 | $sign = @openssl_pkcs7_sign( 3283 | $file, 3284 | $signed, 3285 | 'file://' . realpath($this->sign_cert_file), 3286 | array('file://' . realpath($this->sign_key_file), $this->sign_key_pass), 3287 | null 3288 | ); 3289 | } else { 3290 | $sign = @openssl_pkcs7_sign( 3291 | $file, 3292 | $signed, 3293 | 'file://' . realpath($this->sign_cert_file), 3294 | array('file://' . realpath($this->sign_key_file), $this->sign_key_pass), 3295 | null, 3296 | PKCS7_DETACHED, 3297 | $this->sign_extracerts_file 3298 | ); 3299 | } 3300 | if ($sign) { 3301 | @unlink($file); 3302 | $body = file_get_contents($signed); 3303 | @unlink($signed); 3304 | //The message returned by openssl contains both headers and body, so need to split them up 3305 | $parts = explode("\n\n", $body, 2); 3306 | $this->MIMEHeader .= $parts[0] . $this->LE . $this->LE; 3307 | $body = $parts[1]; 3308 | } else { 3309 | @unlink($file); 3310 | @unlink($signed); 3311 | throw new phpmailerException($this->lang('signing') . openssl_error_string()); 3312 | } 3313 | } catch (phpmailerException $exc) { 3314 | $body = ''; 3315 | if ($this->exceptions) { 3316 | throw $exc; 3317 | } 3318 | } 3319 | } 3320 | return $body; 3321 | } 3322 | /** 3323 | * Return the start of a message boundary. 3324 | * @access protected 3325 | * @param string $boundary 3326 | * @param string $charSet 3327 | * @param string $contentType 3328 | * @param string $encoding 3329 | * @return string 3330 | */ 3331 | protected function getBoundary($boundary, $charSet, $contentType, $encoding) 3332 | { 3333 | $result = ''; 3334 | if ($charSet == '') { 3335 | $charSet = $this->CharSet; 3336 | } 3337 | if ($contentType == '') { 3338 | $contentType = $this->ContentType; 3339 | } 3340 | if ($encoding == '') { 3341 | $encoding = $this->Encoding; 3342 | } 3343 | $result .= $this->textLine('--' . $boundary); 3344 | $result .= sprintf('Content-Type: %s; charset=%s', $contentType, $charSet); 3345 | $result .= $this->LE; 3346 | // RFC1341 part 5 says 7bit is assumed if not specified 3347 | if ($encoding != '7bit') { 3348 | $result .= $this->headerLine('Content-Transfer-Encoding', $encoding); 3349 | } 3350 | $result .= $this->LE; 3351 | return $result; 3352 | } 3353 | /** 3354 | * Return the end of a message boundary. 3355 | * @access protected 3356 | * @param string $boundary 3357 | * @return string 3358 | */ 3359 | protected function endBoundary($boundary) 3360 | { 3361 | return $this->LE . '--' . $boundary . '--' . $this->LE; 3362 | } 3363 | /** 3364 | * Set the message type. 3365 | * PHPMailer only supports some preset message types, not arbitrary MIME structures. 3366 | * @access protected 3367 | * @return void 3368 | */ 3369 | protected function setMessageType() 3370 | { 3371 | $type = array(); 3372 | if ($this->alternativeExists()) { 3373 | $type[] = 'alt'; 3374 | } 3375 | if ($this->inlineImageExists()) { 3376 | $type[] = 'inline'; 3377 | } 3378 | if ($this->attachmentExists()) { 3379 | $type[] = 'attach'; 3380 | } 3381 | $this->message_type = implode('_', $type); 3382 | if ($this->message_type == '') { 3383 | //The 'plain' message_type refers to the message having a single body element, not that it is plain-text 3384 | $this->message_type = 'plain'; 3385 | } 3386 | } 3387 | /** 3388 | * Format a header line. 3389 | * @access public 3390 | * @param string $name 3391 | * @param string $value 3392 | * @return string 3393 | */ 3394 | public function headerLine($name, $value) 3395 | { 3396 | return $name . ': ' . $value . $this->LE; 3397 | } 3398 | /** 3399 | * Return a formatted mail line. 3400 | * @access public 3401 | * @param string $value 3402 | * @return string 3403 | */ 3404 | public function textLine($value) 3405 | { 3406 | return $value . $this->LE; 3407 | } 3408 | /** 3409 | * Add an attachment from a path on the filesystem. 3410 | * Never use a user-supplied path to a file! 3411 | * Returns false if the file could not be found or read. 3412 | * @param string $path Path to the attachment. 3413 | * @param string $name Overrides the attachment name. 3414 | * @param string $encoding File encoding (see $Encoding). 3415 | * @param string $type File extension (MIME) type. 3416 | * @param string $disposition Disposition to use 3417 | * @throws phpmailerException 3418 | * @return boolean 3419 | */ 3420 | public function addAttachment($path, $name = '', $encoding = 'base64', $type = '', $disposition = 'attachment') 3421 | { 3422 | try { 3423 | if (!@is_file($path)) { 3424 | throw new phpmailerException($this->lang('file_access') . $path, self::STOP_CONTINUE); 3425 | } 3426 | // If a MIME type is not specified, try to work it out from the file name 3427 | if ($type == '') { 3428 | $type = self::filenameToType($path); 3429 | } 3430 | $filename = basename($path); 3431 | if ($name == '') { 3432 | $name = $filename; 3433 | } 3434 | $this->attachment[] = array( 3435 | 0 => $path, 3436 | 1 => $filename, 3437 | 2 => $name, 3438 | 3 => $encoding, 3439 | 4 => $type, 3440 | 5 => false, // isStringAttachment 3441 | 6 => $disposition, 3442 | 7 => 0 3443 | ); 3444 | } catch (phpmailerException $exc) { 3445 | $this->setError($exc->getMessage()); 3446 | $this->edebug($exc->getMessage()); 3447 | if ($this->exceptions) { 3448 | throw $exc; 3449 | } 3450 | return false; 3451 | } 3452 | return true; 3453 | } 3454 | /** 3455 | * Return the array of attachments. 3456 | * @return array 3457 | */ 3458 | public function getAttachments() 3459 | { 3460 | return $this->attachment; 3461 | } 3462 | /** 3463 | * Attach all file, string, and binary attachments to the message. 3464 | * Returns an empty string on failure. 3465 | * @access protected 3466 | * @param string $disposition_type 3467 | * @param string $boundary 3468 | * @return string 3469 | */ 3470 | protected function attachAll($disposition_type, $boundary) 3471 | { 3472 | // Return text of body 3473 | $mime = array(); 3474 | $cidUniq = array(); 3475 | $incl = array(); 3476 | // Add all attachments 3477 | foreach ($this->attachment as $attachment) { 3478 | // Check if it is a valid disposition_filter 3479 | if ($attachment[6] == $disposition_type) { 3480 | // Check for string attachment 3481 | $string = ''; 3482 | $path = ''; 3483 | $bString = $attachment[5]; 3484 | if ($bString) { 3485 | $string = $attachment[0]; 3486 | } else { 3487 | $path = $attachment[0]; 3488 | } 3489 | $inclhash = md5(serialize($attachment)); 3490 | if (in_array($inclhash, $incl)) { 3491 | continue; 3492 | } 3493 | $incl[] = $inclhash; 3494 | $name = $attachment[2]; 3495 | $encoding = $attachment[3]; 3496 | $type = $attachment[4]; 3497 | $disposition = $attachment[6]; 3498 | $cid = $attachment[7]; 3499 | if ($disposition == 'inline' && array_key_exists($cid, $cidUniq)) { 3500 | continue; 3501 | } 3502 | $cidUniq[$cid] = true; 3503 | $mime[] = sprintf('--%s%s', $boundary, $this->LE); 3504 | //Only include a filename property if we have one 3505 | if (!empty($name)) { 3506 | $mime[] = sprintf( 3507 | 'Content-Type: %s; name="%s"%s', 3508 | $type, 3509 | $this->encodeHeader($this->secureHeader($name)), 3510 | $this->LE 3511 | ); 3512 | } else { 3513 | $mime[] = sprintf( 3514 | 'Content-Type: %s%s', 3515 | $type, 3516 | $this->LE 3517 | ); 3518 | } 3519 | // RFC1341 part 5 says 7bit is assumed if not specified 3520 | if ($encoding != '7bit') { 3521 | $mime[] = sprintf('Content-Transfer-Encoding: %s%s', $encoding, $this->LE); 3522 | } 3523 | if ($disposition == 'inline') { 3524 | $mime[] = sprintf('Content-ID: <%s>%s', $cid, $this->LE); 3525 | } 3526 | // If a filename contains any of these chars, it should be quoted, 3527 | // but not otherwise: RFC2183 & RFC2045 5.1 3528 | // Fixes a warning in IETF's msglint MIME checker 3529 | // Allow for bypassing the Content-Disposition header totally 3530 | if (!(empty($disposition))) { 3531 | $encoded_name = $this->encodeHeader($this->secureHeader($name)); 3532 | if (preg_match('/[ \(\)<>@,;:\\"\/\[\]\?=]/', $encoded_name)) { 3533 | $mime[] = sprintf( 3534 | 'Content-Disposition: %s; filename="%s"%s', 3535 | $disposition, 3536 | $encoded_name, 3537 | $this->LE . $this->LE 3538 | ); 3539 | } else { 3540 | if (!empty($encoded_name)) { 3541 | $mime[] = sprintf( 3542 | 'Content-Disposition: %s; filename=%s%s', 3543 | $disposition, 3544 | $encoded_name, 3545 | $this->LE . $this->LE 3546 | ); 3547 | } else { 3548 | $mime[] = sprintf( 3549 | 'Content-Disposition: %s%s', 3550 | $disposition, 3551 | $this->LE . $this->LE 3552 | ); 3553 | } 3554 | } 3555 | } else { 3556 | $mime[] = $this->LE; 3557 | } 3558 | // Encode as string attachment 3559 | if ($bString) { 3560 | $mime[] = $this->encodeString($string, $encoding); 3561 | if ($this->isError()) { 3562 | return ''; 3563 | } 3564 | $mime[] = $this->LE . $this->LE; 3565 | } else { 3566 | $mime[] = $this->encodeFile($path, $encoding); 3567 | if ($this->isError()) { 3568 | return ''; 3569 | } 3570 | $mime[] = $this->LE . $this->LE; 3571 | } 3572 | } 3573 | } 3574 | $mime[] = sprintf('--%s--%s', $boundary, $this->LE); 3575 | return implode('', $mime); 3576 | } 3577 | /** 3578 | * Encode a file attachment in requested format. 3579 | * Returns an empty string on failure. 3580 | * @param string $path The full path to the file 3581 | * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable' 3582 | * @throws phpmailerException 3583 | * @access protected 3584 | * @return string 3585 | */ 3586 | protected function encodeFile($path, $encoding = 'base64') 3587 | { 3588 | try { 3589 | if (!is_readable($path)) { 3590 | throw new phpmailerException($this->lang('file_open') . $path, self::STOP_CONTINUE); 3591 | } 3592 | $magic_quotes = get_magic_quotes_runtime(); 3593 | if ($magic_quotes) { 3594 | if (version_compare(PHP_VERSION, '5.3.0', '<')) { 3595 | set_magic_quotes_runtime(false); 3596 | } else { 3597 | //Doesn't exist in PHP 5.4, but we don't need to check because 3598 | //get_magic_quotes_runtime always returns false in 5.4+ 3599 | //so it will never get here 3600 | ini_set('magic_quotes_runtime', false); 3601 | } 3602 | } 3603 | $file_buffer = file_get_contents($path); 3604 | $file_buffer = $this->encodeString($file_buffer, $encoding); 3605 | if ($magic_quotes) { 3606 | if (version_compare(PHP_VERSION, '5.3.0', '<')) { 3607 | set_magic_quotes_runtime($magic_quotes); 3608 | } else { 3609 | ini_set('magic_quotes_runtime', $magic_quotes); 3610 | } 3611 | } 3612 | return $file_buffer; 3613 | } catch (Exception $exc) { 3614 | $this->setError($exc->getMessage()); 3615 | return ''; 3616 | } 3617 | } 3618 | /** 3619 | * Encode a string in requested format. 3620 | * Returns an empty string on failure. 3621 | * @param string $str The text to encode 3622 | * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable' 3623 | * @access public 3624 | * @return string 3625 | */ 3626 | public function encodeString($str, $encoding = 'base64') 3627 | { 3628 | $encoded = ''; 3629 | switch (strtolower($encoding)) { 3630 | case 'base64': 3631 | $encoded = chunk_split(base64_encode($str), 76, $this->LE); 3632 | break; 3633 | case '7bit': 3634 | case '8bit': 3635 | $encoded = $this->fixEOL($str); 3636 | // Make sure it ends with a line break 3637 | if (substr($encoded, -(strlen($this->LE))) != $this->LE) { 3638 | $encoded .= $this->LE; 3639 | } 3640 | break; 3641 | case 'binary': 3642 | $encoded = $str; 3643 | break; 3644 | case 'quoted-printable': 3645 | $encoded = $this->encodeQP($str); 3646 | break; 3647 | default: 3648 | $this->setError($this->lang('encoding') . $encoding); 3649 | break; 3650 | } 3651 | return $encoded; 3652 | } 3653 | /** 3654 | * Encode a header string optimally. 3655 | * Picks shortest of Q, B, quoted-printable or none. 3656 | * @access public 3657 | * @param string $str 3658 | * @param string $position 3659 | * @return string 3660 | */ 3661 | public function encodeHeader($str, $position = 'text') 3662 | { 3663 | $matchcount = 0; 3664 | switch (strtolower($position)) { 3665 | case 'phrase': 3666 | if (!preg_match('/[\200-\377]/', $str)) { 3667 | // Can't use addslashes as we don't know the value of magic_quotes_sybase 3668 | $encoded = addcslashes($str, "\0..\37\177\\\""); 3669 | if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) { 3670 | return ($encoded); 3671 | } else { 3672 | return ("\"$encoded\""); 3673 | } 3674 | } 3675 | $matchcount = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches); 3676 | break; 3677 | /** @noinspection PhpMissingBreakStatementInspection */ 3678 | case 'comment': 3679 | $matchcount = preg_match_all('/[()"]/', $str, $matches); 3680 | // Intentional fall-through 3681 | case 'text': 3682 | default: 3683 | $matchcount += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches); 3684 | break; 3685 | } 3686 | //There are no chars that need encoding 3687 | if ($matchcount == 0) { 3688 | return ($str); 3689 | } 3690 | $maxlen = 75 - 7 - strlen($this->CharSet); 3691 | // Try to select the encoding which should produce the shortest output 3692 | if ($matchcount > strlen($str) / 3) { 3693 | // More than a third of the content will need encoding, so B encoding will be most efficient 3694 | $encoding = 'B'; 3695 | if (function_exists('mb_strlen') && $this->hasMultiBytes($str)) { 3696 | // Use a custom function which correctly encodes and wraps long 3697 | // multibyte strings without breaking lines within a character 3698 | $encoded = $this->base64EncodeWrapMB($str, "\n"); 3699 | } else { 3700 | $encoded = base64_encode($str); 3701 | $maxlen -= $maxlen % 4; 3702 | $encoded = trim(chunk_split($encoded, $maxlen, "\n")); 3703 | } 3704 | } else { 3705 | $encoding = 'Q'; 3706 | $encoded = $this->encodeQ($str, $position); 3707 | $encoded = $this->wrapText($encoded, $maxlen, true); 3708 | $encoded = str_replace('=' . self::CRLF, "\n", trim($encoded)); 3709 | } 3710 | $encoded = preg_replace('/^(.*)$/m', ' =?' . $this->CharSet . "?$encoding?\\1?=", $encoded); 3711 | $encoded = trim(str_replace("\n", $this->LE, $encoded)); 3712 | return $encoded; 3713 | } 3714 | /** 3715 | * Check if a string contains multi-byte characters. 3716 | * @access public 3717 | * @param string $str multi-byte text to wrap encode 3718 | * @return boolean 3719 | */ 3720 | public function hasMultiBytes($str) 3721 | { 3722 | if (function_exists('mb_strlen')) { 3723 | return (strlen($str) > mb_strlen($str, $this->CharSet)); 3724 | } else { // Assume no multibytes (we can't handle without mbstring functions anyway) 3725 | return false; 3726 | } 3727 | } 3728 | /** 3729 | * Does a string contain any 8-bit chars (in any charset)? 3730 | * @param string $text 3731 | * @return boolean 3732 | */ 3733 | public function has8bitChars($text) 3734 | { 3735 | return (boolean)preg_match('/[\x80-\xFF]/', $text); 3736 | } 3737 | /** 3738 | * Encode and wrap long multibyte strings for mail headers 3739 | * without breaking lines within a character. 3740 | * Adapted from a function by paravoid 3741 | * @link http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283 3742 | * @access public 3743 | * @param string $str multi-byte text to wrap encode 3744 | * @param string $linebreak string to use as linefeed/end-of-line 3745 | * @return string 3746 | */ 3747 | public function base64EncodeWrapMB($str, $linebreak = null) 3748 | { 3749 | $start = '=?' . $this->CharSet . '?B?'; 3750 | $end = '?='; 3751 | $encoded = ''; 3752 | if ($linebreak === null) { 3753 | $linebreak = $this->LE; 3754 | } 3755 | $mb_length = mb_strlen($str, $this->CharSet); 3756 | // Each line must have length <= 75, including $start and $end 3757 | $length = 75 - strlen($start) - strlen($end); 3758 | // Average multi-byte ratio 3759 | $ratio = $mb_length / strlen($str); 3760 | // Base64 has a 4:3 ratio 3761 | $avgLength = floor($length * $ratio * .75); 3762 | for ($i = 0; $i < $mb_length; $i += $offset) { 3763 | $lookBack = 0; 3764 | do { 3765 | $offset = $avgLength - $lookBack; 3766 | $chunk = mb_substr($str, $i, $offset, $this->CharSet); 3767 | $chunk = base64_encode($chunk); 3768 | $lookBack++; 3769 | } while (strlen($chunk) > $length); 3770 | $encoded .= $chunk . $linebreak; 3771 | } 3772 | // Chomp the last linefeed 3773 | $encoded = substr($encoded, 0, -strlen($linebreak)); 3774 | return $encoded; 3775 | } 3776 | /** 3777 | * Encode a string in quoted-printable format. 3778 | * According to RFC2045 section 6.7. 3779 | * @access public 3780 | * @param string $string The text to encode 3781 | * @param integer $line_max Number of chars allowed on a line before wrapping 3782 | * @return string 3783 | * @link http://www.php.net/manual/en/function.quoted-printable-decode.php#89417 Adapted from this comment 3784 | */ 3785 | public function encodeQP($string, $line_max = 76) 3786 | { 3787 | // Use native function if it's available (>= PHP5.3) 3788 | if (function_exists('quoted_printable_encode')) { 3789 | return quoted_printable_encode($string); 3790 | } 3791 | // Fall back to a pure PHP implementation 3792 | $string = str_replace( 3793 | array('%20', '%0D%0A.', '%0D%0A', '%'), 3794 | array(' ', "\r\n=2E", "\r\n", '='), 3795 | rawurlencode($string) 3796 | ); 3797 | return preg_replace('/[^\r\n]{' . ($line_max - 3) . '}[^=\r\n]{2}/', "$0=\r\n", $string); 3798 | } 3799 | /** 3800 | * Backward compatibility wrapper for an old QP encoding function that was removed. 3801 | * @see PHPMailer::encodeQP() 3802 | * @access public 3803 | * @param string $string 3804 | * @param integer $line_max 3805 | * @param boolean $space_conv 3806 | * @return string 3807 | * @deprecated Use encodeQP instead. 3808 | */ 3809 | public function encodeQPphp( 3810 | $string, 3811 | $line_max = 76, 3812 | /** @noinspection PhpUnusedParameterInspection */ $space_conv = false 3813 | ) { 3814 | return $this->encodeQP($string, $line_max); 3815 | } 3816 | /** 3817 | * Encode a string using Q encoding. 3818 | * @link http://tools.ietf.org/html/rfc2047 3819 | * @param string $str the text to encode 3820 | * @param string $position Where the text is going to be used, see the RFC for what that means 3821 | * @access public 3822 | * @return string 3823 | */ 3824 | public function encodeQ($str, $position = 'text') 3825 | { 3826 | // There should not be any EOL in the string 3827 | $pattern = ''; 3828 | $encoded = str_replace(array("\r", "\n"), '', $str); 3829 | switch (strtolower($position)) { 3830 | case 'phrase': 3831 | // RFC 2047 section 5.3 3832 | $pattern = '^A-Za-z0-9!*+\/ -'; 3833 | break; 3834 | /** @noinspection PhpMissingBreakStatementInspection */ 3835 | case 'comment': 3836 | // RFC 2047 section 5.2 3837 | $pattern = '\(\)"'; 3838 | // intentional fall-through 3839 | // for this reason we build the $pattern without including delimiters and [] 3840 | case 'text': 3841 | default: 3842 | // RFC 2047 section 5.1 3843 | // Replace every high ascii, control, =, ? and _ characters 3844 | $pattern = '\000-\011\013\014\016-\037\075\077\137\177-\377' . $pattern; 3845 | break; 3846 | } 3847 | $matches = array(); 3848 | if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) { 3849 | // If the string contains an '=', make sure it's the first thing we replace 3850 | // so as to avoid double-encoding 3851 | $eqkey = array_search('=', $matches[0]); 3852 | if (false !== $eqkey) { 3853 | unset($matches[0][$eqkey]); 3854 | array_unshift($matches[0], '='); 3855 | } 3856 | foreach (array_unique($matches[0]) as $char) { 3857 | $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded); 3858 | } 3859 | } 3860 | // Replace every spaces to _ (more readable than =20) 3861 | return str_replace(' ', '_', $encoded); 3862 | } 3863 | /** 3864 | * Add a string or binary attachment (non-filesystem). 3865 | * This method can be used to attach ascii or binary data, 3866 | * such as a BLOB record from a database. 3867 | * @param string $string String attachment data. 3868 | * @param string $filename Name of the attachment. 3869 | * @param string $encoding File encoding (see $Encoding). 3870 | * @param string $type File extension (MIME) type. 3871 | * @param string $disposition Disposition to use 3872 | * @return void 3873 | */ 3874 | public function addStringAttachment( 3875 | $string, 3876 | $filename, 3877 | $encoding = 'base64', 3878 | $type = '', 3879 | $disposition = 'attachment' 3880 | ) { 3881 | // If a MIME type is not specified, try to work it out from the file name 3882 | if ($type == '') { 3883 | $type = self::filenameToType($filename); 3884 | } 3885 | // Append to $attachment array 3886 | $this->attachment[] = array( 3887 | 0 => $string, 3888 | 1 => $filename, 3889 | 2 => basename($filename), 3890 | 3 => $encoding, 3891 | 4 => $type, 3892 | 5 => true, // isStringAttachment 3893 | 6 => $disposition, 3894 | 7 => 0 3895 | ); 3896 | } 3897 | /** 3898 | * Add an embedded (inline) attachment from a file. 3899 | * This can include images, sounds, and just about any other document type. 3900 | * These differ from 'regular' attachments in that they are intended to be 3901 | * displayed inline with the message, not just attached for download. 3902 | * This is used in HTML messages that embed the images 3903 | * the HTML refers to using the $cid value. 3904 | * Never use a user-supplied path to a file! 3905 | * @param string $path Path to the attachment. 3906 | * @param string $cid Content ID of the attachment; Use this to reference 3907 | * the content when using an embedded image in HTML. 3908 | * @param string $name Overrides the attachment name. 3909 | * @param string $encoding File encoding (see $Encoding). 3910 | * @param string $type File MIME type. 3911 | * @param string $disposition Disposition to use 3912 | * @return boolean True on successfully adding an attachment 3913 | */ 3914 | public function addEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = '', $disposition = 'inline') 3915 | { 3916 | if (!@is_file($path)) { 3917 | $this->setError($this->lang('file_access') . $path); 3918 | return false; 3919 | } 3920 | // If a MIME type is not specified, try to work it out from the file name 3921 | if ($type == '') { 3922 | $type = self::filenameToType($path); 3923 | } 3924 | $filename = basename($path); 3925 | if ($name == '') { 3926 | $name = $filename; 3927 | } 3928 | // Append to $attachment array 3929 | $this->attachment[] = array( 3930 | 0 => $path, 3931 | 1 => $filename, 3932 | 2 => $name, 3933 | 3 => $encoding, 3934 | 4 => $type, 3935 | 5 => false, // isStringAttachment 3936 | 6 => $disposition, 3937 | 7 => $cid 3938 | ); 3939 | return true; 3940 | } 3941 | /** 3942 | * Add an embedded stringified attachment. 3943 | * This can include images, sounds, and just about any other document type. 3944 | * Be sure to set the $type to an image type for images: 3945 | * JPEG images use 'image/jpeg', GIF uses 'image/gif', PNG uses 'image/png'. 3946 | * @param string $string The attachment binary data. 3947 | * @param string $cid Content ID of the attachment; Use this to reference 3948 | * the content when using an embedded image in HTML. 3949 | * @param string $name 3950 | * @param string $encoding File encoding (see $Encoding). 3951 | * @param string $type MIME type. 3952 | * @param string $disposition Disposition to use 3953 | * @return boolean True on successfully adding an attachment 3954 | */ 3955 | public function addStringEmbeddedImage( 3956 | $string, 3957 | $cid, 3958 | $name = '', 3959 | $encoding = 'base64', 3960 | $type = '', 3961 | $disposition = 'inline' 3962 | ) { 3963 | // If a MIME type is not specified, try to work it out from the name 3964 | if ($type == '' and !empty($name)) { 3965 | $type = self::filenameToType($name); 3966 | } 3967 | // Append to $attachment array 3968 | $this->attachment[] = array( 3969 | 0 => $string, 3970 | 1 => $name, 3971 | 2 => $name, 3972 | 3 => $encoding, 3973 | 4 => $type, 3974 | 5 => true, // isStringAttachment 3975 | 6 => $disposition, 3976 | 7 => $cid 3977 | ); 3978 | return true; 3979 | } 3980 | /** 3981 | * Check if an inline attachment is present. 3982 | * @access public 3983 | * @return boolean 3984 | */ 3985 | public function inlineImageExists() 3986 | { 3987 | foreach ($this->attachment as $attachment) { 3988 | if ($attachment[6] == 'inline') { 3989 | return true; 3990 | } 3991 | } 3992 | return false; 3993 | } 3994 | /** 3995 | * Check if an attachment (non-inline) is present. 3996 | * @return boolean 3997 | */ 3998 | public function attachmentExists() 3999 | { 4000 | foreach ($this->attachment as $attachment) { 4001 | if ($attachment[6] == 'attachment') { 4002 | return true; 4003 | } 4004 | } 4005 | return false; 4006 | } 4007 | /** 4008 | * Check if this message has an alternative body set. 4009 | * @return boolean 4010 | */ 4011 | public function alternativeExists() 4012 | { 4013 | return !empty($this->AltBody); 4014 | } 4015 | /** 4016 | * Clear queued addresses of given kind. 4017 | * @access protected 4018 | * @param string $kind 'to', 'cc', or 'bcc' 4019 | * @return void 4020 | */ 4021 | public function clearQueuedAddresses($kind) 4022 | { 4023 | $RecipientsQueue = $this->RecipientsQueue; 4024 | foreach ($RecipientsQueue as $address => $params) { 4025 | if ($params[0] == $kind) { 4026 | unset($this->RecipientsQueue[$address]); 4027 | } 4028 | } 4029 | } 4030 | /** 4031 | * Clear all To recipients. 4032 | * @return void 4033 | */ 4034 | public function clearAddresses() 4035 | { 4036 | foreach ($this->to as $to) { 4037 | unset($this->all_recipients[strtolower($to[0])]); 4038 | } 4039 | $this->to = array(); 4040 | $this->clearQueuedAddresses('to'); 4041 | } 4042 | /** 4043 | * Clear all CC recipients. 4044 | * @return void 4045 | */ 4046 | public function clearCCs() 4047 | { 4048 | foreach ($this->cc as $cc) { 4049 | unset($this->all_recipients[strtolower($cc[0])]); 4050 | } 4051 | $this->cc = array(); 4052 | $this->clearQueuedAddresses('cc'); 4053 | } 4054 | /** 4055 | * Clear all BCC recipients. 4056 | * @return void 4057 | */ 4058 | public function clearBCCs() 4059 | { 4060 | foreach ($this->bcc as $bcc) { 4061 | unset($this->all_recipients[strtolower($bcc[0])]); 4062 | } 4063 | $this->bcc = array(); 4064 | $this->clearQueuedAddresses('bcc'); 4065 | } 4066 | /** 4067 | * Clear all ReplyTo recipients. 4068 | * @return void 4069 | */ 4070 | public function clearReplyTos() 4071 | { 4072 | $this->ReplyTo = array(); 4073 | $this->ReplyToQueue = array(); 4074 | } 4075 | /** 4076 | * Clear all recipient types. 4077 | * @return void 4078 | */ 4079 | public function clearAllRecipients() 4080 | { 4081 | $this->to = array(); 4082 | $this->cc = array(); 4083 | $this->bcc = array(); 4084 | $this->all_recipients = array(); 4085 | $this->RecipientsQueue = array(); 4086 | } 4087 | /** 4088 | * Clear all filesystem, string, and binary attachments. 4089 | * @return void 4090 | */ 4091 | public function clearAttachments() 4092 | { 4093 | $this->attachment = array(); 4094 | } 4095 | /** 4096 | * Clear all custom headers. 4097 | * @return void 4098 | */ 4099 | public function clearCustomHeaders() 4100 | { 4101 | $this->CustomHeader = array(); 4102 | } 4103 | /** 4104 | * Add an error message to the error container. 4105 | * @access protected 4106 | * @param string $msg 4107 | * @return void 4108 | */ 4109 | protected function setError($msg) 4110 | { 4111 | $this->error_count++; 4112 | if ($this->Mailer == 'smtp' and !is_null($this->smtp)) { 4113 | $lasterror = $this->smtp->getError(); 4114 | if (!empty($lasterror['error'])) { 4115 | $msg .= $this->lang('smtp_error') . $lasterror['error']; 4116 | if (!empty($lasterror['detail'])) { 4117 | $msg .= ' Detail: '. $lasterror['detail']; 4118 | } 4119 | if (!empty($lasterror['smtp_code'])) { 4120 | $msg .= ' SMTP code: ' . $lasterror['smtp_code']; 4121 | } 4122 | if (!empty($lasterror['smtp_code_ex'])) { 4123 | $msg .= ' Additional SMTP info: ' . $lasterror['smtp_code_ex']; 4124 | } 4125 | } 4126 | } 4127 | $this->ErrorInfo = $msg; 4128 | } 4129 | /** 4130 | * Return an RFC 822 formatted date. 4131 | * @access public 4132 | * @return string 4133 | * @static 4134 | */ 4135 | public static function rfcDate() 4136 | { 4137 | // Set the time zone to whatever the default is to avoid 500 errors 4138 | // Will default to UTC if it's not set properly in php.ini 4139 | date_default_timezone_set(@date_default_timezone_get()); 4140 | return date('D, j M Y H:i:s O'); 4141 | } 4142 | /** 4143 | * Get the server hostname. 4144 | * Returns 'localhost.localdomain' if unknown. 4145 | * @access protected 4146 | * @return string 4147 | */ 4148 | protected function serverHostname() 4149 | { 4150 | $result = 'localhost.localdomain'; 4151 | if (!empty($this->Hostname)) { 4152 | $result = $this->Hostname; 4153 | } elseif (isset($_SERVER) and array_key_exists('SERVER_NAME', $_SERVER) and !empty($_SERVER['SERVER_NAME'])) { 4154 | $result = $_SERVER['SERVER_NAME']; 4155 | } elseif (function_exists('gethostname') && gethostname() !== false) { 4156 | $result = gethostname(); 4157 | } elseif (php_uname('n') !== false) { 4158 | $result = php_uname('n'); 4159 | } 4160 | return $result; 4161 | } 4162 | /** 4163 | * Get an error message in the current language. 4164 | * @access protected 4165 | * @param string $key 4166 | * @return string 4167 | */ 4168 | protected function lang($key) 4169 | { 4170 | if (count($this->language) < 1) { 4171 | $this->setLanguage('en'); // set the default language 4172 | } 4173 | if (array_key_exists($key, $this->language)) { 4174 | if ($key == 'smtp_connect_failed') { 4175 | //Include a link to troubleshooting docs on SMTP connection failure 4176 | //this is by far the biggest cause of support questions 4177 | //but it's usually not PHPMailer's fault. 4178 | return $this->language[$key] . ' https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting'; 4179 | } 4180 | return $this->language[$key]; 4181 | } else { 4182 | //Return the key as a fallback 4183 | return $key; 4184 | } 4185 | } 4186 | /** 4187 | * Check if an error occurred. 4188 | * @access public 4189 | * @return boolean True if an error did occur. 4190 | */ 4191 | public function isError() 4192 | { 4193 | return ($this->error_count > 0); 4194 | } 4195 | /** 4196 | * Ensure consistent line endings in a string. 4197 | * Changes every end of line from CRLF, CR or LF to $this->LE. 4198 | * @access public 4199 | * @param string $str String to fixEOL 4200 | * @return string 4201 | */ 4202 | public function fixEOL($str) 4203 | { 4204 | // Normalise to \n 4205 | $nstr = str_replace(array("\r\n", "\r"), "\n", $str); 4206 | // Now convert LE as needed 4207 | if ($this->LE !== "\n") { 4208 | $nstr = str_replace("\n", $this->LE, $nstr); 4209 | } 4210 | return $nstr; 4211 | } 4212 | /** 4213 | * Add a custom header. 4214 | * $name value can be overloaded to contain 4215 | * both header name and value (name:value) 4216 | * @access public 4217 | * @param string $name Custom header name 4218 | * @param string $value Header value 4219 | * @return void 4220 | */ 4221 | public function addCustomHeader($name, $value = null) 4222 | { 4223 | if ($value === null) { 4224 | // Value passed in as name:value 4225 | $this->CustomHeader[] = explode(':', $name, 2); 4226 | } else { 4227 | $this->CustomHeader[] = array($name, $value); 4228 | } 4229 | } 4230 | /** 4231 | * Returns all custom headers. 4232 | * @return array 4233 | */ 4234 | public function getCustomHeaders() 4235 | { 4236 | return $this->CustomHeader; 4237 | } 4238 | /** 4239 | * Create a message body from an HTML string. 4240 | * Automatically inlines images and creates a plain-text version by converting the HTML, 4241 | * overwriting any existing values in Body and AltBody. 4242 | * Do not source $message content from user input! 4243 | * $basedir is prepended when handling relative URLs, e.g. and must not be empty 4244 | * will look for an image file in $basedir/images/a.png and convert it to inline. 4245 | * If you don't provide a $basedir, relative paths will be left untouched (and thus probably break in email) 4246 | * If you don't want to apply these transformations to your HTML, just set Body and AltBody directly. 4247 | * @access public 4248 | * @param string $message HTML message string 4249 | * @param string $basedir Absolute path to a base directory to prepend to relative paths to images 4250 | * @param boolean|callable $advanced Whether to use the internal HTML to text converter 4251 | * or your own custom converter @see PHPMailer::html2text() 4252 | * @return string $message The transformed message Body 4253 | */ 4254 | public function msgHTML($message, $basedir = '', $advanced = false) 4255 | { 4256 | preg_match_all('/(src|background)=["\'](.*)["\']/Ui', $message, $images); 4257 | if (array_key_exists(2, $images)) { 4258 | if (strlen($basedir) > 1 && substr($basedir, -1) != '/') { 4259 | // Ensure $basedir has a trailing / 4260 | $basedir .= '/'; 4261 | } 4262 | foreach ($images[2] as $imgindex => $url) { 4263 | // Convert data URIs into embedded images 4264 | if (preg_match('#^data:(image[^;,]*)(;base64)?,#', $url, $match)) { 4265 | $data = substr($url, strpos($url, ',')); 4266 | if ($match[2]) { 4267 | $data = base64_decode($data); 4268 | } else { 4269 | $data = rawurldecode($data); 4270 | } 4271 | $cid = md5($url) . '@phpmailer.0'; // RFC2392 S 2 4272 | if ($this->addStringEmbeddedImage($data, $cid, 'embed' . $imgindex, 'base64', $match[1])) { 4273 | $message = str_replace( 4274 | $images[0][$imgindex], 4275 | $images[1][$imgindex] . '="cid:' . $cid . '"', 4276 | $message 4277 | ); 4278 | } 4279 | continue; 4280 | } 4281 | if ( 4282 | // Only process relative URLs if a basedir is provided (i.e. no absolute local paths) 4283 | !empty($basedir) 4284 | // Ignore URLs containing parent dir traversal (..) 4285 | && (strpos($url, '..') === false) 4286 | // Do not change urls that are already inline images 4287 | && substr($url, 0, 4) !== 'cid:' 4288 | // Do not change absolute URLs, including anonymous protocol 4289 | && !preg_match('#^[a-z][a-z0-9+.-]*:?//#i', $url) 4290 | ) { 4291 | $filename = basename($url); 4292 | $directory = dirname($url); 4293 | if ($directory == '.') { 4294 | $directory = ''; 4295 | } 4296 | $cid = md5($url) . '@phpmailer.0'; // RFC2392 S 2 4297 | if (strlen($directory) > 1 && substr($directory, -1) != '/') { 4298 | $directory .= '/'; 4299 | } 4300 | if ($this->addEmbeddedImage( 4301 | $basedir . $directory . $filename, 4302 | $cid, 4303 | $filename, 4304 | 'base64', 4305 | self::_mime_types((string)self::mb_pathinfo($filename, PATHINFO_EXTENSION)) 4306 | ) 4307 | ) { 4308 | $message = preg_replace( 4309 | '/' . $images[1][$imgindex] . '=["\']' . preg_quote($url, '/') . '["\']/Ui', 4310 | $images[1][$imgindex] . '="cid:' . $cid . '"', 4311 | $message 4312 | ); 4313 | } 4314 | } 4315 | } 4316 | } 4317 | $this->isHTML(true); 4318 | // Convert all message body line breaks to CRLF, makes quoted-printable encoding work much better 4319 | $this->Body = $this->normalizeBreaks($message); 4320 | $this->AltBody = $this->normalizeBreaks($this->html2text($message, $advanced)); 4321 | if (!$this->alternativeExists()) { 4322 | $this->AltBody = 'To view this email message, open it in a program that understands HTML!' . 4323 | self::CRLF . self::CRLF; 4324 | } 4325 | return $this->Body; 4326 | } 4327 | /** 4328 | * Convert an HTML string into plain text. 4329 | * This is used by msgHTML(). 4330 | * Note - older versions of this function used a bundled advanced converter 4331 | * which was been removed for license reasons in #232. 4332 | * Example usage: 4333 | * 4334 | * // Use default conversion 4335 | * $plain = $mail->html2text($html); 4336 | * // Use your own custom converter 4337 | * $plain = $mail->html2text($html, function($html) { 4338 | * $converter = new MyHtml2text($html); 4339 | * return $converter->get_text(); 4340 | * }); 4341 | * 4342 | * @param string $html The HTML text to convert 4343 | * @param boolean|callable $advanced Any boolean value to use the internal converter, 4344 | * or provide your own callable for custom conversion. 4345 | * @return string 4346 | */ 4347 | public function html2text($html, $advanced = false) 4348 | { 4349 | if (is_callable($advanced)) { 4350 | return call_user_func($advanced, $html); 4351 | } 4352 | return html_entity_decode( 4353 | trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/si', '', $html))), 4354 | ENT_QUOTES, 4355 | $this->CharSet 4356 | ); 4357 | } 4358 | /** 4359 | * Get the MIME type for a file extension. 4360 | * @param string $ext File extension 4361 | * @access public 4362 | * @return string MIME type of file. 4363 | * @static 4364 | */ 4365 | public static function _mime_types($ext = '') 4366 | { 4367 | $mimes = array( 4368 | 'xl' => 'application/excel', 4369 | 'js' => 'application/javascript', 4370 | 'hqx' => 'application/mac-binhex40', 4371 | 'cpt' => 'application/mac-compactpro', 4372 | 'bin' => 'application/macbinary', 4373 | 'doc' => 'application/msword', 4374 | 'word' => 'application/msword', 4375 | 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 4376 | 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template', 4377 | 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template', 4378 | 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow', 4379 | 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 4380 | 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide', 4381 | 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 4382 | 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template', 4383 | 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12', 4384 | 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12', 4385 | 'class' => 'application/octet-stream', 4386 | 'dll' => 'application/octet-stream', 4387 | 'dms' => 'application/octet-stream', 4388 | 'exe' => 'application/octet-stream', 4389 | 'lha' => 'application/octet-stream', 4390 | 'lzh' => 'application/octet-stream', 4391 | 'psd' => 'application/octet-stream', 4392 | 'sea' => 'application/octet-stream', 4393 | 'so' => 'application/octet-stream', 4394 | 'oda' => 'application/oda', 4395 | 'pdf' => 'application/pdf', 4396 | 'ai' => 'application/postscript', 4397 | 'eps' => 'application/postscript', 4398 | 'ps' => 'application/postscript', 4399 | 'smi' => 'application/smil', 4400 | 'smil' => 'application/smil', 4401 | 'mif' => 'application/vnd.mif', 4402 | 'xls' => 'application/vnd.ms-excel', 4403 | 'ppt' => 'application/vnd.ms-powerpoint', 4404 | 'wbxml' => 'application/vnd.wap.wbxml', 4405 | 'wmlc' => 'application/vnd.wap.wmlc', 4406 | 'dcr' => 'application/x-director', 4407 | 'dir' => 'application/x-director', 4408 | 'dxr' => 'application/x-director', 4409 | 'dvi' => 'application/x-dvi', 4410 | 'gtar' => 'application/x-gtar', 4411 | 'php3' => 'application/x-httpd-php', 4412 | 'php4' => 'application/x-httpd-php', 4413 | 'php' => 'application/x-httpd-php', 4414 | 'phtml' => 'application/x-httpd-php', 4415 | 'phps' => 'application/x-httpd-php-source', 4416 | 'swf' => 'application/x-shockwave-flash', 4417 | 'sit' => 'application/x-stuffit', 4418 | 'tar' => 'application/x-tar', 4419 | 'tgz' => 'application/x-tar', 4420 | 'xht' => 'application/xhtml+xml', 4421 | 'xhtml' => 'application/xhtml+xml', 4422 | 'zip' => 'application/zip', 4423 | 'mid' => 'audio/midi', 4424 | 'midi' => 'audio/midi', 4425 | 'mp2' => 'audio/mpeg', 4426 | 'mp3' => 'audio/mpeg', 4427 | 'mpga' => 'audio/mpeg', 4428 | 'aif' => 'audio/x-aiff', 4429 | 'aifc' => 'audio/x-aiff', 4430 | 'aiff' => 'audio/x-aiff', 4431 | 'ram' => 'audio/x-pn-realaudio', 4432 | 'rm' => 'audio/x-pn-realaudio', 4433 | 'rpm' => 'audio/x-pn-realaudio-plugin', 4434 | 'ra' => 'audio/x-realaudio', 4435 | 'wav' => 'audio/x-wav', 4436 | 'bmp' => 'image/bmp', 4437 | 'gif' => 'image/gif', 4438 | 'jpeg' => 'image/jpeg', 4439 | 'jpe' => 'image/jpeg', 4440 | 'jpg' => 'image/jpeg', 4441 | 'png' => 'image/png', 4442 | 'tiff' => 'image/tiff', 4443 | 'tif' => 'image/tiff', 4444 | 'eml' => 'message/rfc822', 4445 | 'css' => 'text/css', 4446 | 'html' => 'text/html', 4447 | 'htm' => 'text/html', 4448 | 'shtml' => 'text/html', 4449 | 'log' => 'text/plain', 4450 | 'text' => 'text/plain', 4451 | 'txt' => 'text/plain', 4452 | 'rtx' => 'text/richtext', 4453 | 'rtf' => 'text/rtf', 4454 | 'vcf' => 'text/vcard', 4455 | 'vcard' => 'text/vcard', 4456 | 'xml' => 'text/xml', 4457 | 'xsl' => 'text/xml', 4458 | 'mpeg' => 'video/mpeg', 4459 | 'mpe' => 'video/mpeg', 4460 | 'mpg' => 'video/mpeg', 4461 | 'mov' => 'video/quicktime', 4462 | 'qt' => 'video/quicktime', 4463 | 'rv' => 'video/vnd.rn-realvideo', 4464 | 'avi' => 'video/x-msvideo', 4465 | 'movie' => 'video/x-sgi-movie' 4466 | ); 4467 | if (array_key_exists(strtolower($ext), $mimes)) { 4468 | return $mimes[strtolower($ext)]; 4469 | } 4470 | return 'application/octet-stream'; 4471 | } 4472 | /** 4473 | * Map a file name to a MIME type. 4474 | * Defaults to 'application/octet-stream', i.e.. arbitrary binary data. 4475 | * @param string $filename A file name or full path, does not need to exist as a file 4476 | * @return string 4477 | * @static 4478 | */ 4479 | public static function filenameToType($filename) 4480 | { 4481 | // In case the path is a URL, strip any query string before getting extension 4482 | $qpos = strpos($filename, '?'); 4483 | if (false !== $qpos) { 4484 | $filename = substr($filename, 0, $qpos); 4485 | } 4486 | $pathinfo = self::mb_pathinfo($filename); 4487 | return self::_mime_types($pathinfo['extension']); 4488 | } 4489 | /** 4490 | * Multi-byte-safe pathinfo replacement. 4491 | * Drop-in replacement for pathinfo(), but multibyte-safe, cross-platform-safe, old-version-safe. 4492 | * Works similarly to the one in PHP >= 5.2.0 4493 | * @link http://www.php.net/manual/en/function.pathinfo.php#107461 4494 | * @param string $path A filename or path, does not need to exist as a file 4495 | * @param integer|string $options Either a PATHINFO_* constant, 4496 | * or a string name to return only the specified piece, allows 'filename' to work on PHP < 5.2 4497 | * @return string|array 4498 | * @static 4499 | */ 4500 | public static function mb_pathinfo($path, $options = null) 4501 | { 4502 | $ret = array('dirname' => '', 'basename' => '', 'extension' => '', 'filename' => ''); 4503 | $pathinfo = array(); 4504 | if (preg_match('%^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^\.\\\\/]+?)|))[\\\\/\.]*$%im', $path, $pathinfo)) { 4505 | if (array_key_exists(1, $pathinfo)) { 4506 | $ret['dirname'] = $pathinfo[1]; 4507 | } 4508 | if (array_key_exists(2, $pathinfo)) { 4509 | $ret['basename'] = $pathinfo[2]; 4510 | } 4511 | if (array_key_exists(5, $pathinfo)) { 4512 | $ret['extension'] = $pathinfo[5]; 4513 | } 4514 | if (array_key_exists(3, $pathinfo)) { 4515 | $ret['filename'] = $pathinfo[3]; 4516 | } 4517 | } 4518 | switch ($options) { 4519 | case PATHINFO_DIRNAME: 4520 | case 'dirname': 4521 | return $ret['dirname']; 4522 | case PATHINFO_BASENAME: 4523 | case 'basename': 4524 | return $ret['basename']; 4525 | case PATHINFO_EXTENSION: 4526 | case 'extension': 4527 | return $ret['extension']; 4528 | case PATHINFO_FILENAME: 4529 | case 'filename': 4530 | return $ret['filename']; 4531 | default: 4532 | return $ret; 4533 | } 4534 | } 4535 | /** 4536 | * Set or reset instance properties. 4537 | * You should avoid this function - it's more verbose, less efficient, more error-prone and 4538 | * harder to debug than setting properties directly. 4539 | * Usage Example: 4540 | * `$mail->set('SMTPSecure', 'tls');` 4541 | * is the same as: 4542 | * `$mail->SMTPSecure = 'tls';` 4543 | * @access public 4544 | * @param string $name The property name to set 4545 | * @param mixed $value The value to set the property to 4546 | * @return boolean 4547 | * @TODO Should this not be using the __set() magic function? 4548 | */ 4549 | public function set($name, $value = '') 4550 | { 4551 | if (property_exists($this, $name)) { 4552 | $this->$name = $value; 4553 | return true; 4554 | } else { 4555 | $this->setError($this->lang('variable_set') . $name); 4556 | return false; 4557 | } 4558 | } 4559 | /** 4560 | * Strip newlines to prevent header injection. 4561 | * @access public 4562 | * @param string $str 4563 | * @return string 4564 | */ 4565 | public function secureHeader($str) 4566 | { 4567 | return trim(str_replace(array("\r", "\n"), '', $str)); 4568 | } 4569 | /** 4570 | * Normalize line breaks in a string. 4571 | * Converts UNIX LF, Mac CR and Windows CRLF line breaks into a single line break format. 4572 | * Defaults to CRLF (for message bodies) and preserves consecutive breaks. 4573 | * @param string $text 4574 | * @param string $breaktype What kind of line break to use, defaults to CRLF 4575 | * @return string 4576 | * @access public 4577 | * @static 4578 | */ 4579 | public static function normalizeBreaks($text, $breaktype = "\r\n") 4580 | { 4581 | return preg_replace('/(\r\n|\r|\n)/ms', $breaktype, $text); 4582 | } 4583 | /** 4584 | * Set the public and private key files and password for S/MIME signing. 4585 | * @access public 4586 | * @param string $cert_filename 4587 | * @param string $key_filename 4588 | * @param string $key_pass Password for private key 4589 | * @param string $extracerts_filename Optional path to chain certificate 4590 | */ 4591 | public function sign($cert_filename, $key_filename, $key_pass, $extracerts_filename = '') 4592 | { 4593 | $this->sign_cert_file = $cert_filename; 4594 | $this->sign_key_file = $key_filename; 4595 | $this->sign_key_pass = $key_pass; 4596 | $this->sign_extracerts_file = $extracerts_filename; 4597 | } 4598 | /** 4599 | * Quoted-Printable-encode a DKIM header. 4600 | * @access public 4601 | * @param string $txt 4602 | * @return string 4603 | */ 4604 | public function DKIM_QP($txt) 4605 | { 4606 | $line = ''; 4607 | for ($i = 0; $i < strlen($txt); $i++) { 4608 | $ord = ord($txt[$i]); 4609 | if (((0x21 <= $ord) && ($ord <= 0x3A)) || $ord == 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E))) { 4610 | $line .= $txt[$i]; 4611 | } else { 4612 | $line .= '=' . sprintf('%02X', $ord); 4613 | } 4614 | } 4615 | return $line; 4616 | } 4617 | /** 4618 | * Generate a DKIM signature. 4619 | * @access public 4620 | * @param string $signHeader 4621 | * @throws phpmailerException 4622 | * @return string The DKIM signature value 4623 | */ 4624 | public function DKIM_Sign($signHeader) 4625 | { 4626 | if (!defined('PKCS7_TEXT')) { 4627 | if ($this->exceptions) { 4628 | throw new phpmailerException($this->lang('extension_missing') . 'openssl'); 4629 | } 4630 | return ''; 4631 | } 4632 | $privKeyStr = !empty($this->DKIM_private_string) ? $this->DKIM_private_string : file_get_contents($this->DKIM_private); 4633 | if ('' != $this->DKIM_passphrase) { 4634 | $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase); 4635 | } else { 4636 | $privKey = openssl_pkey_get_private($privKeyStr); 4637 | } 4638 | //Workaround for missing digest algorithms in old PHP & OpenSSL versions 4639 | //@link http://stackoverflow.com/a/11117338/333340 4640 | if (version_compare(PHP_VERSION, '5.3.0') >= 0 and 4641 | in_array('sha256WithRSAEncryption', openssl_get_md_methods(true))) { 4642 | if (openssl_sign($signHeader, $signature, $privKey, 'sha256WithRSAEncryption')) { 4643 | openssl_pkey_free($privKey); 4644 | return base64_encode($signature); 4645 | } 4646 | } else { 4647 | $pinfo = openssl_pkey_get_details($privKey); 4648 | $hash = hash('sha256', $signHeader); 4649 | //'Magic' constant for SHA256 from RFC3447 4650 | //@link https://tools.ietf.org/html/rfc3447#page-43 4651 | $t = '3031300d060960864801650304020105000420' . $hash; 4652 | $pslen = $pinfo['bits'] / 8 - (strlen($t) / 2 + 3); 4653 | $eb = pack('H*', '0001' . str_repeat('FF', $pslen) . '00' . $t); 4654 | if (openssl_private_encrypt($eb, $signature, $privKey, OPENSSL_NO_PADDING)) { 4655 | openssl_pkey_free($privKey); 4656 | return base64_encode($signature); 4657 | } 4658 | } 4659 | openssl_pkey_free($privKey); 4660 | return ''; 4661 | } 4662 | /** 4663 | * Generate a DKIM canonicalization header. 4664 | * @access public 4665 | * @param string $signHeader Header 4666 | * @return string 4667 | */ 4668 | public function DKIM_HeaderC($signHeader) 4669 | { 4670 | $signHeader = preg_replace('/\r\n\s+/', ' ', $signHeader); 4671 | $lines = explode("\r\n", $signHeader); 4672 | foreach ($lines as $key => $line) { 4673 | list($heading, $value) = explode(':', $line, 2); 4674 | $heading = strtolower($heading); 4675 | $value = preg_replace('/\s{2,}/', ' ', $value); // Compress useless spaces 4676 | $lines[$key] = $heading . ':' . trim($value); // Don't forget to remove WSP around the value 4677 | } 4678 | $signHeader = implode("\r\n", $lines); 4679 | return $signHeader; 4680 | } 4681 | /** 4682 | * Generate a DKIM canonicalization body. 4683 | * @access public 4684 | * @param string $body Message Body 4685 | * @return string 4686 | */ 4687 | public function DKIM_BodyC($body) 4688 | { 4689 | if ($body == '') { 4690 | return "\r\n"; 4691 | } 4692 | // stabilize line endings 4693 | $body = str_replace("\r\n", "\n", $body); 4694 | $body = str_replace("\n", "\r\n", $body); 4695 | // END stabilize line endings 4696 | while (substr($body, strlen($body) - 4, 4) == "\r\n\r\n") { 4697 | $body = substr($body, 0, strlen($body) - 2); 4698 | } 4699 | return $body; 4700 | } 4701 | /** 4702 | * Create the DKIM header and body in a new message header. 4703 | * @access public 4704 | * @param string $headers_line Header lines 4705 | * @param string $subject Subject 4706 | * @param string $body Body 4707 | * @return string 4708 | */ 4709 | public function DKIM_Add($headers_line, $subject, $body) 4710 | { 4711 | $DKIMsignatureType = 'rsa-sha256'; // Signature & hash algorithms 4712 | $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body 4713 | $DKIMquery = 'dns/txt'; // Query method 4714 | $DKIMtime = time(); // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone) 4715 | $subject_header = "Subject: $subject"; 4716 | $headers = explode($this->LE, $headers_line); 4717 | $from_header = ''; 4718 | $to_header = ''; 4719 | $date_header = ''; 4720 | $current = ''; 4721 | foreach ($headers as $header) { 4722 | if (strpos($header, 'From:') === 0) { 4723 | $from_header = $header; 4724 | $current = 'from_header'; 4725 | } elseif (strpos($header, 'To:') === 0) { 4726 | $to_header = $header; 4727 | $current = 'to_header'; 4728 | } elseif (strpos($header, 'Date:') === 0) { 4729 | $date_header = $header; 4730 | $current = 'date_header'; 4731 | } else { 4732 | if (!empty($$current) && strpos($header, ' =?') === 0) { 4733 | $$current .= $header; 4734 | } else { 4735 | $current = ''; 4736 | } 4737 | } 4738 | } 4739 | $from = str_replace('|', '=7C', $this->DKIM_QP($from_header)); 4740 | $to = str_replace('|', '=7C', $this->DKIM_QP($to_header)); 4741 | $date = str_replace('|', '=7C', $this->DKIM_QP($date_header)); 4742 | $subject = str_replace( 4743 | '|', 4744 | '=7C', 4745 | $this->DKIM_QP($subject_header) 4746 | ); // Copied header fields (dkim-quoted-printable) 4747 | $body = $this->DKIM_BodyC($body); 4748 | $DKIMlen = strlen($body); // Length of body 4749 | $DKIMb64 = base64_encode(pack('H*', hash('sha256', $body))); // Base64 of packed binary SHA-256 hash of body 4750 | if ('' == $this->DKIM_identity) { 4751 | $ident = ''; 4752 | } else { 4753 | $ident = ' i=' . $this->DKIM_identity . ';'; 4754 | } 4755 | $dkimhdrs = 'DKIM-Signature: v=1; a=' . 4756 | $DKIMsignatureType . '; q=' . 4757 | $DKIMquery . '; l=' . 4758 | $DKIMlen . '; s=' . 4759 | $this->DKIM_selector . 4760 | ";\r\n" . 4761 | "\tt=" . $DKIMtime . '; c=' . $DKIMcanonicalization . ";\r\n" . 4762 | "\th=From:To:Date:Subject;\r\n" . 4763 | "\td=" . $this->DKIM_domain . ';' . $ident . "\r\n" . 4764 | "\tz=$from\r\n" . 4765 | "\t|$to\r\n" . 4766 | "\t|$date\r\n" . 4767 | "\t|$subject;\r\n" . 4768 | "\tbh=" . $DKIMb64 . ";\r\n" . 4769 | "\tb="; 4770 | $toSign = $this->DKIM_HeaderC( 4771 | $from_header . "\r\n" . 4772 | $to_header . "\r\n" . 4773 | $date_header . "\r\n" . 4774 | $subject_header . "\r\n" . 4775 | $dkimhdrs 4776 | ); 4777 | $signed = $this->DKIM_Sign($toSign); 4778 | return $dkimhdrs . $signed . "\r\n"; 4779 | } 4780 | /** 4781 | * Detect if a string contains a line longer than the maximum line length allowed. 4782 | * @param string $str 4783 | * @return boolean 4784 | * @static 4785 | */ 4786 | public static function hasLineLongerThanMax($str) 4787 | { 4788 | //+2 to include CRLF line break for a 1000 total 4789 | return (boolean)preg_match('/^(.{'.(self::MAX_LINE_LENGTH + 2).',})/m', $str); 4790 | } 4791 | /** 4792 | * Allows for public read access to 'to' property. 4793 | * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included. 4794 | * @access public 4795 | * @return array 4796 | */ 4797 | public function getToAddresses() 4798 | { 4799 | return $this->to; 4800 | } 4801 | /** 4802 | * Allows for public read access to 'cc' property. 4803 | * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included. 4804 | * @access public 4805 | * @return array 4806 | */ 4807 | public function getCcAddresses() 4808 | { 4809 | return $this->cc; 4810 | } 4811 | /** 4812 | * Allows for public read access to 'bcc' property. 4813 | * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included. 4814 | * @access public 4815 | * @return array 4816 | */ 4817 | public function getBccAddresses() 4818 | { 4819 | return $this->bcc; 4820 | } 4821 | /** 4822 | * Allows for public read access to 'ReplyTo' property. 4823 | * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included. 4824 | * @access public 4825 | * @return array 4826 | */ 4827 | public function getReplyToAddresses() 4828 | { 4829 | return $this->ReplyTo; 4830 | } 4831 | /** 4832 | * Allows for public read access to 'all_recipients' property. 4833 | * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included. 4834 | * @access public 4835 | * @return array 4836 | */ 4837 | public function getAllRecipientAddresses() 4838 | { 4839 | return $this->all_recipients; 4840 | } 4841 | /** 4842 | * Perform a callback. 4843 | * @param boolean $isSent 4844 | * @param array $to 4845 | * @param array $cc 4846 | * @param array $bcc 4847 | * @param string $subject 4848 | * @param string $body 4849 | * @param string $from 4850 | */ 4851 | protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body, $from) 4852 | { 4853 | if (!empty($this->action_function) && is_callable($this->action_function)) { 4854 | $params = array($isSent, $to, $cc, $bcc, $subject, $body, $from); 4855 | call_user_func_array($this->action_function, $params); 4856 | } 4857 | } 4858 | } 4859 | /** 4860 | * PHPMailer exception handler 4861 | * @package PHPMailer 4862 | */ 4863 | class phpmailerException extends Exception 4864 | { 4865 | /** 4866 | * Prettify error message output 4867 | * @return string 4868 | */ 4869 | public function errorMessage() 4870 | { 4871 | $errorMsg = '' . $this->getMessage() . "
\n"; 4872 | return $errorMsg; 4873 | } 4874 | } 4875 | 4876 | -------------------------------------------------------------------------------- /Plugin.php: -------------------------------------------------------------------------------- 1 | finishComment = array('Mailer_Plugin', 'requestService'); 27 | Typecho_Plugin::factory('Widget_Comments_Edit')->finishComment = array('Mailer_Plugin', 'requestService'); 28 | Typecho_Plugin::factory('Widget_Service')->sendMail = array('Mailer_Plugin', 'sendMail'); 29 | 30 | // 添加一列,存储是否接受回复提醒 31 | $db = Typecho_Db::get(); 32 | $prefix = $db->getPrefix(); 33 | if (!array_key_exists('receiveMail', $db->fetchRow($db->select()->from('table.comments')))) 34 | $db->query('ALTER TABLE `'. $prefix .'comments` ADD COLUMN `receiveMail` INT(10) DEFAULT 1;'); 35 | 36 | return '请记得进入插件配置相关信息。'; 37 | } 38 | 39 | /** 40 | * 禁用插件方法,如果禁用失败,直接抛出异常 41 | * 42 | * @static 43 | * @access public 44 | * @return void 45 | * @throws Typecho_Plugin_Exception 46 | */ 47 | public static function deactivate(){} 48 | 49 | /** 50 | * 获取插件配置面板 51 | * 52 | * @access public 53 | * @param Typecho_Widget_Helper_Form $form 配置面板 54 | * @return void 55 | */ 56 | public static function config(Typecho_Widget_Helper_Form $form) 57 | { 58 | $form->addInput(new Typecho_Widget_Helper_Form_Element_Text('host', NULL, '', '邮件服务器')); 59 | $form->addInput(new Typecho_Widget_Helper_Form_Element_Select('port', array(25 => 25, 465 => 465, 587 => 587, 2525 => 2525), 587, '端口号')); 60 | $form->addInput(new Typecho_Widget_Helper_Form_Element_Select('secure', array('tls' => 'tls', 'ssl' => 'ssl'), 'ssl', '连接加密方式')); 61 | $form->addInput(new Typecho_Widget_Helper_Form_Element_Radio('auth', array(1 => '是', 0 => '否'), 0, '启用身份验证')); 62 | $form->addInput(new Typecho_Widget_Helper_Form_Element_Text('user', NULL, '', '用户名', '启用身份验证后有效')); 63 | $form->addInput(new Typecho_Widget_Helper_Form_Element_Text('password', NULL, '', '密码', '启用身份验证后有效')); 64 | $form->addInput(new Typecho_Widget_Helper_Form_Element_Text('from', NULL, '', '发送人邮箱')); 65 | $form->addInput(new Typecho_Widget_Helper_Form_Element_Radio('notifyBlogger', array(1 => '是', 0 => '否'), 1, '提醒博主', '是否提醒博主。')); 66 | $form->addInput(new Typecho_Widget_Helper_Form_Element_Radio('notifyGuest', array(1 => '是', 0 => '否'), 1, '提醒访客', '是否提醒访客(可以的话)。')); 67 | $form->addInput(new Typecho_Widget_Helper_Form_Element_Radio('synchronizedSend', array(0 => '否', 1 => '是'), 0, '强制同步发送', '强制不使用异步发送。如果频繁出现丢信的情况,可以打开这个选项。一般不用开启。')); 68 | $form->addInput(new Typecho_Widget_Helper_Form_Element_Textarea('templateHost', NULL, file_get_contents(__DIR__.'/templateHost.html'), '向博主发信内容模板。', '模板中可以使用某些变量,变量需要使用 {{}} 括起来。 69 | 可用的变量有:post_title,post_permalink,post_author_name,post_author_mail,comment_content,comment_permalink,comment_author_name,comment_author_mail,comment_parent_content,comment_parent_author_name,comment_parent_author_mail,status,ip,site_url,site_name,manage_url')); 70 | $form->addInput(new Typecho_Widget_Helper_Form_Element_Textarea('templateGuest', NULL, file_get_contents(__DIR__.'/templateGuest.html'), '向访客发信内容模板。', '模板中可以使用某些变量,变量需要使用 {{}} 括起来。 71 | 可用的变量有:post_title,post_permalink,post_author_name,post_author_mail,comment_content,comment_permalink,comment_author_name,comment_author_mail,comment_parent_content,comment_parent_author_name,comment_parent_author_mail,status,ip,site_url,site_name,manage_url')); 72 | } 73 | 74 | /** 75 | * 个人用户的配置面板 76 | * 77 | * @access public 78 | * @param Typecho_Widget_Helper_Form $form 79 | * @return void 80 | */ 81 | public static function personalConfig(Typecho_Widget_Helper_Form $form){} 82 | 83 | /** 84 | * 检查参数 85 | * 86 | * @param array $settings 87 | * @return string 88 | */ 89 | public static function configCheck(array $settings) 90 | { 91 | if (!empty($settings['host'])) { 92 | $smtp = new SMTP; 93 | $smtp->setTimeout(10); 94 | 95 | if (!$smtp->connect($settings['host'], $settings['port'])) { 96 | return '邮件服务器连接失败'; 97 | } 98 | 99 | if (!$smtp->hello(gethostname())) { 100 | return '向邮件服务器发送指令失败'; 101 | } 102 | 103 | $e = $smtp->getServerExtList(); 104 | 105 | if (is_array($e) && array_key_exists('STARTTLS', $e)) { 106 | if ($settings['secure'] != 'tls') { 107 | return '邮件服务器要求使用TLS加密'; 108 | } 109 | 110 | $tls = $smtp->startTLS(); 111 | 112 | if (!$tls) { 113 | return '无法用TLS连接邮件服务器'; 114 | } 115 | 116 | if (!$smtp->hello(gethostname())) { 117 | return '向邮件服务器发送指令失败'; 118 | } 119 | 120 | $e = $smtp->getServerExtList(); 121 | } 122 | 123 | if (is_array($e) && array_key_exists('AUTH', $e)) { 124 | if (!$settings['auth']) { 125 | return '邮件服务器要求启用身份验证'; 126 | } 127 | 128 | if (!$smtp->authenticate($settings['user'], $settings['password'])) { 129 | return '身份验证失败, 请检查您的用户名或者密码'; 130 | } 131 | } 132 | } 133 | } 134 | 135 | /** 136 | * 异步回调 137 | * 138 | * @access public 139 | * @param int $commentId 评论id 140 | * @return void 141 | */ 142 | public static function sendMail($commentId) 143 | { 144 | $options = Helper::options(); 145 | $pluginOptions = $options->plugin('Mailer'); 146 | 147 | if (empty($pluginOptions->host)) { 148 | return; 149 | } 150 | 151 | $commentObj = self::widgetById('comments', $commentId); 152 | $parentCommentObj = ''; 153 | if($commentObj->parent) { 154 | $parentCommentObj = self::widgetById('comments', $commentObj->parent); 155 | } 156 | $postObj = self::widgetById('contents', $commentObj->cid); 157 | 158 | if (!$commentObj->have()) { 159 | return; 160 | } 161 | 162 | $stausArr = array('approved' => '已通过', 163 | 'waiting' => '待审', 164 | 'spam' => '垃圾评论'); 165 | 166 | // 向博主发信。若评论发起者为博主,不用发信 167 | if ($pluginOptions->notifyBlogger && $commentObj->authorId != $postObj->authorId) { 168 | $mailTo = $postObj->author->mail; 169 | $name = $postObj->author->screenName; 170 | $subject = '《'.$postObj->title.'》一文有新评论啦!'; 171 | $body = str_replace( 172 | array('{{post_title}}', '{{post_permalink}}', '{{post_author_name}}', '{{post_author_mail}}', 173 | '{{comment_content}}', '{{comment_permalink}}', '{{comment_author_name}}', '{{comment_author_mail}}', 174 | '{{status}}', '{{ip}}', 175 | '{{site_name}}', '{{site_url}}', '{{manage_url}}'), 176 | array($postObj->title, $postObj->permalink, $postObj->author->screenName, $postObj->author->mail, 177 | $commentObj->text, $commentObj->permalink, $commentObj->author, $commentObj->mail, 178 | $stausArr[$commentObj->status], $commentObj->ip, 179 | $options->title, $options->siteUrl, $options->adminUrl.'manage-comments.php'), 180 | $pluginOptions->templateHost); 181 | if (!empty($parentCommentObj)) { 182 | $body = str_replace( 183 | array('{{comment_parent_content}}', '{{comment_parent_author_name}}', '{{comment_parent_author_mail}}'), 184 | array($parentCommentObj->text, $parentCommentObj->author->name, $parentCommentObj->mail), 185 | $body 186 | ); 187 | } else { 188 | $body = str_replace( 189 | array('{{comment_parent_content}}', '{{comment_parent_author_name}}', '{{comment_parent_author_mail}}'), 190 | array('', '', ''), 191 | $body 192 | ); 193 | } 194 | 195 | self::send($mailTo, $name, $subject, $body); 196 | } 197 | 198 | // 向回复对象发信 199 | if ($pluginOptions->notifyGuest) { 200 | if (empty($parentCommentObj) || empty($parentCommentObj->mail)) return; 201 | if ($parentCommentObj->authorId == $postObj->authorId) return; // 回复对象是博主,不要再次发信 202 | if ($parentCommentObj->mail == $commentObj->mail) return; // 自己回复自己,不用提醒 203 | if ($commentObj->status != 'approved') return; // 只提醒过审评论 204 | 205 | $db = Typecho_Db::get(); 206 | $row = $db->fetchRow($db->select('receiveMail') 207 | ->from('table.comments') 208 | ->where('coid = ?', $parentCommentObj->coid)); 209 | if (!$row['receiveMail']) return; // 拒绝接收提醒 210 | 211 | $mailTo = $parentCommentObj->mail; 212 | $name = $parentCommentObj->author; 213 | $subject = '您在《'.$postObj->title.'》一文的评论有新回复啦!'; 214 | $body = str_replace( 215 | array('{{post_title}}', '{{post_permalink}}', '{{post_author_name}}', '{{post_author_mail}}', 216 | '{{comment_content}}', '{{comment_permalink}}', '{{comment_author_name}}', '{{comment_author_mail}}', 217 | '{{comment_parent_content}}', '{{comment_parent_author_name}}', '{{comment_parent_author_mail}}', 218 | '{{status}}', '{{ip}}', 219 | '{{site_name}}', '{{site_url}}', '{{manage_url}}'), 220 | array($postObj->title, $postObj->permalink, $postObj->author->screenName, $postObj->author->mail, 221 | $commentObj->text, $commentObj->permalink, $commentObj->author, $commentObj->mail, 222 | $parentCommentObj->text, $parentCommentObj->author, $parentCommentObj->mail, 223 | $stausArr[$commentObj->status], $commentObj->ip, 224 | $options->title, $options->siteUrl, $options->adminUrl.'manage-comments.php'), 225 | $pluginOptions->templateGuest); 226 | 227 | self::send($mailTo, $name, $subject, $body); 228 | } 229 | } 230 | 231 | /** 232 | * 发信 233 | * 234 | * @access public 235 | * @param string $addr 收件地址 236 | * @param string $name 收件人名称 237 | * @param string $subject 邮件标题 238 | * @param string $body 邮件正文 239 | * @return void 240 | */ 241 | public static function send($addr, $name, $subject, $body) { 242 | $options = Helper::options(); 243 | $pluginOptions = $options->plugin('Mailer'); 244 | 245 | $mail = new PHPMailer(false); 246 | $mail->isSMTP(); 247 | $mail->isHTML(true); 248 | $mail->Host = $pluginOptions->host; 249 | $mail->SMTPAuth = !!$pluginOptions->auth; 250 | $mail->Username = $pluginOptions->user; 251 | $mail->Password = $pluginOptions->password; 252 | $mail->SMTPSecure = $pluginOptions->secure; 253 | $mail->Port = $pluginOptions->port; 254 | $mail->getSMTPInstance()->setTimeout(10); 255 | $mail->CharSet = 'utf-8'; 256 | $mail->setFrom($pluginOptions->from, $options->title); 257 | $mail->Subject = $subject; 258 | $mail->Body = $body; 259 | $mail->addAddress($addr, $name); 260 | 261 | $mail->send(); 262 | } 263 | 264 | /** 265 | * 评论回调,调起异步服务 266 | * 267 | * @param $comment 268 | */ 269 | public static function requestService($comment) 270 | { 271 | if ($comment instanceof Widget_Feedback) { 272 | $r = 0; 273 | // 当前评论是否接受回复提醒 274 | if (isset($_POST['receiveMail']) && 'yes' == $_POST['receiveMail']) { 275 | $r = 1; 276 | } 277 | $db = Typecho_Db::get(); 278 | $prefix = $db->getPrefix(); 279 | $db->query($db->update('table.comments') 280 | ->rows(array('receiveMail' => (int)$r)) 281 | ->where('coid = ?', $comment->coid)); 282 | } 283 | 284 | $options = Helper::options(); 285 | $pluginOptions = $options->plugin('Mailer'); 286 | 287 | if ($pluginOptions->synchronizedSend) { 288 | self::sendMail($comment->coid); 289 | } else { 290 | Helper::requestService('sendMail', $comment->coid); 291 | } 292 | } 293 | 294 | /** 295 | * 根据ID获取单个Widget对象 296 | * 297 | * @param string $table 表名, 支持 contents, comments, metas, users 298 | * @return Widget_Abstract 299 | */ 300 | public static function widgetById($table, $pkId) 301 | { 302 | $table = ucfirst($table); 303 | if (!in_array($table, array('Contents', 'Comments', 'Metas', 'Users'))) { 304 | return NULL; 305 | } 306 | 307 | $keys = array( 308 | 'Contents' => 'cid', 309 | 'Comments' => 'coid', 310 | 'Metas' => 'mid', 311 | 'Users' => 'uid' 312 | ); 313 | 314 | $className = "Widget_Abstract_{$table}"; 315 | $key = $keys[$table]; 316 | $db = Typecho_Db::get(); 317 | $widget = new $className(Typecho_Request::getInstance(), Typecho_Widget_Helper_Empty::getInstance()); 318 | 319 | $db->fetchRow( 320 | $widget->select()->where("{$key} = ?", $pkId)->limit(1), 321 | array($widget, 'push')); 322 | 323 | return $widget; 324 | } 325 | } 326 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Typecho Mailer Plugin 2 | 3 | > 📧 又一款评论邮件提醒插件。 4 | 5 | 本插件需要使用 Typecho 开发版(17.11.15 以上版本)。插件支持自定义模板。使用 Typecho 最新的异步回调机制编写,基于 Joyqi 给出的 [Demo](https://joyqi.com/typecho/typecho-async-service.html)。 6 | 7 | 发信规则如下: 8 | 9 | | 评论者 | 被评论对象 | 发信规则 | 10 | | :----: | :------------: | :----------------: | 11 | | 博主 | 文章 | 不发信 | 12 | | 博主 | 博主 | 不发信 | 13 | | 博主 | 访客 | 提醒访客 | 14 | | 访客 | 文章 | 提醒博主 | 15 | | 访客 | 博主 | 提醒博主 | 16 | | 访客 | 访客(本人) | 提醒博主 | 17 | | 访客 | 访客(非本人) | 提醒评论对象与博主 | 18 | 19 | 也可以单独设置是否提醒博主或者访客。待审或垃圾评论不会提醒访客。 20 | 21 | ## 使用 22 | 23 | 下载插件,上传至插件目录,后台启用后设置相关信息。然后在博客评论区 `form` 元素中合适位置添加: 24 | 25 | ```html 26 | 27 | 28 | 29 | 30 | ``` 31 | 32 | 以上代码必须添加,不添加不会发信。VOID 主题开发版已做了处理。 33 | 34 | 然后在插件设置页面填写发件信息。注意,如果你是用的 QQ 之类的邮箱,可能需要生成专用密码,而不能直接使用登陆密码。 35 | 36 | 插件默认提供了一个比较简单的发信模板,如果有好看的模板欢迎在 issue 区分享。模板中可以使用一些变量,见插件设置页说明。 37 | 38 | ## 日志 39 | 40 | **2019.05.25** 41 | 42 | * 修复后台回复不发信的问题(可能需要禁用后重新启用插件) 43 | 44 | ## License 45 | 46 | MIT © [AlanDecode](https://github.com/AlanDecode) -------------------------------------------------------------------------------- /templateGuest.html: -------------------------------------------------------------------------------- 1 |
7 | 8 |

您好,{{comment_parent_author_name}}。

9 | 10 |

您在文章《{{post_title}}》上发表的评论:

11 | 12 |

{{comment_parent_content}}

15 | 16 |

收到了来自 {{comment_author_name}} 的回复:

17 | 18 |

{{comment_content}}

21 | 22 | 31 | 32 |

本邮件为系统自动发送。欢迎再次访问{{site_name}}

33 | 34 |
-------------------------------------------------------------------------------- /templateHost.html: -------------------------------------------------------------------------------- 1 |
7 | 8 |

来自 《{{post_title}}》 的新评论

9 | 10 |

{{comment_content}}

13 | 14 |

15 | 来自:{{comment_author_name}}
16 | IP:{{ip}}
17 | 状态:{{status}}
18 |

19 | 20 |

查看评论 | 管理评论

21 | 22 |
--------------------------------------------------------------------------------