PageRenderTime 53ms CodeModel.GetById 6ms app.highlight 30ms RepoModel.GetById 1ms app.codeStats 1ms

/common/include/mailer/class.phpmailer.php

https://github.com/tematres/TemaTres-Vocabulary-Server
PHP | 3690 lines | 2178 code | 232 blank | 1280 comment | 355 complexity | 8478e9afa002a4f95d653628a75feca9 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1<?php
   2/**
   3 * PHPMailer - PHP email creation and transport class.
   4 * PHP Version 5
   5 * @package PHPMailer
   6 * @link https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
   7 * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
   8 * @author Jim Jagielski (jimjag) <jimjag@gmail.com>
   9 * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
  10 * @author Brent R. Matzelle (original founder)
  11 * @copyright 2012 - 2014 Marcus Bointon
  12 * @copyright 2010 - 2012 Jim Jagielski
  13 * @copyright 2004 - 2009 Andy Prevost
  14 * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
  15 * @note This program is distributed in the hope that it will be useful - WITHOUT
  16 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  17 * FITNESS FOR A PARTICULAR PURPOSE.
  18 */
  19
  20/**
  21 * PHPMailer - PHP email creation and transport class.
  22 * @package PHPMailer
  23 * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
  24 * @author Jim Jagielski (jimjag) <jimjag@gmail.com>
  25 * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
  26 * @author Brent R. Matzelle (original founder)
  27 */
  28class PHPMailer
  29{
  30    /**
  31     * The PHPMailer Version number.
  32     * @type string
  33     */
  34    public $Version = '5.2.10';
  35
  36    /**
  37     * Email priority.
  38     * Options: null (default), 1 = High, 3 = Normal, 5 = low.
  39     * When null, the header is not set at all.
  40     * @type integer
  41     */
  42    public $Priority = null;
  43
  44    /**
  45     * The character set of the message.
  46     * @type string
  47     */
  48    public $CharSet = 'iso-8859-1';
  49
  50    /**
  51     * The MIME Content-type of the message.
  52     * @type string
  53     */
  54    public $ContentType = 'text/plain';
  55
  56    /**
  57     * The message encoding.
  58     * Options: "8bit", "7bit", "binary", "base64", and "quoted-printable".
  59     * @type string
  60     */
  61    public $Encoding = '8bit';
  62
  63    /**
  64     * Holds the most recent mailer error message.
  65     * @type string
  66     */
  67    public $ErrorInfo = '';
  68
  69    /**
  70     * The From email address for the message.
  71     * @type string
  72     */
  73    public $From = 'root@localhost';
  74
  75    /**
  76     * The From name of the message.
  77     * @type string
  78     */
  79    public $FromName = 'Root User';
  80
  81    /**
  82     * The Sender email (Return-Path) of the message.
  83     * If not empty, will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode.
  84     * @type string
  85     */
  86    public $Sender = '';
  87
  88    /**
  89     * The Return-Path of the message.
  90     * If empty, it will be set to either From or Sender.
  91     * @type string
  92     * @deprecated Email senders should never set a return-path header;
  93     * it's the receiver's job (RFC5321 section 4.4), so this no longer does anything.
  94     * @link https://tools.ietf.org/html/rfc5321#section-4.4 RFC5321 reference
  95     */
  96    public $ReturnPath = '';
  97
  98    /**
  99     * The Subject of the message.
 100     * @type string
 101     */
 102    public $Subject = '';
 103
 104    /**
 105     * An HTML or plain text message body.
 106     * If HTML then call isHTML(true).
 107     * @type string
 108     */
 109    public $Body = '';
 110
 111    /**
 112     * The plain-text message body.
 113     * This body can be read by mail clients that do not have HTML email
 114     * capability such as mutt & Eudora.
 115     * Clients that can read HTML will view the normal Body.
 116     * @type string
 117     */
 118    public $AltBody = '';
 119
 120    /**
 121     * An iCal message part body.
 122     * Only supported in simple alt or alt_inline message types
 123     * To generate iCal events, use the bundled extras/EasyPeasyICS.php class or iCalcreator
 124     * @link http://sprain.ch/blog/downloads/php-class-easypeasyics-create-ical-files-with-php/
 125     * @link http://kigkonsult.se/iCalcreator/
 126     * @type string
 127     */
 128    public $Ical = '';
 129
 130    /**
 131     * The complete compiled MIME message body.
 132     * @access protected
 133     * @type string
 134     */
 135    protected $MIMEBody = '';
 136
 137    /**
 138     * The complete compiled MIME message headers.
 139     * @type string
 140     * @access protected
 141     */
 142    protected $MIMEHeader = '';
 143
 144    /**
 145     * Extra headers that createHeader() doesn't fold in.
 146     * @type string
 147     * @access protected
 148     */
 149    protected $mailHeader = '';
 150
 151    /**
 152     * Word-wrap the message body to this number of chars.
 153     * Set to 0 to not wrap. A useful value here is 78, for RFC2822 section 2.1.1 compliance.
 154     * @type integer
 155     */
 156    public $WordWrap = 0;
 157
 158    /**
 159     * Which method to use to send mail.
 160     * Options: "mail", "sendmail", or "smtp".
 161     * @type string
 162     */
 163    public $Mailer = 'mail';
 164
 165    /**
 166     * The path to the sendmail program.
 167     * @type string
 168     */
 169    public $Sendmail = '/usr/sbin/sendmail';
 170
 171    /**
 172     * Whether mail() uses a fully sendmail-compatible MTA.
 173     * One which supports sendmail's "-oi -f" options.
 174     * @type boolean
 175     */
 176    public $UseSendmailOptions = true;
 177
 178    /**
 179     * Path to PHPMailer plugins.
 180     * Useful if the SMTP class is not in the PHP include path.
 181     * @type string
 182     * @deprecated Should not be needed now there is an autoloader.
 183     */
 184    public $PluginDir = '';
 185
 186    /**
 187     * The email address that a reading confirmation should be sent to.
 188     * @type string
 189     */
 190    public $ConfirmReadingTo = '';
 191
 192    /**
 193     * The hostname to use in Message-Id and Received headers
 194     * and as default HELO string.
 195     * If empty, the value returned
 196     * by SERVER_NAME is used or 'localhost.localdomain'.
 197     * @type string
 198     */
 199    public $Hostname = '';
 200
 201    /**
 202     * An ID to be used in the Message-Id header.
 203     * If empty, a unique id will be generated.
 204     * @type string
 205     */
 206    public $MessageID = '';
 207
 208    /**
 209     * The message Date to be used in the Date header.
 210     * If empty, the current date will be added.
 211     * @type string
 212     */
 213    public $MessageDate = '';
 214
 215    /**
 216     * SMTP hosts.
 217     * Either a single hostname or multiple semicolon-delimited hostnames.
 218     * You can also specify a different port
 219     * for each host by using this format: [hostname:port]
 220     * (e.g. "smtp1.example.com:25;smtp2.example.com").
 221     * You can also specify encryption type, for example:
 222     * (e.g. "tls://smtp1.example.com:587;ssl://smtp2.example.com:465").
 223     * Hosts will be tried in order.
 224     * @type string
 225     */
 226    public $Host = 'localhost';
 227
 228    /**
 229     * The default SMTP server port.
 230     * @type integer
 231     * @TODO Why is this needed when the SMTP class takes care of it?
 232     */
 233    public $Port = 25;
 234
 235    /**
 236     * The SMTP HELO of the message.
 237     * Default is $Hostname.
 238     * @type string
 239     * @see PHPMailer::$Hostname
 240     */
 241    public $Helo = '';
 242
 243    /**
 244     * What kind of encryption to use on the SMTP connection.
 245     * Options: '', 'ssl' or 'tls'
 246     * @type string
 247     */
 248    public $SMTPSecure = '';
 249
 250    /**
 251     * Whether to enable TLS encryption automatically if a server supports it,
 252     * even if `SMTPSecure` is not set to 'tls'.
 253     * Be aware that in PHP >= 5.6 this requires that the server's certificates are valid.
 254     * @type boolean
 255     */
 256    public $SMTPAutoTLS = true;
 257
 258    /**
 259     * Whether to use SMTP authentication.
 260     * Uses the Username and Password properties.
 261     * @type boolean
 262     * @see PHPMailer::$Username
 263     * @see PHPMailer::$Password
 264     */
 265    public $SMTPAuth = false;
 266
 267    /**
 268     * Options array passed to stream_context_create when connecting via SMTP.
 269     * @type array
 270     */
 271    public $SMTPOptions = array();
 272
 273    /**
 274     * SMTP username.
 275     * @type string
 276     */
 277    public $Username = '';
 278
 279    /**
 280     * SMTP password.
 281     * @type string
 282     */
 283    public $Password = '';
 284
 285    /**
 286     * SMTP auth type.
 287     * Options are LOGIN (default), PLAIN, NTLM, CRAM-MD5
 288     * @type string
 289     */
 290    public $AuthType = '';
 291
 292    /**
 293     * SMTP realm.
 294     * Used for NTLM auth
 295     * @type string
 296     */
 297    public $Realm = '';
 298
 299    /**
 300     * SMTP workstation.
 301     * Used for NTLM auth
 302     * @type string
 303     */
 304    public $Workstation = '';
 305
 306    /**
 307     * The SMTP server timeout in seconds.
 308     * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2
 309     * @type integer
 310     */
 311    public $Timeout = 300;
 312
 313    /**
 314     * SMTP class debug output mode.
 315     * Debug output level.
 316     * Options:
 317     * * `0` No output
 318     * * `1` Commands
 319     * * `2` Data and commands
 320     * * `3` As 2 plus connection status
 321     * * `4` Low-level data output
 322     * @type integer
 323     * @see SMTP::$do_debug
 324     */
 325    public $SMTPDebug = 0;
 326
 327    /**
 328     * How to handle debug output.
 329     * Options:
 330     * * `echo` Output plain-text as-is, appropriate for CLI
 331     * * `html` Output escaped, line breaks converted to `<br>`, appropriate for browser output
 332     * * `error_log` Output to error log as configured in php.ini
 333     *
 334     * Alternatively, you can provide a callable expecting two params: a message string and the debug level:
 335     * <code>
 336     * $mail->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";};
 337     * </code>
 338     * @type string|callable
 339     * @see SMTP::$Debugoutput
 340     */
 341    public $Debugoutput = 'echo';
 342
 343    /**
 344     * Whether to keep SMTP connection open after each message.
 345     * If this is set to true then to close the connection
 346     * requires an explicit call to smtpClose().
 347     * @type boolean
 348     */
 349    public $SMTPKeepAlive = false;
 350
 351    /**
 352     * Whether to split multiple to addresses into multiple messages
 353     * or send them all in one message.
 354     * @type boolean
 355     */
 356    public $SingleTo = false;
 357
 358    /**
 359     * Storage for addresses when SingleTo is enabled.
 360     * @type array
 361     * @TODO This should really not be public
 362     */
 363    public $SingleToArray = array();
 364
 365    /**
 366     * Whether to generate VERP addresses on send.
 367     * Only applicable when sending via SMTP.
 368     * @link http://en.wikipedia.org/wiki/Variable_envelope_return_path
 369     * @link http://www.postfix.org/VERP_README.html Postfix VERP info
 370     * @type boolean
 371     */
 372    public $do_verp = false;
 373
 374    /**
 375     * Whether to allow sending messages with an empty body.
 376     * @type boolean
 377     */
 378    public $AllowEmpty = false;
 379
 380    /**
 381     * The default line ending.
 382     * @note The default remains "\n". We force CRLF where we know
 383     *        it must be used via self::CRLF.
 384     * @type string
 385     */
 386    public $LE = "\n";
 387
 388    /**
 389     * DKIM selector.
 390     * @type string
 391     */
 392    public $DKIM_selector = '';
 393
 394    /**
 395     * DKIM Identity.
 396     * Usually the email address used as the source of the email
 397     * @type string
 398     */
 399    public $DKIM_identity = '';
 400
 401    /**
 402     * DKIM passphrase.
 403     * Used if your key is encrypted.
 404     * @type string
 405     */
 406    public $DKIM_passphrase = '';
 407
 408    /**
 409     * DKIM signing domain name.
 410     * @example 'example.com'
 411     * @type string
 412     */
 413    public $DKIM_domain = '';
 414
 415    /**
 416     * DKIM private key file path.
 417     * @type string
 418     */
 419    public $DKIM_private = '';
 420
 421    /**
 422     * Callback Action function name.
 423     *
 424     * The function that handles the result of the send email action.
 425     * It is called out by send() for each email sent.
 426     *
 427     * Value can be any php callable: http://www.php.net/is_callable
 428     *
 429     * Parameters:
 430     *   boolean $result        result of the send action
 431     *   string  $to            email address of the recipient
 432     *   string  $cc            cc email addresses
 433     *   string  $bcc           bcc email addresses
 434     *   string  $subject       the subject
 435     *   string  $body          the email body
 436     *   string  $from          email address of sender
 437     * @type string
 438     */
 439    public $action_function = '';
 440
 441    /**
 442     * What to put in the X-Mailer header.
 443     * Options: An empty string for PHPMailer default, whitespace for none, or a string to use
 444     * @type string
 445     */
 446    public $XMailer = '';
 447
 448    /**
 449     * An instance of the SMTP sender class.
 450     * @type SMTP
 451     * @access protected
 452     */
 453    protected $smtp = null;
 454
 455    /**
 456     * The array of 'to' addresses.
 457     * @type array
 458     * @access protected
 459     */
 460    protected $to = array();
 461
 462    /**
 463     * The array of 'cc' addresses.
 464     * @type array
 465     * @access protected
 466     */
 467    protected $cc = array();
 468
 469    /**
 470     * The array of 'bcc' addresses.
 471     * @type array
 472     * @access protected
 473     */
 474    protected $bcc = array();
 475
 476    /**
 477     * The array of reply-to names and addresses.
 478     * @type array
 479     * @access protected
 480     */
 481    protected $ReplyTo = array();
 482
 483    /**
 484     * An array of all kinds of addresses.
 485     * Includes all of $to, $cc, $bcc
 486     * @type array
 487     * @access protected
 488     */
 489    protected $all_recipients = array();
 490
 491    /**
 492     * The array of attachments.
 493     * @type array
 494     * @access protected
 495     */
 496    protected $attachment = array();
 497
 498    /**
 499     * The array of custom headers.
 500     * @type array
 501     * @access protected
 502     */
 503    protected $CustomHeader = array();
 504
 505    /**
 506     * The most recent Message-ID (including angular brackets).
 507     * @type string
 508     * @access protected
 509     */
 510    protected $lastMessageID = '';
 511
 512    /**
 513     * The message's MIME type.
 514     * @type string
 515     * @access protected
 516     */
 517    protected $message_type = '';
 518
 519    /**
 520     * The array of MIME boundary strings.
 521     * @type array
 522     * @access protected
 523     */
 524    protected $boundary = array();
 525
 526    /**
 527     * The array of available languages.
 528     * @type array
 529     * @access protected
 530     */
 531    protected $language = array();
 532
 533    /**
 534     * The number of errors encountered.
 535     * @type integer
 536     * @access protected
 537     */
 538    protected $error_count = 0;
 539
 540    /**
 541     * The S/MIME certificate file path.
 542     * @type string
 543     * @access protected
 544     */
 545    protected $sign_cert_file = '';
 546
 547    /**
 548     * The S/MIME key file path.
 549     * @type string
 550     * @access protected
 551     */
 552    protected $sign_key_file = '';
 553
 554    /**
 555     * The optional S/MIME extra certificates ("CA Chain") file path.
 556     * @type string
 557     * @access protected
 558     */
 559    protected $sign_extracerts_file = '';
 560
 561    /**
 562     * The S/MIME password for the key.
 563     * Used only if the key is encrypted.
 564     * @type string
 565     * @access protected
 566     */
 567    protected $sign_key_pass = '';
 568
 569    /**
 570     * Whether to throw exceptions for errors.
 571     * @type boolean
 572     * @access protected
 573     */
 574    protected $exceptions = false;
 575
 576    /**
 577     * Unique ID used for message ID and boundaries.
 578     * @type string
 579     * @access protected
 580     */
 581    protected $uniqueid = '';
 582
 583    /**
 584     * Error severity: message only, continue processing.
 585     */
 586    const STOP_MESSAGE = 0;
 587
 588    /**
 589     * Error severity: message, likely ok to continue processing.
 590     */
 591    const STOP_CONTINUE = 1;
 592
 593    /**
 594     * Error severity: message, plus full stop, critical error reached.
 595     */
 596    const STOP_CRITICAL = 2;
 597
 598    /**
 599     * SMTP RFC standard line ending.
 600     */
 601    const CRLF = "\r\n";
 602
 603    /**
 604     * The maximum line length allowed by RFC 2822 section 2.1.1
 605     * @type integer
 606     */
 607    const MAX_LINE_LENGTH = 998;
 608
 609    /**
 610     * Constructor.
 611     * @param boolean $exceptions Should we throw external exceptions?
 612     */
 613    public function __construct($exceptions = false)
 614    {
 615        $this->exceptions = (boolean)$exceptions;
 616    }
 617
 618    /**
 619     * Destructor.
 620     */
 621    public function __destruct()
 622    {
 623        //Close any open SMTP connection nicely
 624        if ($this->Mailer == 'smtp') {
 625            $this->smtpClose();
 626        }
 627    }
 628
 629    /**
 630     * Call mail() in a safe_mode-aware fashion.
 631     * Also, unless sendmail_path points to sendmail (or something that
 632     * claims to be sendmail), don't pass params (not a perfect fix,
 633     * but it will do)
 634     * @param string $to To
 635     * @param string $subject Subject
 636     * @param string $body Message Body
 637     * @param string $header Additional Header(s)
 638     * @param string $params Params
 639     * @access private
 640     * @return boolean
 641     */
 642    private function mailPassthru($to, $subject, $body, $header, $params)
 643    {
 644        //Check overloading of mail function to avoid double-encoding
 645        if (ini_get('mbstring.func_overload') & 1) {
 646            $subject = $this->secureHeader($subject);
 647        } else {
 648            $subject = $this->encodeHeader($this->secureHeader($subject));
 649        }
 650        if (ini_get('safe_mode') || !($this->UseSendmailOptions)) {
 651            $result = @mail($to, $subject, $body, $header);
 652        } else {
 653            $result = @mail($to, $subject, $body, $header, $params);
 654        }
 655        return $result;
 656    }
 657
 658    /**
 659     * Output debugging info via user-defined method.
 660     * Only generates output if SMTP debug output is enabled (@see SMTP::$do_debug).
 661     * @see PHPMailer::$Debugoutput
 662     * @see PHPMailer::$SMTPDebug
 663     * @param string $str
 664     */
 665    protected function edebug($str)
 666    {
 667        if ($this->SMTPDebug <= 0) {
 668            return;
 669        }
 670        //Avoid clash with built-in function names
 671        if (!in_array($this->Debugoutput, array('error_log', 'html', 'echo')) and is_callable($this->Debugoutput)) {
 672            call_user_func($this->Debugoutput, $str, $this->SMTPDebug);
 673            return;
 674        }
 675        switch ($this->Debugoutput) {
 676            case 'error_log':
 677                //Don't output, just log
 678                error_log($str);
 679                break;
 680            case 'html':
 681                //Cleans up output a bit for a better looking, HTML-safe output
 682                echo htmlentities(
 683                    preg_replace('/[\r\n]+/', '', $str),
 684                    ENT_QUOTES,
 685                    'UTF-8'
 686                )
 687                . "<br>\n";
 688                break;
 689            case 'echo':
 690            default:
 691                //Normalize line breaks
 692                $str = preg_replace('/(\r\n|\r|\n)/ms', "\n", $str);
 693                echo gmdate('Y-m-d H:i:s') . "\t" . str_replace(
 694                    "\n",
 695                    "\n                   \t                  ",
 696                    trim($str)
 697                ) . "\n";
 698        }
 699    }
 700
 701    /**
 702     * Sets message type to HTML or plain.
 703     * @param boolean $isHtml True for HTML mode.
 704     * @return void
 705     */
 706    public function isHTML($isHtml = true)
 707    {
 708        if ($isHtml) {
 709            $this->ContentType = 'text/html';
 710        } else {
 711            $this->ContentType = 'text/plain';
 712        }
 713    }
 714
 715    /**
 716     * Send messages using SMTP.
 717     * @return void
 718     */
 719    public function isSMTP()
 720    {
 721        $this->Mailer = 'smtp';
 722    }
 723
 724    /**
 725     * Send messages using PHP's mail() function.
 726     * @return void
 727     */
 728    public function isMail()
 729    {
 730        $this->Mailer = 'mail';
 731    }
 732
 733    /**
 734     * Send messages using $Sendmail.
 735     * @return void
 736     */
 737    public function isSendmail()
 738    {
 739        $ini_sendmail_path = ini_get('sendmail_path');
 740
 741        if (!stristr($ini_sendmail_path, 'sendmail')) {
 742            $this->Sendmail = '/usr/sbin/sendmail';
 743        } else {
 744            $this->Sendmail = $ini_sendmail_path;
 745        }
 746        $this->Mailer = 'sendmail';
 747    }
 748
 749    /**
 750     * Send messages using qmail.
 751     * @return void
 752     */
 753    public function isQmail()
 754    {
 755        $ini_sendmail_path = ini_get('sendmail_path');
 756
 757        if (!stristr($ini_sendmail_path, 'qmail')) {
 758            $this->Sendmail = '/var/qmail/bin/qmail-inject';
 759        } else {
 760            $this->Sendmail = $ini_sendmail_path;
 761        }
 762        $this->Mailer = 'qmail';
 763    }
 764
 765    /**
 766     * Add a "To" address.
 767     * @param string $address
 768     * @param string $name
 769     * @return boolean true on success, false if address already used
 770     */
 771    public function addAddress($address, $name = '')
 772    {
 773        return $this->addAnAddress('to', $address, $name);
 774    }
 775
 776    /**
 777     * Add a "CC" address.
 778     * @note: This function works with the SMTP mailer on win32, not with the "mail" mailer.
 779     * @param string $address
 780     * @param string $name
 781     * @return boolean true on success, false if address already used
 782     */
 783    public function addCC($address, $name = '')
 784    {
 785        return $this->addAnAddress('cc', $address, $name);
 786    }
 787
 788    /**
 789     * Add a "BCC" address.
 790     * @note: This function works with the SMTP mailer on win32, not with the "mail" mailer.
 791     * @param string $address
 792     * @param string $name
 793     * @return boolean true on success, false if address already used
 794     */
 795    public function addBCC($address, $name = '')
 796    {
 797        return $this->addAnAddress('bcc', $address, $name);
 798    }
 799
 800    /**
 801     * Add a "Reply-to" address.
 802     * @param string $address
 803     * @param string $name
 804     * @return boolean
 805     */
 806    public function addReplyTo($address, $name = '')
 807    {
 808        return $this->addAnAddress('Reply-To', $address, $name);
 809    }
 810
 811    /**
 812     * Add an address to one of the recipient arrays.
 813     * Addresses that have been added already return false, but do not throw exceptions
 814     * @param string $kind One of 'to', 'cc', 'bcc', 'ReplyTo'
 815     * @param string $address The email address to send to
 816     * @param string $name
 817     * @throws phpmailerException
 818     * @return boolean true on success, false if address already used or invalid in some way
 819     * @access protected
 820     */
 821    protected function addAnAddress($kind, $address, $name = '')
 822    {
 823        if (!preg_match('/^(to|cc|bcc|Reply-To)$/', $kind)) {
 824            $this->setError($this->lang('Invalid recipient array') . ': ' . $kind);
 825            $this->edebug($this->lang('Invalid recipient array') . ': ' . $kind);
 826            if ($this->exceptions) {
 827                throw new phpmailerException('Invalid recipient array: ' . $kind);
 828            }
 829            return false;
 830        }
 831        $address = trim($address);
 832        $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
 833        if (!$this->validateAddress($address)) {
 834            $this->setError($this->lang('invalid_address') . ': ' . $address);
 835            $this->edebug($this->lang('invalid_address') . ': ' . $address);
 836            if ($this->exceptions) {
 837                throw new phpmailerException($this->lang('invalid_address') . ': ' . $address);
 838            }
 839            return false;
 840        }
 841        if ($kind != 'Reply-To') {
 842            if (!isset($this->all_recipients[strtolower($address)])) {
 843                array_push($this->$kind, array($address, $name));
 844                $this->all_recipients[strtolower($address)] = true;
 845                return true;
 846            }
 847        } else {
 848            if (!array_key_exists(strtolower($address), $this->ReplyTo)) {
 849                $this->ReplyTo[strtolower($address)] = array($address, $name);
 850                return true;
 851            }
 852        }
 853        return false;
 854    }
 855
 856    /**
 857     * Parse and validate a string containing one or more RFC822-style comma-separated email addresses
 858     * of the form "display name <address>" into an array of name/address pairs.
 859     * Uses the imap_rfc822_parse_adrlist function if the IMAP extension is available.
 860     * Note that quotes in the name part are removed.
 861     * @param string $addrstr The address list string
 862     * @param bool $useimap Whether to use the IMAP extension to parse the list
 863     * @return array
 864     * @link http://www.andrew.cmu.edu/user/agreen1/testing/mrbs/web/Mail/RFC822.php A more careful implementation
 865     */
 866    public function parseAddresses($addrstr, $useimap = true)
 867    {
 868        $addresses = array();
 869        if ($useimap and function_exists('imap_rfc822_parse_adrlist')) {
 870            //Use this built-in parser if it's available
 871            $list = imap_rfc822_parse_adrlist($addrstr, '');
 872            foreach ($list as $address) {
 873                if ($address->host != '.SYNTAX-ERROR.') {
 874                    if ($this->validateAddress($address->mailbox . '@' . $address->host)) {
 875                        $addresses[] = array(
 876                            'name' => (property_exists($address, 'personal') ? $address->personal : ''),
 877                            'address' => $address->mailbox . '@' . $address->host
 878                        );
 879                    }
 880                }
 881            }
 882        } else {
 883            //Use this simpler parser
 884            $list = explode(',', $addrstr);
 885            foreach ($list as $address) {
 886                $address = trim($address);
 887                //Is there a separate name part?
 888                if (strpos($address, '<') === false) {
 889                    //No separate name, just use the whole thing
 890                    if ($this->validateAddress($address)) {
 891                        $addresses[] = array(
 892                            'name' => '',
 893                            'address' => $address
 894                        );
 895                    }
 896                } else {
 897                    list($name, $email) = explode('<', $address);
 898                    $email = trim(str_replace('>', '', $email));
 899                    if ($this->validateAddress($email)) {
 900                        $addresses[] = array(
 901                            'name' => trim(str_replace(array('"', "'"), '', $name)),
 902                            'address' => $email
 903                        );
 904                    }
 905                }
 906            }
 907        }
 908        return $addresses;
 909    }
 910
 911    /**
 912     * Set the From and FromName properties.
 913     * @param string $address
 914     * @param string $name
 915     * @param boolean $auto Whether to also set the Sender address, defaults to true
 916     * @throws phpmailerException
 917     * @return boolean
 918     */
 919    public function setFrom($address, $name = '', $auto = true)
 920    {
 921        $address = trim($address);
 922        $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
 923        if (!$this->validateAddress($address)) {
 924            $this->setError($this->lang('invalid_address') . ': ' . $address);
 925            $this->edebug($this->lang('invalid_address') . ': ' . $address);
 926            if ($this->exceptions) {
 927                throw new phpmailerException($this->lang('invalid_address') . ': ' . $address);
 928            }
 929            return false;
 930        }
 931        $this->From = $address;
 932        $this->FromName = $name;
 933        if ($auto) {
 934            if (empty($this->Sender)) {
 935                $this->Sender = $address;
 936            }
 937        }
 938        return true;
 939    }
 940
 941    /**
 942     * Return the Message-ID header of the last email.
 943     * Technically this is the value from the last time the headers were created,
 944     * but it's also the message ID of the last sent message except in
 945     * pathological cases.
 946     * @return string
 947     */
 948    public function getLastMessageID()
 949    {
 950        return $this->lastMessageID;
 951    }
 952
 953    /**
 954     * Check that a string looks like an email address.
 955     * @param string $address The email address to check
 956     * @param string $patternselect A selector for the validation pattern to use :
 957     * * `auto` Pick strictest one automatically;
 958     * * `pcre8` Use the squiloople.com pattern, requires PCRE > 8.0, PHP >= 5.3.2, 5.2.14;
 959     * * `pcre` Use old PCRE implementation;
 960     * * `php` Use PHP built-in FILTER_VALIDATE_EMAIL; same as pcre8 but does not allow 'dotless' domains;
 961     * * `html5` Use the pattern given by the HTML5 spec for 'email' type form input elements.
 962     * * `noregex` Don't use a regex: super fast, really dumb.
 963     * @return boolean
 964     * @static
 965     * @access public
 966     */
 967    public static function validateAddress($address, $patternselect = 'auto')
 968    {
 969        if (!$patternselect or $patternselect == 'auto') {
 970            //Check this constant first so it works when extension_loaded() is disabled by safe mode
 971            //Constant was added in PHP 5.2.4
 972            if (defined('PCRE_VERSION')) {
 973                //This pattern can get stuck in a recursive loop in PCRE <= 8.0.2
 974                if (version_compare(PCRE_VERSION, '8.0.3') >= 0) {
 975                    $patternselect = 'pcre8';
 976                } else {
 977                    $patternselect = 'pcre';
 978                }
 979            } elseif (function_exists('extension_loaded') and extension_loaded('pcre')) {
 980                //Fall back to older PCRE
 981                $patternselect = 'pcre';
 982            } else {
 983                //Filter_var appeared in PHP 5.2.0 and does not require the PCRE extension
 984                if (version_compare(PHP_VERSION, '5.2.0') >= 0) {
 985                    $patternselect = 'php';
 986                } else {
 987                    $patternselect = 'noregex';
 988                }
 989            }
 990        }
 991        switch ($patternselect) {
 992            case 'pcre8':
 993                /**
 994                 * Uses the same RFC5322 regex on which FILTER_VALIDATE_EMAIL is based, but allows dotless domains.
 995                 * @link http://squiloople.com/2009/12/20/email-address-validation/
 996                 * @copyright 2009-2010 Michael Rushton
 997                 * Feel free to use and redistribute this code. But please keep this copyright notice.
 998                 */
 999                return (boolean)preg_match(
1000                    '/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)' .
1001                    '((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)' .
1002                    '(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)' .
1003                    '([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*' .
1004                    '(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)' .
1005                    '(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}' .
1006                    '|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:' .
1007                    '|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}' .
1008                    '|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD',
1009                    $address
1010                );
1011            case 'pcre':
1012                //An older regex that doesn't need a recent PCRE
1013                return (boolean)preg_match(
1014                    '/^(?!(?>"?(?>\\\[ -~]|[^"])"?){255,})(?!(?>"?(?>\\\[ -~]|[^"])"?){65,}@)(?>' .
1015                    '[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*")' .
1016                    '(?>\.(?>[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*"))*' .
1017                    '@(?>(?![a-z0-9-]{64,})(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>\.(?![a-z0-9-]{64,})' .
1018                    '(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)){0,126}|\[(?:(?>IPv6:(?>(?>[a-f0-9]{1,4})(?>:' .
1019                    '[a-f0-9]{1,4}){7}|(?!(?:.*[a-f0-9][:\]]){8,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?' .
1020                    '::(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?))|(?>(?>IPv6:(?>[a-f0-9]{1,4}(?>:' .
1021                    '[a-f0-9]{1,4}){5}:|(?!(?:.*[a-f0-9]:){6,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4})?' .
1022                    '::(?>(?:[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4}):)?))?(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}' .
1023                    '|[1-9]?[0-9])(?>\.(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}))\])$/isD',
1024                    $address
1025                );
1026            case 'html5':
1027                /**
1028                 * This is the pattern used in the HTML5 spec for validation of 'email' type form input elements.
1029                 * @link http://www.whatwg.org/specs/web-apps/current-work/#e-mail-state-(type=email)
1030                 */
1031                return (boolean)preg_match(
1032                    '/^[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}' .
1033                    '[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/sD',
1034                    $address
1035                );
1036            case 'noregex':
1037                //No PCRE! Do something _very_ approximate!
1038                //Check the address is 3 chars or longer and contains an @ that's not the first or last char
1039                return (strlen($address) >= 3
1040                    and strpos($address, '@') >= 1
1041                    and strpos($address, '@') != strlen($address) - 1);
1042            case 'php':
1043            default:
1044                return (boolean)filter_var($address, FILTER_VALIDATE_EMAIL);
1045        }
1046    }
1047
1048    /**
1049     * Create a message and send it.
1050     * Uses the sending method specified by $Mailer.
1051     * @throws phpmailerException
1052     * @return boolean false on error - See the ErrorInfo property for details of the error.
1053     */
1054    public function send()
1055    {
1056        try {
1057            if (!$this->preSend()) {
1058                return false;
1059            }
1060            return $this->postSend();
1061        } catch (phpmailerException $exc) {
1062            $this->mailHeader = '';
1063            $this->setError($exc->getMessage());
1064            if ($this->exceptions) {
1065                throw $exc;
1066            }
1067            return false;
1068        }
1069    }
1070
1071    /**
1072     * Prepare a message for sending.
1073     * @throws phpmailerException
1074     * @return boolean
1075     */
1076    public function preSend()
1077    {
1078        try {
1079            $this->mailHeader = '';
1080            if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) {
1081                throw new phpmailerException($this->lang('provide_address'), self::STOP_CRITICAL);
1082            }
1083
1084            // Set whether the message is multipart/alternative
1085            if (!empty($this->AltBody)) {
1086                $this->ContentType = 'multipart/alternative';
1087            }
1088
1089            $this->error_count = 0; // Reset errors
1090            $this->setMessageType();
1091            // Refuse to send an empty message unless we are specifically allowing it
1092            if (!$this->AllowEmpty and empty($this->Body)) {
1093                throw new phpmailerException($this->lang('empty_message'), self::STOP_CRITICAL);
1094            }
1095
1096            // Create body before headers in case body makes changes to headers (e.g. altering transfer encoding)
1097            $this->MIMEHeader = '';
1098            $this->MIMEBody = $this->createBody();
1099            // createBody may have added some headers, so retain them
1100            $tempheaders = $this->MIMEHeader;
1101            $this->MIMEHeader = $this->createHeader();
1102            $this->MIMEHeader .= $tempheaders;
1103
1104            // To capture the complete message when using mail(), create
1105            // an extra header list which createHeader() doesn't fold in
1106            if ($this->Mailer == 'mail') {
1107                if (count($this->to) > 0) {
1108                    $this->mailHeader .= $this->addrAppend('To', $this->to);
1109                } else {
1110                    $this->mailHeader .= $this->headerLine('To', 'undisclosed-recipients:;');
1111                }
1112                $this->mailHeader .= $this->headerLine(
1113                    'Subject',
1114                    $this->encodeHeader($this->secureHeader(trim($this->Subject)))
1115                );
1116            }
1117
1118            // Sign with DKIM if enabled
1119            if (!empty($this->DKIM_domain)
1120                && !empty($this->DKIM_private)
1121                && !empty($this->DKIM_selector)
1122                && file_exists($this->DKIM_private)) {
1123                $header_dkim = $this->DKIM_Add(
1124                    $this->MIMEHeader . $this->mailHeader,
1125                    $this->encodeHeader($this->secureHeader($this->Subject)),
1126                    $this->MIMEBody
1127                );
1128                $this->MIMEHeader = rtrim($this->MIMEHeader, "\r\n ") . self::CRLF .
1129                    str_replace("\r\n", "\n", $header_dkim) . self::CRLF;
1130            }
1131            return true;
1132        } catch (phpmailerException $exc) {
1133            $this->setError($exc->getMessage());
1134            if ($this->exceptions) {
1135                throw $exc;
1136            }
1137            return false;
1138        }
1139    }
1140
1141    /**
1142     * Actually send a message.
1143     * Send the email via the selected mechanism
1144     * @throws phpmailerException
1145     * @return boolean
1146     */
1147    public function postSend()
1148    {
1149        try {
1150            // Choose the mailer and send through it
1151            switch ($this->Mailer) {
1152                case 'sendmail':
1153                case 'qmail':
1154                    return $this->sendmailSend($this->MIMEHeader, $this->MIMEBody);
1155                case 'smtp':
1156                    return $this->smtpSend($this->MIMEHeader, $this->MIMEBody);
1157                case 'mail':
1158                    return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
1159                default:
1160                    $sendMethod = $this->Mailer.'Send';
1161                    if (method_exists($this, $sendMethod)) {
1162                        return $this->$sendMethod($this->MIMEHeader, $this->MIMEBody);
1163                    }
1164
1165                    return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
1166            }
1167        } catch (phpmailerException $exc) {
1168            $this->setError($exc->getMessage());
1169            $this->edebug($exc->getMessage());
1170            if ($this->exceptions) {
1171                throw $exc;
1172            }
1173        }
1174        return false;
1175    }
1176
1177    /**
1178     * Send mail using the $Sendmail program.
1179     * @param string $header The message headers
1180     * @param string $body The message body
1181     * @see PHPMailer::$Sendmail
1182     * @throws phpmailerException
1183     * @access protected
1184     * @return boolean
1185     */
1186    protected function sendmailSend($header, $body)
1187    {
1188        if ($this->Sender != '') {
1189            if ($this->Mailer == 'qmail') {
1190                $sendmail = sprintf('%s -f%s', escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
1191            } else {
1192                $sendmail = sprintf('%s -oi -f%s -t', escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
1193            }
1194        } else {
1195            if ($this->Mailer == 'qmail') {
1196                $sendmail = sprintf('%s', escapeshellcmd($this->Sendmail));
1197            } else {
1198                $sendmail = sprintf('%s -oi -t', escapeshellcmd($this->Sendmail));
1199            }
1200        }
1201        if ($this->SingleTo) {
1202            foreach ($this->SingleToArray as $toAddr) {
1203                if (!@$mail = popen($sendmail, 'w')) {
1204                    throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1205                }
1206                fputs($mail, 'To: ' . $toAddr . "\n");
1207                fputs($mail, $header);
1208                fputs($mail, $body);
1209                $result = pclose($mail);
1210                $this->doCallback(
1211                    ($result == 0),
1212                    array($toAddr),
1213                    $this->cc,
1214                    $this->bcc,
1215                    $this->Subject,
1216                    $body,
1217                    $this->From
1218                );
1219                if ($result != 0) {
1220                    throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1221                }
1222            }
1223        } else {
1224            if (!@$mail = popen($sendmail, 'w')) {
1225                throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1226            }
1227            fputs($mail, $header);
1228            fputs($mail, $body);
1229            $result = pclose($mail);
1230            $this->doCallback(($result == 0), $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From);
1231            if ($result != 0) {
1232                throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1233            }
1234        }
1235        return true;
1236    }
1237
1238    /**
1239     * Send mail using the PHP mail() function.
1240     * @param string $header The message headers
1241     * @param string $body The message body
1242     * @link http://www.php.net/manual/en/book.mail.php
1243     * @throws phpmailerException
1244     * @access protected
1245     * @return boolean
1246     */
1247    protected function mailSend($header, $body)
1248    {
1249        $toArr = array();
1250        foreach ($this->to as $toaddr) {
1251            $toArr[] = $this->addrFormat($toaddr);
1252        }
1253        $to = implode(', ', $toArr);
1254
1255        if (empty($this->Sender)) {
1256            $params = ' ';
1257        } else {
1258            $params = sprintf('-f%s', $this->Sender);
1259        }
1260        if ($this->Sender != '' and !ini_get('safe_mode')) {
1261            $old_from = ini_get('sendmail_from');
1262            ini_set('sendmail_from', $this->Sender);
1263        }
1264        $result = false;
1265        if ($this->SingleTo && count($toArr) > 1) {
1266            foreach ($toArr as $toAddr) {
1267                $result = $this->mailPassthru($toAddr, $this->Subject, $body, $header, $params);
1268                $this->doCallback($result, array($toAddr), $this->cc, $this->bcc, $this->Subject, $body, $this->From);
1269            }
1270        } else {
1271            $result = $this->mailPassthru($to, $this->Subject, $body, $header, $params);
1272            $this->doCallback($result, $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From);
1273        }
1274        if (isset($old_from)) {
1275            ini_set('sendmail_from', $old_from);
1276        }
1277        if (!$result) {
1278            throw new phpmailerException($this->lang('instantiate'), self::STOP_CRITICAL);
1279        }
1280        return true;
1281    }
1282
1283    /**
1284     * Get an instance to use for SMTP operations.
1285     * Override this function to load your own SMTP implementation
1286     * @return SMTP
1287     */
1288    public function getSMTPInstance()
1289    {
1290        if (!is_object($this->smtp)) {
1291            $this->smtp = new SMTP;
1292        }
1293        return $this->smtp;
1294    }
1295
1296    /**
1297     * Send mail via SMTP.
1298     * Returns false if there is a bad MAIL FROM, RCPT, or DATA input.
1299     * Uses the PHPMailerSMTP class by default.
1300     * @see PHPMailer::getSMTPInstance() to use a different class.
1301     * @param string $header The message headers
1302     * @param string $body The message body
1303     * @throws phpmailerException
1304     * @uses SMTP
1305     * @access protected
1306     * @return boolean
1307     */
1308    protected function smtpSend($header, $body)
1309    {
1310        $bad_rcpt = array();
1311        if (!$this->smtpConnect($this->SMTPOptions)) {
1312            throw new phpmailerException($this->lang('smtp_connect_failed'), self::STOP_CRITICAL);
1313        }
1314        if ('' == $this->Sender) {
1315            $smtp_from = $this->From;
1316        } else {
1317            $smtp_from = $this->Sender;
1318        }
1319        if (!$this->smtp->mail($smtp_from)) {
1320            $this->setError($this->lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp->getError()));
1321            throw new phpmailerException($this->ErrorInfo, self::STOP_CRITICAL);
1322        }
1323
1324        // Attempt to send to all recipients
1325        foreach (array($this->to, $this->cc, $this->bcc) as $togroup) {
1326            foreach ($togroup as $to) {
1327                if (!$this->smtp->recipient($to[0])) {
1328                    $error = $this->smtp->getError();
1329                    $bad_rcpt[] = array('to' => $to[0], 'error' => $error['detail']);
1330                    $isSent = false;
1331                } else {
1332                    $isSent = true;
1333                }
1334                $this->doCallback($isSent, array($to[0]), array(), array(), $this->Subject, $body, $this->From);
1335            }
1336        }
1337
1338        // Only send the DATA command if we have viable recipients
1339        if ((count($this->all_recipients) > count($bad_rcpt)) and !$this->smtp->data($header . $body)) {
1340            throw new phpmailerException($this->lang('data_not_accepted'), self::STOP_CRITICAL);
1341        }
1342        if ($this->SMTPKeepAlive) {
1343            $this->smtp->reset();
1344        } else {
1345            $this->smtp->quit();
1346            $this->smtp->close();
1347        }
1348        //Create error message for any bad addresses
1349        if (count($bad_rcpt) > 0) {
1350            $errstr = '';
1351            foreach ($bad_rcpt as $bad) {
1352                $errstr .= $bad['to'] . ': ' . $bad['error'];
1353            }
1354            throw new phpmailerException(
1355                $this->lang('recipients_failed') . $errstr,
1356                self::STOP_CONTINUE
1357            );
1358        }
1359        return true;
1360    }
1361
1362    /**
1363     * Initiate a connection to an SMTP server.
1364     * Returns false if the operation failed.
1365     * @param array $options An array of options compatible with stream_context_create()
1366     * @uses SMTP
1367     * @access public
1368     * @throws phpmailerException
1369     * @return boolean
1370     */
1371    public function smtpConnect($options = array())
1372    {
1373        if (is_null($this->smtp)) {
1374            $this->smtp = $this->getSMTPInstance();
1375        }
1376
1377        // Already connected?
1378        if ($this->smtp->connected()) {
1379            return true;
1380        }
1381
1382        $this->smtp->setTimeout($this->Timeout);
1383        $this->smtp->setDebugLevel($this->SMTPDebug);
1384        $this->smtp->setDebugOutput($this->Debugoutput);
1385        $this->smtp->setVerp($this->do_verp);
1386        $hosts = explode(';', $this->Host);
1387        $lastexception = null;
1388
1389        foreach ($hosts as $hostentry) {
1390            $hostinfo = array();
1391            if (!preg_match('/^((ssl|tls):\/\/)*([a-zA-Z0-9\.-]*):?([0-9]*)$/', trim($hostentry), $hostinfo)) {
1392                // Not a valid host entry
1393                continue;
1394            }
1395            // $hostinfo[2]: optional ssl or tls prefix
1396            // $hostinfo[3]: the hostname
1397            // $hostinfo[4]: optional port number
1398            // The host string prefix can temporarily override the current setting for SMTPSecure
1399            // If it's not specified, the default value is used
1400            $prefix = '';
1401            $secure = $this->SMTPSecure;
1402            $tls = ($this->SMTPSecure == 'tls');
1403            if ('ssl' == $hostinfo[2] or ('' == $hostinfo[2] and 'ssl' == $this->SMTPSecure)) {
1404                $prefix = 'ssl://';
1405                $tls = false; // Can't have SSL and TLS at the same time
1406                $secure = 'ssl';
1407            } elseif ($hostinfo[2] == 'tls') {
1408                $tls = true;
1409                // tls doesn't use a prefix
1410                $secure = 'tls';
1411            }
1412            //Do we need the OpenSSL extension?
1413            $sslext = defined('OPENSSL_ALGO_SHA1');
1414            if ('tls' === $secure or 'ssl' === $secure) {
1415                //Check for an OpenSSL constant rather than using extension_loaded, which is sometimes disabled
1416                if (!$sslext) {
1417                    throw new phpmailerException($this->lang('extension_missing').'openssl', self::STOP_CRITICAL);
1418                }
1419            }
1420            $host = $hostinfo[3];
1421            $port = $this->Port;
1422            $tport = (integer)$hostinfo[4];
1423            if ($tport > 0 and $tport < 65536) {
1424                $port = $tport;
1425            }
1426            if ($this->smtp->connect($prefix . $host, $port, $this->Timeout, $options)) {
1427                try {
1428                    if ($this->Helo) {
1429                        $hello = $this->Helo;
1430                    } else {
1431                        $hello = $this->serverHostname();
1432                    }
1433                    $this->smtp->hello($hello);
1434                    //Automatically enable TLS encryption if:
1435                    // * it's not disabled
1436                    // * we have openssl extension
1437                    // * we are not already using SSL
1438                    // * the server offers STARTTLS
1439                    if ($this->SMTPAutoTLS and $sslext and $secure != 'ssl' and $this->smtp->getServerExt('STARTTLS')) {
1440                        $tls = true;
1441                    }
1442                    if ($tls) {
1443                        if (!$this->smtp->startTLS()) {
1444                            throw new phpmailerException($this->lang('connect_host'));
1445                        }
1446                        // We must resend HELO after tls negotiation
1447                        $this->smtp->hello($hello);
1448                    }
1449                    if ($this->SMTPAuth) {
1450                        if (!$this->smtp->authenticate(
1451                            $this->Username,
1452                            $this->Password,
1453                            $this->AuthType,
1454                            $this->Realm,
1455                            $this->Workstation
1456                        )
1457                        ) {
1458                            throw new phpmailerException($this->lang('authenticate'));
1459                        }
1460                    }
1461                    return true;
1462                } catch (phpmailerException $exc) {
1463                    $lastexception = $exc;
1464                    $this->edebug($exc->getMessage());
1465                    // We must have connected, but then failed TLS or Auth, so close connection nicely
1466                    $this->smtp->quit();
1467                }
1468            }
1469        }
1470        // If we get here, all connection attempts have failed, so close connection hard
1471        $this->smtp->close();
1472        // As we've caught all exceptions, just report whatever the last one was
1473        if ($this->exceptions and !is_null($lastexception)) {
1474            throw $lastexception;
1475        }
1476        return false;
1477    }
1478
1479    /**
1480     * Close the active SMTP session if one exists.
1481     * @return void
1482     */
1483    public function smtpClose()
1484    {
1485        if ($this->smtp !== null) {
1486            if ($this->smtp->connected()) {
1487                $this->smtp->quit();
1488                $this->smtp->close();
1489            }
1490        }
1491    }
1492
1493    /**
1494     * Set the language for error messages.
1495     * Returns false if it cannot load the language file.
1496     * The default language is English.
1497     * @param string $langcode ISO 639-1 2-character language code (e.g. French is "fr")
1498     * @param string $lang_path Path to the language file directory, with trailing separator (slash)
1499     * @return boolean
1500     * @access public
1501     */
1502    public function se…

Large files files are truncated, but you can click here to view the full file