Core  3.2
PHP API documentation
 All Data Structures Namespaces Files Functions Variables Pages
class.phpmailer.php
Go to the documentation of this 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  */
28 class PHPMailer
29 {
30  /**
31  * The PHPMailer Version number.
32  * @var string
33  */
34  public $Version = '5.2.14';
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  * @var integer
41  */
42  public $Priority = null;
43 
44  /**
45  * The character set of the message.
46  * @var string
47  */
48  public $CharSet = 'iso-8859-1';
49 
50  /**
51  * The MIME Content-type of the message.
52  * @var string
53  */
54  public $ContentType = 'text/plain';
55 
56  /**
57  * The message encoding.
58  * Options: "8bit", "7bit", "binary", "base64", and "quoted-printable".
59  * @var string
60  */
61  public $Encoding = '8bit';
62 
63  /**
64  * Holds the most recent mailer error message.
65  * @var string
66  */
67  public $ErrorInfo = '';
68 
69  /**
70  * The From email address for the message.
71  * @var string
72  */
73  public $From = 'root@localhost';
74 
75  /**
76  * The From name of the message.
77  * @var 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  * @var 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  * @var 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  * @var string
101  */
102  public $Subject = '';
103 
104  /**
105  * An HTML or plain text message body.
106  * If HTML then call isHTML(true).
107  * @var 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  * @var 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  * @var string
127  */
128  public $Ical = '';
129 
130  /**
131  * The complete compiled MIME message body.
132  * @access protected
133  * @var string
134  */
135  protected $MIMEBody = '';
136 
137  /**
138  * The complete compiled MIME message headers.
139  * @var string
140  * @access protected
141  */
142  protected $MIMEHeader = '';
143 
144  /**
145  * Extra headers that createHeader() doesn't fold in.
146  * @var 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  * @var integer
155  */
156  public $WordWrap = 0;
157 
158  /**
159  * Which method to use to send mail.
160  * Options: "mail", "sendmail", or "smtp".
161  * @var string
162  */
163  public $Mailer = 'mail';
164 
165  /**
166  * The path to the sendmail program.
167  * @var 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  * @var 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  * @var 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, also known as read receipt.
188  * @var string
189  */
190  public $ConfirmReadingTo = '';
191 
192  /**
193  * The hostname to use in the Message-ID header and as default HELO string.
194  * If empty, PHPMailer attempts to find one with, in order,
195  * $_SERVER['SERVER_NAME'], gethostname(), php_uname('n'), or the value
196  * 'localhost.localdomain'.
197  * @var 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  * @var 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  * @var 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  * @var string
225  */
226  public $Host = 'localhost';
227 
228  /**
229  * The default SMTP server port.
230  * @var 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. If $Hostname is empty, PHPMailer attempts to find
238  * one with the same method described above for $Hostname.
239  * @var string
240  * @see PHPMailer::$Hostname
241  */
242  public $Helo = '';
243 
244  /**
245  * What kind of encryption to use on the SMTP connection.
246  * Options: '', 'ssl' or 'tls'
247  * @var string
248  */
249  public $SMTPSecure = '';
250 
251  /**
252  * Whether to enable TLS encryption automatically if a server supports it,
253  * even if `SMTPSecure` is not set to 'tls'.
254  * Be aware that in PHP >= 5.6 this requires that the server's certificates are valid.
255  * @var boolean
256  */
257  public $SMTPAutoTLS = true;
258 
259  /**
260  * Whether to use SMTP authentication.
261  * Uses the Username and Password properties.
262  * @var boolean
263  * @see PHPMailer::$Username
264  * @see PHPMailer::$Password
265  */
266  public $SMTPAuth = false;
267 
268  /**
269  * Options array passed to stream_context_create when connecting via SMTP.
270  * @var array
271  */
272  public $SMTPOptions = array();
273 
274  /**
275  * SMTP username.
276  * @var string
277  */
278  public $Username = '';
279 
280  /**
281  * SMTP password.
282  * @var string
283  */
284  public $Password = '';
285 
286  /**
287  * SMTP auth type.
288  * Options are LOGIN (default), PLAIN, NTLM, CRAM-MD5
289  * @var string
290  */
291  public $AuthType = '';
292 
293  /**
294  * SMTP realm.
295  * Used for NTLM auth
296  * @var string
297  */
298  public $Realm = '';
299 
300  /**
301  * SMTP workstation.
302  * Used for NTLM auth
303  * @var string
304  */
305  public $Workstation = '';
306 
307  /**
308  * The SMTP server timeout in seconds.
309  * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2
310  * @var integer
311  */
312  public $Timeout = 300;
313 
314  /**
315  * SMTP class debug output mode.
316  * Debug output level.
317  * Options:
318  * * `0` No output
319  * * `1` Commands
320  * * `2` Data and commands
321  * * `3` As 2 plus connection status
322  * * `4` Low-level data output
323  * @var integer
324  * @see SMTP::$do_debug
325  */
326  public $SMTPDebug = 0;
327 
328  /**
329  * How to handle debug output.
330  * Options:
331  * * `echo` Output plain-text as-is, appropriate for CLI
332  * * `html` Output escaped, line breaks converted to `<br>`, appropriate for browser output
333  * * `error_log` Output to error log as configured in php.ini
334  *
335  * Alternatively, you can provide a callable expecting two params: a message string and the debug level:
336  * <code>
337  * $mail->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";};
338  * </code>
339  * @var string|callable
340  * @see SMTP::$Debugoutput
341  */
342  public $Debugoutput = 'echo';
343 
344  /**
345  * Whether to keep SMTP connection open after each message.
346  * If this is set to true then to close the connection
347  * requires an explicit call to smtpClose().
348  * @var boolean
349  */
350  public $SMTPKeepAlive = false;
351 
352  /**
353  * Whether to split multiple to addresses into multiple messages
354  * or send them all in one message.
355  * @var boolean
356  */
357  public $SingleTo = false;
358 
359  /**
360  * Storage for addresses when SingleTo is enabled.
361  * @var array
362  * @TODO This should really not be public
363  */
364  public $SingleToArray = array();
365 
366  /**
367  * Whether to generate VERP addresses on send.
368  * Only applicable when sending via SMTP.
369  * @link https://en.wikipedia.org/wiki/Variable_envelope_return_path
370  * @link http://www.postfix.org/VERP_README.html Postfix VERP info
371  * @var boolean
372  */
373  public $do_verp = false;
374 
375  /**
376  * Whether to allow sending messages with an empty body.
377  * @var boolean
378  */
379  public $AllowEmpty = false;
380 
381  /**
382  * The default line ending.
383  * @note The default remains "\n". We force CRLF where we know
384  * it must be used via self::CRLF.
385  * @var string
386  */
387  public $LE = "\n";
388 
389  /**
390  * DKIM selector.
391  * @var string
392  */
393  public $DKIM_selector = '';
394 
395  /**
396  * DKIM Identity.
397  * Usually the email address used as the source of the email
398  * @var string
399  */
400  public $DKIM_identity = '';
401 
402  /**
403  * DKIM passphrase.
404  * Used if your key is encrypted.
405  * @var string
406  */
407  public $DKIM_passphrase = '';
408 
409  /**
410  * DKIM signing domain name.
411  * @example 'example.com'
412  * @var string
413  */
414  public $DKIM_domain = '';
415 
416  /**
417  * DKIM private key file path.
418  * @var string
419  */
420  public $DKIM_private = '';
421 
422  /**
423  * Callback Action function name.
424  *
425  * The function that handles the result of the send email action.
426  * It is called out by send() for each email sent.
427  *
428  * Value can be any php callable: http://www.php.net/is_callable
429  *
430  * Parameters:
431  * boolean $result result of the send action
432  * string $to email address of the recipient
433  * string $cc cc email addresses
434  * string $bcc bcc email addresses
435  * string $subject the subject
436  * string $body the email body
437  * string $from email address of sender
438  * @var string
439  */
440  public $action_function = '';
441 
442  /**
443  * What to put in the X-Mailer header.
444  * Options: An empty string for PHPMailer default, whitespace for none, or a string to use
445  * @var string
446  */
447  public $XMailer = '';
448 
449  /**
450  * An instance of the SMTP sender class.
451  * @var SMTP
452  * @access protected
453  */
454  protected $smtp = null;
455 
456  /**
457  * The array of 'to' names and addresses.
458  * @var array
459  * @access protected
460  */
461  protected $to = array();
462 
463  /**
464  * The array of 'cc' names and addresses.
465  * @var array
466  * @access protected
467  */
468  protected $cc = array();
469 
470  /**
471  * The array of 'bcc' names and addresses.
472  * @var array
473  * @access protected
474  */
475  protected $bcc = array();
476 
477  /**
478  * The array of reply-to names and addresses.
479  * @var array
480  * @access protected
481  */
482  protected $ReplyTo = array();
483 
484  /**
485  * An array of all kinds of addresses.
486  * Includes all of $to, $cc, $bcc
487  * @var array
488  * @access protected
489  * @see PHPMailer::$to @see PHPMailer::$cc @see PHPMailer::$bcc
490  */
491  protected $all_recipients = array();
492 
493  /**
494  * An array of names and addresses queued for validation.
495  * In send(), valid and non duplicate entries are moved to $all_recipients
496  * and one of $to, $cc, or $bcc.
497  * This array is used only for addresses with IDN.
498  * @var array
499  * @access protected
500  * @see PHPMailer::$to @see PHPMailer::$cc @see PHPMailer::$bcc
501  * @see PHPMailer::$all_recipients
502  */
503  protected $RecipientsQueue = array();
504 
505  /**
506  * An array of reply-to names and addresses queued for validation.
507  * In send(), valid and non duplicate entries are moved to $ReplyTo.
508  * This array is used only for addresses with IDN.
509  * @var array
510  * @access protected
511  * @see PHPMailer::$ReplyTo
512  */
513  protected $ReplyToQueue = array();
514 
515  /**
516  * The array of attachments.
517  * @var array
518  * @access protected
519  */
520  protected $attachment = array();
521 
522  /**
523  * The array of custom headers.
524  * @var array
525  * @access protected
526  */
527  protected $CustomHeader = array();
528 
529  /**
530  * The most recent Message-ID (including angular brackets).
531  * @var string
532  * @access protected
533  */
534  protected $lastMessageID = '';
535 
536  /**
537  * The message's MIME type.
538  * @var string
539  * @access protected
540  */
541  protected $message_type = '';
542 
543  /**
544  * The array of MIME boundary strings.
545  * @var array
546  * @access protected
547  */
548  protected $boundary = array();
549 
550  /**
551  * The array of available languages.
552  * @var array
553  * @access protected
554  */
555  protected $language = array();
556 
557  /**
558  * The number of errors encountered.
559  * @var integer
560  * @access protected
561  */
562  protected $error_count = 0;
563 
564  /**
565  * The S/MIME certificate file path.
566  * @var string
567  * @access protected
568  */
569  protected $sign_cert_file = '';
570 
571  /**
572  * The S/MIME key file path.
573  * @var string
574  * @access protected
575  */
576  protected $sign_key_file = '';
577 
578  /**
579  * The optional S/MIME extra certificates ("CA Chain") file path.
580  * @var string
581  * @access protected
582  */
583  protected $sign_extracerts_file = '';
584 
585  /**
586  * The S/MIME password for the key.
587  * Used only if the key is encrypted.
588  * @var string
589  * @access protected
590  */
591  protected $sign_key_pass = '';
592 
593  /**
594  * Whether to throw exceptions for errors.
595  * @var boolean
596  * @access protected
597  */
598  protected $exceptions = false;
599 
600  /**
601  * Unique ID used for message ID and boundaries.
602  * @var string
603  * @access protected
604  */
605  protected $uniqueid = '';
606 
607  /**
608  * Error severity: message only, continue processing.
609  */
610  const STOP_MESSAGE = 0;
611 
612  /**
613  * Error severity: message, likely ok to continue processing.
614  */
615  const STOP_CONTINUE = 1;
616 
617  /**
618  * Error severity: message, plus full stop, critical error reached.
619  */
620  const STOP_CRITICAL = 2;
621 
622  /**
623  * SMTP RFC standard line ending.
624  */
625  const CRLF = "\r\n";
626 
627  /**
628  * The maximum line length allowed by RFC 2822 section 2.1.1
629  * @var integer
630  */
631  const MAX_LINE_LENGTH = 998;
632 
633  /**
634  * Constructor.
635  * @param boolean $exceptions Should we throw external exceptions?
636  */
637  public function __construct($exceptions = false)
638  {
639  $this->exceptions = (boolean)$exceptions;
640  }
641 
642  /**
643  * Destructor.
644  */
645  public function __destruct()
646  {
647  //Close any open SMTP connection nicely
648  if ($this->Mailer == 'smtp') {
649  $this->smtpClose();
650  }
651  }
652 
653  /**
654  * Call mail() in a safe_mode-aware fashion.
655  * Also, unless sendmail_path points to sendmail (or something that
656  * claims to be sendmail), don't pass params (not a perfect fix,
657  * but it will do)
658  * @param string $to To
659  * @param string $subject Subject
660  * @param string $body Message Body
661  * @param string $header Additional Header(s)
662  * @param string $params Params
663  * @access private
664  * @return boolean
665  */
666  private function mailPassthru($to, $subject, $body, $header, $params)
667  {
668  //Check overloading of mail function to avoid double-encoding
669  if (ini_get('mbstring.func_overload') & 1) {
670  $subject = $this->secureHeader($subject);
671  } else {
672  $subject = $this->encodeHeader($this->secureHeader($subject));
673  }
674  if (ini_get('safe_mode') || !($this->UseSendmailOptions)) {
675  $result = @mail($to, $subject, $body, $header);
676  } else {
677  $result = @mail($to, $subject, $body, $header, $params);
678  }
679  return $result;
680  }
681 
682  /**
683  * Output debugging info via user-defined method.
684  * Only generates output if SMTP debug output is enabled (@see SMTP::$do_debug).
685  * @see PHPMailer::$Debugoutput
686  * @see PHPMailer::$SMTPDebug
687  * @param string $str
688  */
689  protected function edebug($str)
690  {
691  if ($this->SMTPDebug <= 0) {
692  return;
693  }
694  //Avoid clash with built-in function names
695  if (!in_array($this->Debugoutput, array('error_log', 'html', 'echo')) and is_callable($this->Debugoutput)) {
696  call_user_func($this->Debugoutput, $str, $this->SMTPDebug);
697  return;
698  }
699  switch ($this->Debugoutput) {
700  case 'error_log':
701  //Don't output, just log
702  error_log($str);
703  break;
704  case 'html':
705  //Cleans up output a bit for a better looking, HTML-safe output
706  echo htmlentities(
707  preg_replace('/[\r\n]+/', '', $str),
708  ENT_QUOTES,
709  'UTF-8'
710  )
711  . "<br>\n";
712  break;
713  case 'echo':
714  default:
715  //Normalize line breaks
716  $str = preg_replace('/(\r\n|\r|\n)/ms', "\n", $str);
717  echo gmdate('Y-m-d H:i:s') . "\t" . str_replace(
718  "\n",
719  "\n \t ",
720  trim($str)
721  ) . "\n";
722  }
723  }
724 
725  /**
726  * Sets message type to HTML or plain.
727  * @param boolean $isHtml True for HTML mode.
728  * @return void
729  */
730  public function isHTML($isHtml = true)
731  {
732  if ($isHtml) {
733  $this->ContentType = 'text/html';
734  } else {
735  $this->ContentType = 'text/plain';
736  }
737  }
738 
739  /**
740  * Send messages using SMTP.
741  * @return void
742  */
743  public function isSMTP()
744  {
745  $this->Mailer = 'smtp';
746  }
747 
748  /**
749  * Send messages using PHP's mail() function.
750  * @return void
751  */
752  public function isMail()
753  {
754  $this->Mailer = 'mail';
755  }
756 
757  /**
758  * Send messages using $Sendmail.
759  * @return void
760  */
761  public function isSendmail()
762  {
763  $ini_sendmail_path = ini_get('sendmail_path');
764 
765  if (!stristr($ini_sendmail_path, 'sendmail')) {
766  $this->Sendmail = '/usr/sbin/sendmail';
767  } else {
768  $this->Sendmail = $ini_sendmail_path;
769  }
770  $this->Mailer = 'sendmail';
771  }
772 
773  /**
774  * Send messages using qmail.
775  * @return void
776  */
777  public function isQmail()
778  {
779  $ini_sendmail_path = ini_get('sendmail_path');
780 
781  if (!stristr($ini_sendmail_path, 'qmail')) {
782  $this->Sendmail = '/var/qmail/bin/qmail-inject';
783  } else {
784  $this->Sendmail = $ini_sendmail_path;
785  }
786  $this->Mailer = 'qmail';
787  }
788 
789  /**
790  * Add a "To" address.
791  * @param string $address The email address to send to
792  * @param string $name
793  * @return boolean true on success, false if address already used or invalid in some way
794  */
795  public function addAddress($address, $name = '')
796  {
797  return $this->addOrEnqueueAnAddress('to', $address, $name);
798  }
799 
800  /**
801  * Add a "CC" address.
802  * @note: This function works with the SMTP mailer on win32, not with the "mail" mailer.
803  * @param string $address The email address to send to
804  * @param string $name
805  * @return boolean true on success, false if address already used or invalid in some way
806  */
807  public function addCC($address, $name = '')
808  {
809  return $this->addOrEnqueueAnAddress('cc', $address, $name);
810  }
811 
812  /**
813  * Add a "BCC" address.
814  * @note: This function works with the SMTP mailer on win32, not with the "mail" mailer.
815  * @param string $address The email address to send to
816  * @param string $name
817  * @return boolean true on success, false if address already used or invalid in some way
818  */
819  public function addBCC($address, $name = '')
820  {
821  return $this->addOrEnqueueAnAddress('bcc', $address, $name);
822  }
823 
824  /**
825  * Add a "Reply-To" address.
826  * @param string $address The email address to reply to
827  * @param string $name
828  * @return boolean true on success, false if address already used or invalid in some way
829  */
830  public function addReplyTo($address, $name = '')
831  {
832  return $this->addOrEnqueueAnAddress('Reply-To', $address, $name);
833  }
834 
835  /**
836  * Add an address to one of the recipient arrays or to the ReplyTo array. Because PHPMailer
837  * can't validate addresses with an IDN without knowing the PHPMailer::$CharSet (that can still
838  * be modified after calling this function), addition of such addresses is delayed until send().
839  * Addresses that have been added already return false, but do not throw exceptions.
840  * @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo'
841  * @param string $address The email address to send, resp. to reply to
842  * @param string $name
843  * @throws phpmailerException
844  * @return boolean true on success, false if address already used or invalid in some way
845  * @access protected
846  */
847  protected function addOrEnqueueAnAddress($kind, $address, $name)
848  {
849  $address = trim($address);
850  $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
851  if (($pos = strrpos($address, '@')) === false) {
852  // At-sign is misssing.
853  $error_message = $this->lang('invalid_address') . $address;
854  $this->setError($error_message);
855  $this->edebug($error_message);
856  if ($this->exceptions) {
857  throw new phpmailerException($error_message);
858  }
859  return false;
860  }
861  $params = array($kind, $address, $name);
862  // Enqueue addresses with IDN until we know the PHPMailer::$CharSet.
863  if ($this->has8bitChars(substr($address, ++$pos)) and $this->idnSupported()) {
864  if ($kind != 'Reply-To') {
865  if (!array_key_exists($address, $this->RecipientsQueue)) {
866  $this->RecipientsQueue[$address] = $params;
867  return true;
868  }
869  } else {
870  if (!array_key_exists($address, $this->ReplyToQueue)) {
871  $this->ReplyToQueue[$address] = $params;
872  return true;
873  }
874  }
875  return false;
876  }
877  // Immediately add standard addresses without IDN.
878  return call_user_func_array(array($this, 'addAnAddress'), $params);
879  }
880 
881  /**
882  * Add an address to one of the recipient arrays or to the ReplyTo array.
883  * Addresses that have been added already return false, but do not throw exceptions.
884  * @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo'
885  * @param string $address The email address to send, resp. to reply to
886  * @param string $name
887  * @throws phpmailerException
888  * @return boolean true on success, false if address already used or invalid in some way
889  * @access protected
890  */
891  protected function addAnAddress($kind, $address, $name = '')
892  {
893  if (!in_array($kind, array('to', 'cc', 'bcc', 'Reply-To'))) {
894  $error_message = $this->lang('Invalid recipient kind: ') . $kind;
895  $this->setError($error_message);
896  $this->edebug($error_message);
897  if ($this->exceptions) {
898  throw new phpmailerException($error_message);
899  }
900  return false;
901  }
902  if (!$this->validateAddress($address)) {
903  $error_message = $this->lang('invalid_address') . $address;
904  $this->setError($error_message);
905  $this->edebug($error_message);
906  if ($this->exceptions) {
907  throw new phpmailerException($error_message);
908  }
909  return false;
910  }
911  if ($kind != 'Reply-To') {
912  if (!array_key_exists(strtolower($address), $this->all_recipients)) {
913  array_push($this->$kind, array($address, $name));
914  $this->all_recipients[strtolower($address)] = true;
915  return true;
916  }
917  } else {
918  if (!array_key_exists(strtolower($address), $this->ReplyTo)) {
919  $this->ReplyTo[strtolower($address)] = array($address, $name);
920  return true;
921  }
922  }
923  return false;
924  }
925 
926  /**
927  * Parse and validate a string containing one or more RFC822-style comma-separated email addresses
928  * of the form "display name <address>" into an array of name/address pairs.
929  * Uses the imap_rfc822_parse_adrlist function if the IMAP extension is available.
930  * Note that quotes in the name part are removed.
931  * @param string $addrstr The address list string
932  * @param bool $useimap Whether to use the IMAP extension to parse the list
933  * @return array
934  * @link http://www.andrew.cmu.edu/user/agreen1/testing/mrbs/web/Mail/RFC822.php A more careful implementation
935  */
936  public function parseAddresses($addrstr, $useimap = true)
937  {
938  $addresses = array();
939  if ($useimap and function_exists('imap_rfc822_parse_adrlist')) {
940  //Use this built-in parser if it's available
941  $list = imap_rfc822_parse_adrlist($addrstr, '');
942  foreach ($list as $address) {
943  if ($address->host != '.SYNTAX-ERROR.') {
944  if ($this->validateAddress($address->mailbox . '@' . $address->host)) {
945  $addresses[] = array(
946  'name' => (property_exists($address, 'personal') ? $address->personal : ''),
947  'address' => $address->mailbox . '@' . $address->host
948  );
949  }
950  }
951  }
952  } else {
953  //Use this simpler parser
954  $list = explode(',', $addrstr);
955  foreach ($list as $address) {
956  $address = trim($address);
957  //Is there a separate name part?
958  if (strpos($address, '<') === false) {
959  //No separate name, just use the whole thing
960  if ($this->validateAddress($address)) {
961  $addresses[] = array(
962  'name' => '',
963  'address' => $address
964  );
965  }
966  } else {
967  list($name, $email) = explode('<', $address);
968  $email = trim(str_replace('>', '', $email));
969  if ($this->validateAddress($email)) {
970  $addresses[] = array(
971  'name' => trim(str_replace(array('"', "'"), '', $name)),
972  'address' => $email
973  );
974  }
975  }
976  }
977  }
978  return $addresses;
979  }
980 
981  /**
982  * Set the From and FromName properties.
983  * @param string $address
984  * @param string $name
985  * @param boolean $auto Whether to also set the Sender address, defaults to true
986  * @throws phpmailerException
987  * @return boolean
988  */
989  public function setFrom($address, $name = '', $auto = true)
990  {
991  $address = trim($address);
992  $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
993  // Don't validate now addresses with IDN. Will be done in send().
994  if (($pos = strrpos($address, '@')) === false or
995  (!$this->has8bitChars(substr($address, ++$pos)) or !$this->idnSupported()) and
996  !$this->validateAddress($address)) {
997  $error_message = $this->lang('invalid_address') . $address;
998  $this->setError($error_message);
999  $this->edebug($error_message);
1000  if ($this->exceptions) {
1001  throw new phpmailerException($error_message);
1002  }
1003  return false;
1004  }
1005  $this->From = $address;
1006  $this->FromName = $name;
1007  if ($auto) {
1008  if (empty($this->Sender)) {
1009  $this->Sender = $address;
1010  }
1011  }
1012  return true;
1013  }
1014 
1015  /**
1016  * Return the Message-ID header of the last email.
1017  * Technically this is the value from the last time the headers were created,
1018  * but it's also the message ID of the last sent message except in
1019  * pathological cases.
1020  * @return string
1021  */
1022  public function getLastMessageID()
1023  {
1024  return $this->lastMessageID;
1025  }
1026 
1027  /**
1028  * Check that a string looks like an email address.
1029  * @param string $address The email address to check
1030  * @param string $patternselect A selector for the validation pattern to use :
1031  * * `auto` Pick best pattern automatically;
1032  * * `pcre8` Use the squiloople.com pattern, requires PCRE > 8.0, PHP >= 5.3.2, 5.2.14;
1033  * * `pcre` Use old PCRE implementation;
1034  * * `php` Use PHP built-in FILTER_VALIDATE_EMAIL;
1035  * * `html5` Use the pattern given by the HTML5 spec for 'email' type form input elements.
1036  * * `noregex` Don't use a regex: super fast, really dumb.
1037  * @return boolean
1038  * @static
1039  * @access public
1040  */
1041  public static function validateAddress($address, $patternselect = 'auto')
1042  {
1043  //Reject line breaks in addresses; it's valid RFC5322, but not RFC5321
1044  if (strpos($address, "\n") !== false or strpos($address, "\r") !== false) {
1045  return false;
1046  }
1047  if (!$patternselect or $patternselect == 'auto') {
1048  //Check this constant first so it works when extension_loaded() is disabled by safe mode
1049  //Constant was added in PHP 5.2.4
1050  if (defined('PCRE_VERSION')) {
1051  //This pattern can get stuck in a recursive loop in PCRE <= 8.0.2
1052  if (version_compare(PCRE_VERSION, '8.0.3') >= 0) {
1053  $patternselect = 'pcre8';
1054  } else {
1055  $patternselect = 'pcre';
1056  }
1057  } elseif (function_exists('extension_loaded') and extension_loaded('pcre')) {
1058  //Fall back to older PCRE
1059  $patternselect = 'pcre';
1060  } else {
1061  //Filter_var appeared in PHP 5.2.0 and does not require the PCRE extension
1062  if (version_compare(PHP_VERSION, '5.2.0') >= 0) {
1063  $patternselect = 'php';
1064  } else {
1065  $patternselect = 'noregex';
1066  }
1067  }
1068  }
1069  switch ($patternselect) {
1070  case 'pcre8':
1071  /**
1072  * Uses the same RFC5322 regex on which FILTER_VALIDATE_EMAIL is based, but allows dotless domains.
1073  * @link http://squiloople.com/2009/12/20/email-address-validation/
1074  * @copyright 2009-2010 Michael Rushton
1075  * Feel free to use and redistribute this code. But please keep this copyright notice.
1076  */
1077  return (boolean)preg_match(
1078  '/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)' .
1079  '((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)' .
1080  '(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)' .
1081  '([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*' .
1082  '(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)' .
1083  '(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}' .
1084  '|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:' .
1085  '|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}' .
1086  '|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD',
1087  $address
1088  );
1089  case 'pcre':
1090  //An older regex that doesn't need a recent PCRE
1091  return (boolean)preg_match(
1092  '/^(?!(?>"?(?>\\\[ -~]|[^"])"?){255,})(?!(?>"?(?>\\\[ -~]|[^"])"?){65,}@)(?>' .
1093  '[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*")' .
1094  '(?>\.(?>[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*"))*' .
1095  '@(?>(?![a-z0-9-]{64,})(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>\.(?![a-z0-9-]{64,})' .
1096  '(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)){0,126}|\[(?:(?>IPv6:(?>(?>[a-f0-9]{1,4})(?>:' .
1097  '[a-f0-9]{1,4}){7}|(?!(?:.*[a-f0-9][:\]]){8,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?' .
1098  '::(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?))|(?>(?>IPv6:(?>[a-f0-9]{1,4}(?>:' .
1099  '[a-f0-9]{1,4}){5}:|(?!(?:.*[a-f0-9]:){6,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4})?' .
1100  '::(?>(?:[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4}):)?))?(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}' .
1101  '|[1-9]?[0-9])(?>\.(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}))\])$/isD',
1102  $address
1103  );
1104  case 'html5':
1105  /**
1106  * This is the pattern used in the HTML5 spec for validation of 'email' type form input elements.
1107  * @link http://www.whatwg.org/specs/web-apps/current-work/#e-mail-state-(type=email)
1108  */
1109  return (boolean)preg_match(
1110  '/^[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}' .
1111  '[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/sD',
1112  $address
1113  );
1114  case 'noregex':
1115  //No PCRE! Do something _very_ approximate!
1116  //Check the address is 3 chars or longer and contains an @ that's not the first or last char
1117  return (strlen($address) >= 3
1118  and strpos($address, '@') >= 1
1119  and strpos($address, '@') != strlen($address) - 1);
1120  case 'php':
1121  default:
1122  return (boolean)filter_var($address, FILTER_VALIDATE_EMAIL);
1123  }
1124  }
1125 
1126  /**
1127  * Tells whether IDNs (Internationalized Domain Names) are supported or not. This requires the
1128  * "intl" and "mbstring" PHP extensions.
1129  * @return bool "true" if required functions for IDN support are present
1130  */
1131  public function idnSupported()
1132  {
1133  // @TODO: Write our own "idn_to_ascii" function for PHP <= 5.2.
1134  return function_exists('idn_to_ascii') and function_exists('mb_convert_encoding');
1135  }
1136 
1137  /**
1138  * Converts IDN in given email address to its ASCII form, also known as punycode, if possible.
1139  * Important: Address must be passed in same encoding as currently set in PHPMailer::$CharSet.
1140  * This function silently returns unmodified address if:
1141  * - No conversion is necessary (i.e. domain name is not an IDN, or is already in ASCII form)
1142  * - Conversion to punycode is impossible (e.g. required PHP functions are not available)
1143  * or fails for any reason (e.g. domain has characters not allowed in an IDN)
1144  * @see PHPMailer::$CharSet
1145  * @param string $address The email address to convert
1146  * @return string The encoded address in ASCII form
1147  */
1148  public function punyencodeAddress($address)
1149  {
1150  // Verify we have required functions, CharSet, and at-sign.
1151  if ($this->idnSupported() and
1152  !empty($this->CharSet) and
1153  ($pos = strrpos($address, '@')) !== false) {
1154  $domain = substr($address, ++$pos);
1155  // Verify CharSet string is a valid one, and domain properly encoded in this CharSet.
1156  if ($this->has8bitChars($domain) and @mb_check_encoding($domain, $this->CharSet)) {
1157  $domain = mb_convert_encoding($domain, 'UTF-8', $this->CharSet);
1158  if (($punycode = defined('INTL_IDNA_VARIANT_UTS46') ?
1159  idn_to_ascii($domain, 0, INTL_IDNA_VARIANT_UTS46) :
1160  idn_to_ascii($domain)) !== false) {
1161  return substr($address, 0, $pos) . $punycode;
1162  }
1163  }
1164  }
1165  return $address;
1166  }
1167 
1168  /**
1169  * Create a message and send it.
1170  * Uses the sending method specified by $Mailer.
1171  * @throws phpmailerException
1172  * @return boolean false on error - See the ErrorInfo property for details of the error.
1173  */
1174  public function send()
1175  {
1176  try {
1177  if (!$this->preSend()) {
1178  return false;
1179  }
1180  return $this->postSend();
1181  } catch (phpmailerException $exc) {
1182  $this->mailHeader = '';
1183  $this->setError($exc->getMessage());
1184  if ($this->exceptions) {
1185  throw $exc;
1186  }
1187  return false;
1188  }
1189  }
1190 
1191  /**
1192  * Prepare a message for sending.
1193  * @throws phpmailerException
1194  * @return boolean
1195  */
1196  public function preSend()
1197  {
1198  try {
1199  $this->error_count = 0; // Reset errors
1200  $this->mailHeader = '';
1201 
1202  // Dequeue recipient and Reply-To addresses with IDN
1203  foreach (array_merge($this->RecipientsQueue, $this->ReplyToQueue) as $params) {
1204  $params[1] = $this->punyencodeAddress($params[1]);
1205  call_user_func_array(array($this, 'addAnAddress'), $params);
1206  }
1207  if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) {
1208  throw new phpmailerException($this->lang('provide_address'), self::STOP_CRITICAL);
1209  }
1210 
1211  // Validate From, Sender, and ConfirmReadingTo addresses
1212  foreach (array('From', 'Sender', 'ConfirmReadingTo') as $address_kind) {
1213  $this->$address_kind = trim($this->$address_kind);
1214  if (empty($this->$address_kind)) {
1215  continue;
1216  }
1217  $this->$address_kind = $this->punyencodeAddress($this->$address_kind);
1218  if (!$this->validateAddress($this->$address_kind)) {
1219  $error_message = $this->lang('invalid_address') . $this->$address_kind;
1220  $this->setError($error_message);
1221  $this->edebug($error_message);
1222  if ($this->exceptions) {
1223  throw new phpmailerException($error_message);
1224  }
1225  return false;
1226  }
1227  }
1228 
1229  // Set whether the message is multipart/alternative
1230  if (!empty($this->AltBody)) {
1231  $this->ContentType = 'multipart/alternative';
1232  }
1233 
1234  $this->setMessageType();
1235  // Refuse to send an empty message unless we are specifically allowing it
1236  if (!$this->AllowEmpty and empty($this->Body)) {
1237  throw new phpmailerException($this->lang('empty_message'), self::STOP_CRITICAL);
1238  }
1239 
1240  // Create body before headers in case body makes changes to headers (e.g. altering transfer encoding)
1241  $this->MIMEHeader = '';
1242  $this->MIMEBody = $this->createBody();
1243  // createBody may have added some headers, so retain them
1244  $tempheaders = $this->MIMEHeader;
1245  $this->MIMEHeader = $this->createHeader();
1246  $this->MIMEHeader .= $tempheaders;
1247 
1248  // To capture the complete message when using mail(), create
1249  // an extra header list which createHeader() doesn't fold in
1250  if ($this->Mailer == 'mail') {
1251  if (count($this->to) > 0) {
1252  $this->mailHeader .= $this->addrAppend('To', $this->to);
1253  } else {
1254  $this->mailHeader .= $this->headerLine('To', 'undisclosed-recipients:;');
1255  }
1256  $this->mailHeader .= $this->headerLine(
1257  'Subject',
1258  $this->encodeHeader($this->secureHeader(trim($this->Subject)))
1259  );
1260  }
1261 
1262  // Sign with DKIM if enabled
1263  if (!empty($this->DKIM_domain)
1264  && !empty($this->DKIM_private)
1265  && !empty($this->DKIM_selector)
1266  && file_exists($this->DKIM_private)) {
1267  $header_dkim = $this->DKIM_Add(
1268  $this->MIMEHeader . $this->mailHeader,
1269  $this->encodeHeader($this->secureHeader($this->Subject)),
1270  $this->MIMEBody
1271  );
1272  $this->MIMEHeader = rtrim($this->MIMEHeader, "\r\n ") . self::CRLF .
1273  str_replace("\r\n", "\n", $header_dkim) . self::CRLF;
1274  }
1275  return true;
1276  } catch (phpmailerException $exc) {
1277  $this->setError($exc->getMessage());
1278  if ($this->exceptions) {
1279  throw $exc;
1280  }
1281  return false;
1282  }
1283  }
1284 
1285  /**
1286  * Actually send a message.
1287  * Send the email via the selected mechanism
1288  * @throws phpmailerException
1289  * @return boolean
1290  */
1291  public function postSend()
1292  {
1293  try {
1294  // Choose the mailer and send through it
1295  switch ($this->Mailer) {
1296  case 'sendmail':
1297  case 'qmail':
1298  return $this->sendmailSend($this->MIMEHeader, $this->MIMEBody);
1299  case 'smtp':
1300  return $this->smtpSend($this->MIMEHeader, $this->MIMEBody);
1301  case 'mail':
1302  return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
1303  default:
1304  $sendMethod = $this->Mailer.'Send';
1305  if (method_exists($this, $sendMethod)) {
1306  return $this->$sendMethod($this->MIMEHeader, $this->MIMEBody);
1307  }
1308 
1309  return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
1310  }
1311  } catch (phpmailerException $exc) {
1312  $this->setError($exc->getMessage());
1313  $this->edebug($exc->getMessage());
1314  if ($this->exceptions) {
1315  throw $exc;
1316  }
1317  }
1318  return false;
1319  }
1320 
1321  /**
1322  * Send mail using the $Sendmail program.
1323  * @param string $header The message headers
1324  * @param string $body The message body
1325  * @see PHPMailer::$Sendmail
1326  * @throws phpmailerException
1327  * @access protected
1328  * @return boolean
1329  */
1330  protected function sendmailSend($header, $body)
1331  {
1332  // CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped.
1333  if (!empty($this->Sender) and self::isShellSafe($this->Sender)) {
1334  if ($this->Mailer == 'qmail') {
1335  $sendmailFmt = '%s -f%s';
1336  } else {
1337  $sendmailFmt = '%s -oi -f%s -t';
1338  }
1339  } else {
1340  if ($this->Mailer == 'qmail') {
1341  $sendmailFmt = '%s';
1342  } else {
1343  $sendmailFmt = '%s -oi -t';
1344  }
1345  }
1346 
1347  // TODO: If possible, this should be changed to escapeshellarg. Needs thorough testing.
1348  $sendmail = sprintf($sendmailFmt, escapeshellcmd($this->Sendmail), $this->Sender);
1349 
1350  if ($this->SingleTo) {
1351  foreach ($this->SingleToArray as $toAddr) {
1352  if (!@$mail = popen($sendmail, 'w')) {
1353  throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1354  }
1355  fputs($mail, 'To: ' . $toAddr . "\n");
1356  fputs($mail, $header);
1357  fputs($mail, $body);
1358  $result = pclose($mail);
1359  $this->doCallback(
1360  ($result == 0),
1361  array($toAddr),
1362  $this->cc,
1363  $this->bcc,
1364  $this->Subject,
1365  $body,
1366  $this->From
1367  );
1368  if ($result != 0) {
1369  throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1370  }
1371  }
1372  } else {
1373  if (!@$mail = popen($sendmail, 'w')) {
1374  throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1375  }
1376  fputs($mail, $header);
1377  fputs($mail, $body);
1378  $result = pclose($mail);
1379  $this->doCallback(
1380  ($result == 0),
1381  $this->to,
1382  $this->cc,
1383  $this->bcc,
1384  $this->Subject,
1385  $body,
1386  $this->From
1387  );
1388  if ($result != 0) {
1389  throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1390  }
1391  }
1392  return true;
1393  }
1394 
1395  /**
1396  * Fix CVE-2016-10033 and CVE-2016-10045 by disallowing potentially unsafe shell characters.
1397  *
1398  * Note that escapeshellarg and escapeshellcmd are inadequate for our purposes, especially on Windows.
1399  * @param string $string The string to be validated
1400  * @see https://github.com/PHPMailer/PHPMailer/issues/924 CVE-2016-10045 bug report
1401  * @access protected
1402  * @return boolean
1403  */
1404  protected static function isShellSafe($string)
1405  {
1406  // Future-proof
1407  if (escapeshellcmd($string) !== $string or !in_array(escapeshellarg($string), array("'$string'", "\"$string\""))) {
1408  return false;
1409  }
1410 
1411  $length = strlen($string);
1412 
1413  for ($i = 0; $i < $length; $i++) {
1414  $c = $string[$i];
1415 
1416  // All other characters have a special meaning in at least one common shell, including = and +.
1417  // Full stop (.) has a special meaning in cmd.exe, but its impact should be negligible here.
1418  // Note that this does permit non-Latin alphanumeric characters based on the current locale.
1419  if (!ctype_alnum($c) && strpos('@_-.', $c) === false) {
1420  return false;
1421  }
1422  }
1423 
1424  return true;
1425  }
1426 
1427  /**
1428  * Send mail using the PHP mail() function.
1429  * @param string $header The message headers
1430  * @param string $body The message body
1431  * @link http://www.php.net/manual/en/book.mail.php
1432  * @throws phpmailerException
1433  * @access protected
1434  * @return boolean
1435  */
1436  protected function mailSend($header, $body)
1437  {
1438  $toArr = array();
1439  foreach ($this->to as $toaddr) {
1440  $toArr[] = $this->addrFormat($toaddr);
1441  }
1442  $to = implode(', ', $toArr);
1443 
1444  $params = null;
1445  if (!empty($this->Sender) and $this->validateAddress($this->Sender)) {
1446  // CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped.
1447  if (self::isShellSafe($this->Sender)) {
1448  $params = sprintf('-f%s', $this->Sender);
1449  }
1450  }
1451  if (!empty($this->Sender) and !ini_get('safe_mode') and $this->validateAddress($this->Sender)) {
1452  $old_from = ini_get('sendmail_from');
1453  ini_set('sendmail_from', $this->Sender);
1454  }
1455  $result = false;
1456  if ($this->SingleTo && count($toArr) > 1) {
1457  foreach ($toArr as $toAddr) {
1458  $result = $this->mailPassthru($toAddr, $this->Subject, $body, $header, $params);
1459  $this->doCallback($result, array($toAddr), $this->cc, $this->bcc, $this->Subject, $body, $this->From);
1460  }
1461  } else {
1462  $result = $this->mailPassthru($to, $this->Subject, $body, $header, $params);
1463  $this->doCallback($result, $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From);
1464  }
1465  if (isset($old_from)) {
1466  ini_set('sendmail_from', $old_from);
1467  }
1468  if (!$result) {
1469  throw new phpmailerException($this->lang('instantiate'), self::STOP_CRITICAL);
1470  }
1471  return true;
1472  }
1473 
1474  /**
1475  * Get an instance to use for SMTP operations.
1476  * Override this function to load your own SMTP implementation
1477  * @return SMTP
1478  */
1479  public function getSMTPInstance()
1480  {
1481  if (!is_object($this->smtp)) {
1482  $this->smtp = new SMTP;
1483  }
1484  return $this->smtp;
1485  }
1486 
1487  /**
1488  * Send mail via SMTP.
1489  * Returns false if there is a bad MAIL FROM, RCPT, or DATA input.
1490  * Uses the PHPMailerSMTP class by default.
1491  * @see PHPMailer::getSMTPInstance() to use a different class.
1492  * @param string $header The message headers
1493  * @param string $body The message body
1494  * @throws phpmailerException
1495  * @uses SMTP
1496  * @access protected
1497  * @return boolean
1498  */
1499  protected function smtpSend($header, $body)
1500  {
1501  $bad_rcpt = array();
1502  if (!$this->smtpConnect($this->SMTPOptions)) {
1503  throw new phpmailerException($this->lang('smtp_connect_failed'), self::STOP_CRITICAL);
1504  }
1505  if (!empty($this->Sender) and $this->validateAddress($this->Sender)) {
1506  $smtp_from = $this->Sender;
1507  } else {
1508  $smtp_from = $this->From;
1509  }
1510  if (!$this->smtp->mail($smtp_from)) {
1511  $this->setError($this->lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp->getError()));
1512  throw new phpmailerException($this->ErrorInfo, self::STOP_CRITICAL);
1513  }
1514 
1515  // Attempt to send to all recipients
1516  foreach (array($this->to, $this->cc, $this->bcc) as $togroup) {
1517  foreach ($togroup as $to) {
1518  if (!$this->smtp->recipient($to[0])) {
1519  $error = $this->smtp->getError();
1520  $bad_rcpt[] = array('to' => $to[0], 'error' => $error['detail']);
1521  $isSent = false;
1522  } else {
1523  $isSent = true;
1524  }
1525  $this->doCallback($isSent, array($to[0]), array(), array(), $this->Subject, $body, $this->From);
1526  }
1527  }
1528 
1529  // Only send the DATA command if we have viable recipients
1530  if ((count($this->all_recipients) > count($bad_rcpt)) and !$this->smtp->data($header . $body)) {
1531  throw new phpmailerException($this->lang('data_not_accepted'), self::STOP_CRITICAL);
1532  }
1533  if ($this->SMTPKeepAlive) {
1534  $this->smtp->reset();
1535  } else {
1536  $this->smtp->quit();
1537  $this->smtp->close();
1538  }
1539  //Create error message for any bad addresses
1540  if (count($bad_rcpt) > 0) {
1541  $errstr = '';
1542  foreach ($bad_rcpt as $bad) {
1543  $errstr .= $bad['to'] . ': ' . $bad['error'];
1544  }
1545  throw new phpmailerException(
1546  $this->lang('recipients_failed') . $errstr,
1547  self::STOP_CONTINUE
1548  );
1549  }
1550  return true;
1551  }
1552 
1553  /**
1554  * Initiate a connection to an SMTP server.
1555  * Returns false if the operation failed.
1556  * @param array $options An array of options compatible with stream_context_create()
1557  * @uses SMTP
1558  * @access public
1559  * @throws phpmailerException
1560  * @return boolean
1561  */
1562  public function smtpConnect($options = array())
1563  {
1564  if (is_null($this->smtp)) {
1565  $this->smtp = $this->getSMTPInstance();
1566  }
1567 
1568  // Already connected?
1569  if ($this->smtp->connected()) {
1570  return true;
1571  }
1572 
1573  $this->smtp->setTimeout($this->Timeout);
1574  $this->smtp->setDebugLevel($this->SMTPDebug);
1575  $this->smtp->setDebugOutput($this->Debugoutput);
1576  $this->smtp->setVerp($this->do_verp);
1577  $hosts = explode(';', $this->Host);
1578  $lastexception = null;
1579 
1580  foreach ($hosts as $hostentry) {
1581  $hostinfo = array();
1582  if (!preg_match('/^((ssl|tls):\/\/)*([a-zA-Z0-9\.-]*):?([0-9]*)$/', trim($hostentry), $hostinfo)) {
1583  // Not a valid host entry
1584  continue;
1585  }
1586  // $hostinfo[2]: optional ssl or tls prefix
1587  // $hostinfo[3]: the hostname
1588  // $hostinfo[4]: optional port number
1589  // The host string prefix can temporarily override the current setting for SMTPSecure
1590  // If it's not specified, the default value is used
1591  $prefix = '';
1592  $secure = $this->SMTPSecure;
1593  $tls = ($this->SMTPSecure == 'tls');
1594  if ('ssl' == $hostinfo[2] or ('' == $hostinfo[2] and 'ssl' == $this->SMTPSecure)) {
1595  $prefix = 'ssl://';
1596  $tls = false; // Can't have SSL and TLS at the same time
1597  $secure = 'ssl';
1598  } elseif ($hostinfo[2] == 'tls') {
1599  $tls = true;
1600  // tls doesn't use a prefix
1601  $secure = 'tls';
1602  }
1603  //Do we need the OpenSSL extension?
1604  $sslext = defined('OPENSSL_ALGO_SHA1');
1605  if ('tls' === $secure or 'ssl' === $secure) {
1606  //Check for an OpenSSL constant rather than using extension_loaded, which is sometimes disabled
1607  if (!$sslext) {
1608  throw new phpmailerException($this->lang('extension_missing').'openssl', self::STOP_CRITICAL);
1609  }
1610  }
1611  $host = $hostinfo[3];
1612  $port = $this->Port;
1613  $tport = (integer)$hostinfo[4];
1614  if ($tport > 0 and $tport < 65536) {
1615  $port = $tport;
1616  }
1617  if ($this->smtp->connect($prefix . $host, $port, $this->Timeout, $options)) {
1618  try {
1619  if ($this->Helo) {
1620  $hello = $this->Helo;
1621  } else {
1622  $hello = $this->serverHostname();
1623  }
1624  $this->smtp->hello($hello);
1625  //Automatically enable TLS encryption if:
1626  // * it's not disabled
1627  // * we have openssl extension
1628  // * we are not already using SSL
1629  // * the server offers STARTTLS
1630  if ($this->SMTPAutoTLS and $sslext and $secure != 'ssl' and $this->smtp->getServerExt('STARTTLS')) {
1631  $tls = true;
1632  }
1633  if ($tls) {
1634  if (!$this->smtp->startTLS()) {
1635  throw new phpmailerException($this->lang('connect_host'));
1636  }
1637  // We must resend HELO after tls negotiation
1638  $this->smtp->hello($hello);
1639  }
1640  if ($this->SMTPAuth) {
1641  if (!$this->smtp->authenticate(
1642  $this->Username,
1643  $this->Password,
1644  $this->AuthType,
1645  $this->Realm,
1646  $this->Workstation
1647  )
1648  ) {
1649  throw new phpmailerException($this->lang('authenticate'));
1650  }
1651  }
1652  return true;
1653  } catch (phpmailerException $exc) {
1654  $lastexception = $exc;
1655  $this->edebug($exc->getMessage());
1656  // We must have connected, but then failed TLS or Auth, so close connection nicely
1657  $this->smtp->quit();
1658  }
1659  }
1660  }
1661  // If we get here, all connection attempts have failed, so close connection hard
1662  $this->smtp->close();
1663  // As we've caught all exceptions, just report whatever the last one was
1664  if ($this->exceptions and !is_null($lastexception)) {
1665  throw $lastexception;
1666  }
1667  return false;
1668  }
1669 
1670  /**
1671  * Close the active SMTP session if one exists.
1672  * @return void
1673  */
1674  public function smtpClose()
1675  {
1676  if ($this->smtp !== null) {
1677  if ($this->smtp->connected()) {
1678  $this->smtp->quit();
1679  $this->smtp->close();
1680  }
1681  }
1682  }
1683 
1684  /**
1685  * Set the language for error messages.
1686  * Returns false if it cannot load the language file.
1687  * The default language is English.
1688  * @param string $langcode ISO 639-1 2-character language code (e.g. French is "fr")
1689  * @param string $lang_path Path to the language file directory, with trailing separator (slash)
1690  * @return boolean
1691  * @access public
1692  */
1693  public function setLanguage($langcode = 'en', $lang_path = '')
1694  {
1695  // Define full set of translatable strings in English
1696  $PHPMAILER_LANG = array(
1697  'authenticate' => 'SMTP Error: Could not authenticate.',
1698  'connect_host' => 'SMTP Error: Could not connect to SMTP host.',
1699  'data_not_accepted' => 'SMTP Error: data not accepted.',
1700  'empty_message' => 'Message body empty',
1701  'encoding' => 'Unknown encoding: ',
1702  'execute' => 'Could not execute: ',
1703  'file_access' => 'Could not access file: ',
1704  'file_open' => 'File Error: Could not open file: ',
1705  'from_failed' => 'The following From address failed: ',
1706  'instantiate' => 'Could not instantiate mail function.',
1707  'invalid_address' => 'Invalid address: ',
1708  'mailer_not_supported' => ' mailer is not supported.',
1709  'provide_address' => 'You must provide at least one recipient email address.',
1710  'recipients_failed' => 'SMTP Error: The following recipients failed: ',
1711  'signing' => 'Signing Error: ',
1712  'smtp_connect_failed' => 'SMTP connect() failed.',
1713  'smtp_error' => 'SMTP server error: ',
1714  'variable_set' => 'Cannot set or reset variable: ',
1715  'extension_missing' => 'Extension missing: '
1716  );
1717  if (empty($lang_path)) {
1718  // Calculate an absolute path so it can work if CWD is not here
1719  $lang_path = dirname(__FILE__). DIRECTORY_SEPARATOR . 'language'. DIRECTORY_SEPARATOR;
1720  }
1721  $foundlang = true;
1722  $lang_file = $lang_path . 'phpmailer.lang-' . $langcode . '.php';
1723  // There is no English translation file
1724  if ($langcode != 'en') {
1725  // Make sure language file path is readable
1726  if (!is_readable($lang_file)) {
1727  $foundlang = false;
1728  } else {
1729  // Overwrite language-specific strings.
1730  // This way we'll never have missing translation keys.
1731  $foundlang = include $lang_file;
1732  }
1733  }
1734  $this->language = $PHPMAILER_LANG;
1735  return (boolean)$foundlang; // Returns false if language not found
1736  }
1737 
1738  /**
1739  * Get the array of strings for the current language.
1740  * @return array
1741  */
1742  public function getTranslations()
1743  {
1744  return $this->language;
1745  }
1746 
1747  /**
1748  * Create recipient headers.
1749  * @access public
1750  * @param string $type
1751  * @param array $addr An array of recipient,
1752  * where each recipient is a 2-element indexed array with element 0 containing an address
1753  * and element 1 containing a name, like:
1754  * array(array('joe@example.com', 'Joe User'), array('zoe@example.com', 'Zoe User'))
1755  * @return string
1756  */
1757  public function addrAppend($type, $addr)
1758  {
1759  $addresses = array();
1760  foreach ($addr as $address) {
1761  $addresses[] = $this->addrFormat($address);
1762  }
1763  return $type . ': ' . implode(', ', $addresses) . $this->LE;
1764  }
1765 
1766  /**
1767  * Format an address for use in a message header.
1768  * @access public
1769  * @param array $addr A 2-element indexed array, element 0 containing an address, element 1 containing a name
1770  * like array('joe@example.com', 'Joe User')
1771  * @return string
1772  */
1773  public function addrFormat($addr)
1774  {
1775  if (empty($addr[1])) { // No name provided
1776  return $this->secureHeader($addr[0]);
1777  } else {
1778  return $this->encodeHeader($this->secureHeader($addr[1]), 'phrase') . ' <' . $this->secureHeader(
1779  $addr[0]
1780  ) . '>';
1781  }
1782  }
1783 
1784  /**
1785  * Word-wrap message.
1786  * For use with mailers that do not automatically perform wrapping
1787  * and for quoted-printable encoded messages.
1788  * Original written by philippe.
1789  * @param string $message The message to wrap
1790  * @param integer $length The line length to wrap to
1791  * @param boolean $qp_mode Whether to run in Quoted-Printable mode
1792  * @access public
1793  * @return string
1794  */
1795  public function wrapText($message, $length, $qp_mode = false)
1796  {
1797  if ($qp_mode) {
1798  $soft_break = sprintf(' =%s', $this->LE);
1799  } else {
1800  $soft_break = $this->LE;
1801  }
1802  // If utf-8 encoding is used, we will need to make sure we don't
1803  // split multibyte characters when we wrap
1804  $is_utf8 = (strtolower($this->CharSet) == 'utf-8');
1805  $lelen = strlen($this->LE);
1806  $crlflen = strlen(self::CRLF);
1807 
1808  $message = $this->fixEOL($message);
1809  //Remove a trailing line break
1810  if (substr($message, -$lelen) == $this->LE) {
1811  $message = substr($message, 0, -$lelen);
1812  }
1813 
1814  //Split message into lines
1815  $lines = explode($this->LE, $message);
1816  //Message will be rebuilt in here
1817  $message = '';
1818  foreach ($lines as $line) {
1819  $words = explode(' ', $line);
1820  $buf = '';
1821  $firstword = true;
1822  foreach ($words as $word) {
1823  if ($qp_mode and (strlen($word) > $length)) {
1824  $space_left = $length - strlen($buf) - $crlflen;
1825  if (!$firstword) {
1826  if ($space_left > 20) {
1827  $len = $space_left;
1828  if ($is_utf8) {
1829  $len = $this->utf8CharBoundary($word, $len);
1830  } elseif (substr($word, $len - 1, 1) == '=') {
1831  $len--;
1832  } elseif (substr($word, $len - 2, 1) == '=') {
1833  $len -= 2;
1834  }
1835  $part = substr($word, 0, $len);
1836  $word = substr($word, $len);
1837  $buf .= ' ' . $part;
1838  $message .= $buf . sprintf('=%s', self::CRLF);
1839  } else {
1840  $message .= $buf . $soft_break;
1841  }
1842  $buf = '';
1843  }
1844  while (strlen($word) > 0) {
1845  if ($length <= 0) {
1846  break;
1847  }
1848  $len = $length;
1849  if ($is_utf8) {
1850  $len = $this->utf8CharBoundary($word, $len);
1851  } elseif (substr($word, $len - 1, 1) == '=') {
1852  $len--;
1853  } elseif (substr($word, $len - 2, 1) == '=') {
1854  $len -= 2;
1855  }
1856  $part = substr($word, 0, $len);
1857  $word = substr($word, $len);
1858 
1859  if (strlen($word) > 0) {
1860  $message .= $part . sprintf('=%s', self::CRLF);
1861  } else {
1862  $buf = $part;
1863  }
1864  }
1865  } else {
1866  $buf_o = $buf;
1867  if (!$firstword) {
1868  $buf .= ' ';
1869  }
1870  $buf .= $word;
1871 
1872  if (strlen($buf) > $length and $buf_o != '') {
1873  $message .= $buf_o . $soft_break;
1874  $buf = $word;
1875  }
1876  }
1877  $firstword = false;
1878  }
1879  $message .= $buf . self::CRLF;
1880  }
1881 
1882  return $message;
1883  }
1884 
1885  /**
1886  * Find the last character boundary prior to $maxLength in a utf-8
1887  * quoted-printable encoded string.
1888  * Original written by Colin Brown.
1889  * @access public
1890  * @param string $encodedText utf-8 QP text
1891  * @param integer $maxLength Find the last character boundary prior to this length
1892  * @return integer
1893  */
1894  public function utf8CharBoundary($encodedText, $maxLength)
1895  {
1896  $foundSplitPos = false;
1897  $lookBack = 3;
1898  while (!$foundSplitPos) {
1899  $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
1900  $encodedCharPos = strpos($lastChunk, '=');
1901  if (false !== $encodedCharPos) {
1902  // Found start of encoded character byte within $lookBack block.
1903  // Check the encoded byte value (the 2 chars after the '=')
1904  $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
1905  $dec = hexdec($hex);
1906  if ($dec < 128) {
1907  // Single byte character.
1908  // If the encoded char was found at pos 0, it will fit
1909  // otherwise reduce maxLength to start of the encoded char
1910  if ($encodedCharPos > 0) {
1911  $maxLength = $maxLength - ($lookBack - $encodedCharPos);
1912  }
1913  $foundSplitPos = true;
1914  } elseif ($dec >= 192) {
1915  // First byte of a multi byte character
1916  // Reduce maxLength to split at start of character
1917  $maxLength = $maxLength - ($lookBack - $encodedCharPos);
1918  $foundSplitPos = true;
1919  } elseif ($dec < 192) {
1920  // Middle byte of a multi byte character, look further back
1921  $lookBack += 3;
1922  }
1923  } else {
1924  // No encoded character found
1925  $foundSplitPos = true;
1926  }
1927  }
1928  return $maxLength;
1929  }
1930 
1931  /**
1932  * Apply word wrapping to the message body.
1933  * Wraps the message body to the number of chars set in the WordWrap property.
1934  * You should only do this to plain-text bodies as wrapping HTML tags may break them.
1935  * This is called automatically by createBody(), so you don't need to call it yourself.
1936  * @access public
1937  * @return void
1938  */
1939  public function setWordWrap()
1940  {
1941  if ($this->WordWrap < 1) {
1942  return;
1943  }
1944 
1945  switch ($this->message_type) {
1946  case 'alt':
1947  case 'alt_inline':
1948  case 'alt_attach':
1949  case 'alt_inline_attach':
1950  $this->AltBody = $this->wrapText($this->AltBody, $this->WordWrap);
1951  break;
1952  default:
1953  $this->Body = $this->wrapText($this->Body, $this->WordWrap);
1954  break;
1955  }
1956  }
1957 
1958  /**
1959  * Assemble message headers.
1960  * @access public
1961  * @return string The assembled headers
1962  */
1963  public function createHeader()
1964  {
1965  $result = '';
1966 
1967  if ($this->MessageDate == '') {
1968  $this->MessageDate = self::rfcDate();
1969  }
1970  $result .= $this->headerLine('Date', $this->MessageDate);
1971 
1972  // To be created automatically by mail()
1973  if ($this->SingleTo) {
1974  if ($this->Mailer != 'mail') {
1975  foreach ($this->to as $toaddr) {
1976  $this->SingleToArray[] = $this->addrFormat($toaddr);
1977  }
1978  }
1979  } else {
1980  if (count($this->to) > 0) {
1981  if ($this->Mailer != 'mail') {
1982  $result .= $this->addrAppend('To', $this->to);
1983  }
1984  } elseif (count($this->cc) == 0) {
1985  $result .= $this->headerLine('To', 'undisclosed-recipients:;');
1986  }
1987  }
1988 
1989  $result .= $this->addrAppend('From', array(array(trim($this->From), $this->FromName)));
1990 
1991  // sendmail and mail() extract Cc from the header before sending
1992  if (count($this->cc) > 0) {
1993  $result .= $this->addrAppend('Cc', $this->cc);
1994  }
1995 
1996  // sendmail and mail() extract Bcc from the header before sending
1997  if ((
1998  $this->Mailer == 'sendmail' or $this->Mailer == 'qmail' or $this->Mailer == 'mail'
1999  )
2000  and count($this->bcc) > 0
2001  ) {
2002  $result .= $this->addrAppend('Bcc', $this->bcc);
2003  }
2004 
2005  if (count($this->ReplyTo) > 0) {
2006  $result .= $this->addrAppend('Reply-To', $this->ReplyTo);
2007  }
2008 
2009  // mail() sets the subject itself
2010  if ($this->Mailer != 'mail') {
2011  $result .= $this->headerLine('Subject', $this->encodeHeader($this->secureHeader($this->Subject)));
2012  }
2013 
2014  if ($this->MessageID != '') {
2015  $this->lastMessageID = $this->MessageID;
2016  } else {
2017  $this->lastMessageID = sprintf('<%s@%s>', $this->uniqueid, $this->serverHostname());
2018  }
2019  $result .= $this->headerLine('Message-ID', $this->lastMessageID);
2020  if (!is_null($this->Priority)) {
2021  $result .= $this->headerLine('X-Priority', $this->Priority);
2022  }
2023  if ($this->XMailer == '') {
2024  $result .= $this->headerLine(
2025  'X-Mailer',
2026  'PHPMailer ' . $this->Version . ' (https://github.com/PHPMailer/PHPMailer)'
2027  );
2028  } else {
2029  $myXmailer = trim($this->XMailer);
2030  if ($myXmailer) {
2031  $result .= $this->headerLine('X-Mailer', $myXmailer);
2032  }
2033  }
2034 
2035  if ($this->ConfirmReadingTo != '') {
2036  $result .= $this->headerLine('Disposition-Notification-To', '<' . $this->ConfirmReadingTo . '>');
2037  }
2038 
2039  // Add custom headers
2040  foreach ($this->CustomHeader as $header) {
2041  $result .= $this->headerLine(
2042  trim($header[0]),
2043  $this->encodeHeader(trim($header[1]))
2044  );
2045  }
2046  if (!$this->sign_key_file) {
2047  $result .= $this->headerLine('MIME-Version', '1.0');
2048  $result .= $this->getMailMIME();
2049  }
2050 
2051  return $result;
2052  }
2053 
2054  /**
2055  * Get the message MIME type headers.
2056  * @access public
2057  * @return string
2058  */
2059  public function getMailMIME()
2060  {
2061  $result = '';
2062  $ismultipart = true;
2063  switch ($this->message_type) {
2064  case 'inline':
2065  $result .= $this->headerLine('Content-Type', 'multipart/related;');
2066  $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
2067  break;
2068  case 'attach':
2069  case 'inline_attach':
2070  case 'alt_attach':
2071  case 'alt_inline_attach':
2072  $result .= $this->headerLine('Content-Type', 'multipart/mixed;');
2073  $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
2074  break;
2075  case 'alt':
2076  case 'alt_inline':
2077  $result .= $this->headerLine('Content-Type', 'multipart/alternative;');
2078  $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
2079  break;
2080  default:
2081  // Catches case 'plain': and case '':
2082  $result .= $this->textLine('Content-Type: ' . $this->ContentType . '; charset=' . $this->CharSet);
2083  $ismultipart = false;
2084  break;
2085  }
2086  // RFC1341 part 5 says 7bit is assumed if not specified
2087  if ($this->Encoding != '7bit') {
2088  // RFC 2045 section 6.4 says multipart MIME parts may only use 7bit, 8bit or binary CTE
2089  if ($ismultipart) {
2090  if ($this->Encoding == '8bit') {
2091  $result .= $this->headerLine('Content-Transfer-Encoding', '8bit');
2092  }
2093  // The only remaining alternatives are quoted-printable and base64, which are both 7bit compatible
2094  } else {
2095  $result .= $this->headerLine('Content-Transfer-Encoding', $this->Encoding);
2096  }
2097  }
2098 
2099  if ($this->Mailer != 'mail') {
2100  $result .= $this->LE;
2101  }
2102 
2103  return $result;
2104  }
2105 
2106  /**
2107  * Returns the whole MIME message.
2108  * Includes complete headers and body.
2109  * Only valid post preSend().
2110  * @see PHPMailer::preSend()
2111  * @access public
2112  * @return string
2113  */
2114  public function getSentMIMEMessage()
2115  {
2116  return $this->MIMEHeader . $this->mailHeader . self::CRLF . $this->MIMEBody;
2117  }
2118 
2119  /**
2120  * Assemble the message body.
2121  * Returns an empty string on failure.
2122  * @access public
2123  * @throws phpmailerException
2124  * @return string The assembled message body
2125  */
2126  public function createBody()
2127  {
2128  $body = '';
2129  //Create unique IDs and preset boundaries
2130  $this->uniqueid = md5(uniqid(time()));
2131  $this->boundary[1] = 'b1_' . $this->uniqueid;
2132  $this->boundary[2] = 'b2_' . $this->uniqueid;
2133  $this->boundary[3] = 'b3_' . $this->uniqueid;
2134 
2135  if ($this->sign_key_file) {
2136  $body .= $this->getMailMIME() . $this->LE;
2137  }
2138 
2139  $this->setWordWrap();
2140 
2141  $bodyEncoding = $this->Encoding;
2142  $bodyCharSet = $this->CharSet;
2143  //Can we do a 7-bit downgrade?
2144  if ($bodyEncoding == '8bit' and !$this->has8bitChars($this->Body)) {
2145  $bodyEncoding = '7bit';
2146  $bodyCharSet = 'us-ascii';
2147  }
2148  //If lines are too long, and we're not already using an encoding that will shorten them,
2149  //change to quoted-printable transfer encoding
2150  if ('base64' != $this->Encoding and self::hasLineLongerThanMax($this->Body)) {
2151  $this->Encoding = 'quoted-printable';
2152  $bodyEncoding = 'quoted-printable';
2153  }
2154 
2155  $altBodyEncoding = $this->Encoding;
2156  $altBodyCharSet = $this->CharSet;
2157  //Can we do a 7-bit downgrade?
2158  if ($altBodyEncoding == '8bit' and !$this->has8bitChars($this->AltBody)) {
2159  $altBodyEncoding = '7bit';
2160  $altBodyCharSet = 'us-ascii';
2161  }
2162  //If lines are too long, change to quoted-printable transfer encoding
2163  if (self::hasLineLongerThanMax($this->AltBody)) {
2164  $altBodyEncoding = 'quoted-printable';
2165  }
2166  //Use this as a preamble in all multipart message types
2167  $mimepre = "This is a multi-part message in MIME format." . $this->LE . $this->LE;
2168  switch ($this->message_type) {
2169  case 'inline':
2170  $body .= $mimepre;
2171  $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
2172  $body .= $this->encodeString($this->Body, $bodyEncoding);
2173  $body .= $this->LE . $this->LE;
2174  $body .= $this->attachAll('inline', $this->boundary[1]);
2175  break;
2176  case 'attach':
2177  $body .= $mimepre;
2178  $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
2179  $body .= $this->encodeString($this->Body, $bodyEncoding);
2180  $body .= $this->LE . $this->LE;
2181  $body .= $this->attachAll('attachment', $this->boundary[1]);
2182  break;
2183  case 'inline_attach':
2184  $body .= $mimepre;
2185  $body .= $this->textLine('--' . $this->boundary[1]);
2186  $body .= $this->headerLine('Content-Type', 'multipart/related;');
2187  $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
2188  $body .= $this->LE;
2189  $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, '', $bodyEncoding);
2190  $body .= $this->encodeString($this->Body, $bodyEncoding);
2191  $body .= $this->LE . $this->LE;
2192  $body .= $this->attachAll('inline', $this->boundary[2]);
2193  $body .= $this->LE;
2194  $body .= $this->attachAll('attachment', $this->boundary[1]);
2195  break;
2196  case 'alt':
2197  $body .= $mimepre;
2198  $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, 'text/plain', $altBodyEncoding);
2199  $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
2200  $body .= $this->LE . $this->LE;
2201  $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, 'text/html', $bodyEncoding);
2202  $body .= $this->encodeString($this->Body, $bodyEncoding);
2203  $body .= $this->LE . $this->LE;
2204  if (!empty($this->Ical)) {
2205  $body .= $this->getBoundary($this->boundary[1], '', 'text/calendar; method=REQUEST', '');
2206  $body .= $this->encodeString($this->Ical, $this->Encoding);
2207  $body .= $this->LE . $this->LE;
2208  }
2209  $body .= $this->endBoundary($this->boundary[1]);
2210  break;
2211  case 'alt_inline':
2212  $body .= $mimepre;
2213  $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, 'text/plain', $altBodyEncoding);
2214  $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
2215  $body .= $this->LE . $this->LE;
2216  $body .= $this->textLine('--' . $this->boundary[1]);
2217  $body .= $this->headerLine('Content-Type', 'multipart/related;');
2218  $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
2219  $body .= $this->LE;
2220  $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, 'text/html', $bodyEncoding);
2221  $body .= $this->encodeString($this->Body, $bodyEncoding);
2222  $body .= $this->LE . $this->LE;
2223  $body .= $this->attachAll('inline', $this->boundary[2]);
2224  $body .= $this->LE;
2225  $body .= $this->endBoundary($this->boundary[1]);
2226  break;
2227  case 'alt_attach':
2228  $body .= $mimepre;
2229  $body .= $this->textLine('--' . $this->boundary[1]);
2230  $body .= $this->headerLine('Content-Type', 'multipart/alternative;');
2231  $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
2232  $body .= $this->LE;
2233  $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, 'text/plain', $altBodyEncoding);
2234  $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
2235  $body .= $this->LE . $this->LE;
2236  $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, 'text/html', $bodyEncoding);
2237  $body .= $this->encodeString($this->Body, $bodyEncoding);
2238  $body .= $this->LE . $this->LE;
2239  $body .= $this->endBoundary($this->boundary[2]);
2240  $body .= $this->LE;
2241  $body .= $this->attachAll('attachment', $this->boundary[1]);
2242  break;
2243  case 'alt_inline_attach':
2244  $body .= $mimepre;
2245  $body .= $this->textLine('--' . $this->boundary[1]);
2246  $body .= $this->headerLine('Content-Type', 'multipart/alternative;');
2247  $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
2248  $body .= $this->LE;
2249  $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, 'text/plain', $altBodyEncoding);
2250  $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
2251  $body .= $this->LE . $this->LE;
2252  $body .= $this->textLine('--' . $this->boundary[2]);
2253  $body .= $this->headerLine('Content-Type', 'multipart/related;');
2254  $body .= $this->textLine("\tboundary=\"" . $this->boundary[3] . '"');
2255  $body .= $this->LE;
2256  $body .= $this->getBoundary($this->boundary[3], $bodyCharSet, 'text/html', $bodyEncoding);
2257  $body .= $this->encodeString($this->Body, $bodyEncoding);
2258  $body .= $this->LE . $this->LE;
2259  $body .= $this->attachAll('inline', $this->boundary[3]);
2260  $body .= $this->LE;
2261  $body .= $this->endBoundary($this->boundary[2]);
2262  $body .= $this->LE;
2263  $body .= $this->attachAll('attachment', $this->boundary[1]);
2264  break;
2265  default:
2266  // catch case 'plain' and case ''
2267  $body .= $this->encodeString($this->Body, $bodyEncoding);
2268  break;
2269  }
2270 
2271  if ($this->isError()) {
2272  $body = '';
2273  } elseif ($this->sign_key_file) {
2274  try {
2275  if (!defined('PKCS7_TEXT')) {
2276  throw new phpmailerException($this->lang('extension_missing') . 'openssl');
2277  }
2278  // @TODO would be nice to use php://temp streams here, but need to wrap for PHP < 5.1
2279  $file = tempnam(sys_get_temp_dir(), 'mail');
2280  if (false === file_put_contents($file, $body)) {
2281  throw new phpmailerException($this->lang('signing') . ' Could not write temp file');
2282  }
2283  $signed = tempnam(sys_get_temp_dir(), 'signed');
2284  //Workaround for PHP bug https://bugs.php.net/bug.php?id=69197
2285  if (empty($this->sign_extracerts_file)) {
2286  $sign = @openssl_pkcs7_sign(
2287  $file,
2288  $signed,
2289  'file://' . realpath($this->sign_cert_file),
2290  array('file://' . realpath($this->sign_key_file), $this->sign_key_pass),
2291  null
2292  );
2293  } else {
2294  $sign = @openssl_pkcs7_sign(
2295  $file,
2296  $signed,
2297  'file://' . realpath($this->sign_cert_file),
2298  array('file://' . realpath($this->sign_key_file), $this->sign_key_pass),
2299  null,
2300  PKCS7_DETACHED,
2301  $this->sign_extracerts_file
2302  );
2303  }
2304  if ($sign) {
2305  @unlink($file);
2306  $body = file_get_contents($signed);
2307  @unlink($signed);
2308  //The message returned by openssl contains both headers and body, so need to split them up
2309  $parts = explode("\n\n", $body, 2);
2310  $this->MIMEHeader .= $parts[0] . $this->LE . $this->LE;
2311  $body = $parts[1];
2312  } else {
2313  @unlink($file);
2314  @unlink($signed);
2315  throw new phpmailerException($this->lang('signing') . openssl_error_string());
2316  }
2317  } catch (phpmailerException $exc) {
2318  $body = '';
2319  if ($this->exceptions) {
2320  throw $exc;
2321  }
2322  }
2323  }
2324  return $body;
2325  }
2326 
2327  /**
2328  * Return the start of a message boundary.
2329  * @access protected
2330  * @param string $boundary
2331  * @param string $charSet
2332  * @param string $contentType
2333  * @param string $encoding
2334  * @return string
2335  */
2336  protected function getBoundary($boundary, $charSet, $contentType, $encoding)
2337  {
2338  $result = '';
2339  if ($charSet == '') {
2340  $charSet = $this->CharSet;
2341  }
2342  if ($contentType == '') {
2343  $contentType = $this->ContentType;
2344  }
2345  if ($encoding == '') {
2346  $encoding = $this->Encoding;
2347  }
2348  $result .= $this->textLine('--' . $boundary);
2349  $result .= sprintf('Content-Type: %s; charset=%s', $contentType, $charSet);
2350  $result .= $this->LE;
2351  // RFC1341 part 5 says 7bit is assumed if not specified
2352  if ($encoding != '7bit') {
2353  $result .= $this->headerLine('Content-Transfer-Encoding', $encoding);
2354  }
2355  $result .= $this->LE;
2356 
2357  return $result;
2358  }
2359 
2360  /**
2361  * Return the end of a message boundary.
2362  * @access protected
2363  * @param string $boundary
2364  * @return string
2365  */
2366  protected function endBoundary($boundary)
2367  {
2368  return $this->LE . '--' . $boundary . '--' . $this->LE;
2369  }
2370 
2371  /**
2372  * Set the message type.
2373  * PHPMailer only supports some preset message types,
2374  * not arbitrary MIME structures.
2375  * @access protected
2376  * @return void
2377  */
2378  protected function setMessageType()
2379  {
2380  $type = array();
2381  if ($this->alternativeExists()) {
2382  $type[] = 'alt';
2383  }
2384  if ($this->inlineImageExists()) {
2385  $type[] = 'inline';
2386  }
2387  if ($this->attachmentExists()) {
2388  $type[] = 'attach';
2389  }
2390  $this->message_type = implode('_', $type);
2391  if ($this->message_type == '') {
2392  $this->message_type = 'plain';
2393  }
2394  }
2395 
2396  /**
2397  * Format a header line.
2398  * @access public
2399  * @param string $name
2400  * @param string $value
2401  * @return string
2402  */
2403  public function headerLine($name, $value)
2404  {
2405  return $name . ': ' . $value . $this->LE;
2406  }
2407 
2408  /**
2409  * Return a formatted mail line.
2410  * @access public
2411  * @param string $value
2412  * @return string
2413  */
2414  public function textLine($value)
2415  {
2416  return $value . $this->LE;
2417  }
2418 
2419  /**
2420  * Add an attachment from a path on the filesystem.
2421  * Returns false if the file could not be found or read.
2422  * @param string $path Path to the attachment.
2423  * @param string $name Overrides the attachment name.
2424  * @param string $encoding File encoding (see $Encoding).
2425  * @param string $type File extension (MIME) type.
2426  * @param string $disposition Disposition to use
2427  * @throws phpmailerException
2428  * @return boolean
2429  */
2430  public function addAttachment($path, $name = '', $encoding = 'base64', $type = '', $disposition = 'attachment')
2431  {
2432  try {
2433  if (!@is_file($path)) {
2434  throw new phpmailerException($this->lang('file_access') . $path, self::STOP_CONTINUE);
2435  }
2436 
2437  // If a MIME type is not specified, try to work it out from the file name
2438  if ($type == '') {
2439  $type = self::filenameToType($path);
2440  }
2441 
2442  $filename = basename($path);
2443  if ($name == '') {
2444  $name = $filename;
2445  }
2446 
2447  $this->attachment[] = array(
2448  0 => $path,
2449  1 => $filename,
2450  2 => $name,
2451  3 => $encoding,
2452  4 => $type,
2453  5 => false, // isStringAttachment
2454  6 => $disposition,
2455  7 => 0
2456  );
2457 
2458  } catch (phpmailerException $exc) {
2459  $this->setError($exc->getMessage());
2460  $this->edebug($exc->getMessage());
2461  if ($this->exceptions) {
2462  throw $exc;
2463  }
2464  return false;
2465  }
2466  return true;
2467  }
2468 
2469  /**
2470  * Return the array of attachments.
2471  * @return array
2472  */
2473  public function getAttachments()
2474  {
2475  return $this->attachment;
2476  }
2477 
2478  /**
2479  * Attach all file, string, and binary attachments to the message.
2480  * Returns an empty string on failure.
2481  * @access protected
2482  * @param string $disposition_type
2483  * @param string $boundary
2484  * @return string
2485  */
2486  protected function attachAll($disposition_type, $boundary)
2487  {
2488  // Return text of body
2489  $mime = array();
2490  $cidUniq = array();
2491  $incl = array();
2492 
2493  // Add all attachments
2494  foreach ($this->attachment as $attachment) {
2495  // Check if it is a valid disposition_filter
2496  if ($attachment[6] == $disposition_type) {
2497  // Check for string attachment
2498  $string = '';
2499  $path = '';
2500  $bString = $attachment[5];
2501  if ($bString) {
2502  $string = $attachment[0];
2503  } else {
2504  $path = $attachment[0];
2505  }
2506 
2507  $inclhash = md5(serialize($attachment));
2508  if (in_array($inclhash, $incl)) {
2509  continue;
2510  }
2511  $incl[] = $inclhash;
2512  $name = $attachment[2];
2513  $encoding = $attachment[3];
2514  $type = $attachment[4];
2515  $disposition = $attachment[6];
2516  $cid = $attachment[7];
2517  if ($disposition == 'inline' && array_key_exists($cid, $cidUniq)) {
2518  continue;
2519  }
2520  $cidUniq[$cid] = true;
2521 
2522  $mime[] = sprintf('--%s%s', $boundary, $this->LE);
2523  //Only include a filename property if we have one
2524  if (!empty($name)) {
2525  $mime[] = sprintf(
2526  'Content-Type: %s; name="%s"%s',
2527  $type,
2528  $this->encodeHeader($this->secureHeader($name)),
2529  $this->LE
2530  );
2531  } else {
2532  $mime[] = sprintf(
2533  'Content-Type: %s%s',
2534  $type,
2535  $this->LE
2536  );
2537  }
2538  // RFC1341 part 5 says 7bit is assumed if not specified
2539  if ($encoding != '7bit') {
2540  $mime[] = sprintf('Content-Transfer-Encoding: %s%s', $encoding, $this->LE);
2541  }
2542 
2543  if ($disposition == 'inline') {
2544  $mime[] = sprintf('Content-ID: <%s>%s', $cid, $this->LE);
2545  }
2546 
2547  // If a filename contains any of these chars, it should be quoted,
2548  // but not otherwise: RFC2183 & RFC2045 5.1
2549  // Fixes a warning in IETF's msglint MIME checker
2550  // Allow for bypassing the Content-Disposition header totally
2551  if (!(empty($disposition))) {
2552  $encoded_name = $this->encodeHeader($this->secureHeader($name));
2553  if (preg_match('/[ \(\)<>@,;:\\"\/\[\]\?=]/', $encoded_name)) {
2554  $mime[] = sprintf(
2555  'Content-Disposition: %s; filename="%s"%s',
2556  $disposition,
2557  $encoded_name,
2558  $this->LE . $this->LE
2559  );
2560  } else {
2561  if (!empty($encoded_name)) {
2562  $mime[] = sprintf(
2563  'Content-Disposition: %s; filename=%s%s',
2564  $disposition,
2565  $encoded_name,
2566  $this->LE . $this->LE
2567  );
2568  } else {
2569  $mime[] = sprintf(
2570  'Content-Disposition: %s%s',
2571  $disposition,
2572  $this->LE . $this->LE
2573  );
2574  }
2575  }
2576  } else {
2577  $mime[] = $this->LE;
2578  }
2579 
2580  // Encode as string attachment
2581  if ($bString) {
2582  $mime[] = $this->encodeString($string, $encoding);
2583  if ($this->isError()) {
2584  return '';
2585  }
2586  $mime[] = $this->LE . $this->LE;
2587  } else {
2588  $mime[] = $this->encodeFile($path, $encoding);
2589  if ($this->isError()) {
2590  return '';
2591  }
2592  $mime[] = $this->LE . $this->LE;
2593  }
2594  }
2595  }
2596 
2597  $mime[] = sprintf('--%s--%s', $boundary, $this->LE);
2598 
2599  return implode('', $mime);
2600  }
2601 
2602  /**
2603  * Encode a file attachment in requested format.
2604  * Returns an empty string on failure.
2605  * @param string $path The full path to the file
2606  * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
2607  * @throws phpmailerException
2608  * @access protected
2609  * @return string
2610  */
2611  protected function encodeFile($path, $encoding = 'base64')
2612  {
2613  try {
2614  if (!is_readable($path)) {
2615  throw new phpmailerException($this->lang('file_open') . $path, self::STOP_CONTINUE);
2616  }
2617  $magic_quotes = get_magic_quotes_runtime();
2618  if ($magic_quotes) {
2619  if (version_compare(PHP_VERSION, '5.3.0', '<')) {
2620  set_magic_quotes_runtime(false);
2621  } else {
2622  //Doesn't exist in PHP 5.4, but we don't need to check because
2623  //get_magic_quotes_runtime always returns false in 5.4+
2624  //so it will never get here
2625  ini_set('magic_quotes_runtime', false);
2626  }
2627  }
2628  $file_buffer = file_get_contents($path);
2629  $file_buffer = $this->encodeString($file_buffer, $encoding);
2630  if ($magic_quotes) {
2631  if (version_compare(PHP_VERSION, '5.3.0', '<')) {
2632  set_magic_quotes_runtime($magic_quotes);
2633  } else {
2634  ini_set('magic_quotes_runtime', $magic_quotes);
2635  }
2636  }
2637  return $file_buffer;
2638  } catch (Exception $exc) {
2639  $this->setError($exc->getMessage());
2640  return '';
2641  }
2642  }
2643 
2644  /**
2645  * Encode a string in requested format.
2646  * Returns an empty string on failure.
2647  * @param string $str The text to encode
2648  * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
2649  * @access public
2650  * @return string
2651  */
2652  public function encodeString($str, $encoding = 'base64')
2653  {
2654  $encoded = '';
2655  switch (strtolower($encoding)) {
2656  case 'base64':
2657  $encoded = chunk_split(base64_encode($str), 76, $this->LE);
2658  break;
2659  case '7bit':
2660  case '8bit':
2661  $encoded = $this->fixEOL($str);
2662  // Make sure it ends with a line break
2663  if (substr($encoded, -(strlen($this->LE))) != $this->LE) {
2664  $encoded .= $this->LE;
2665  }
2666  break;
2667  case 'binary':
2668  $encoded = $str;
2669  break;
2670  case 'quoted-printable':
2671  $encoded = $this->encodeQP($str);
2672  break;
2673  default:
2674  $this->setError($this->lang('encoding') . $encoding);
2675  break;
2676  }
2677  return $encoded;
2678  }
2679 
2680  /**
2681  * Encode a header string optimally.
2682  * Picks shortest of Q, B, quoted-printable or none.
2683  * @access public
2684  * @param string $str
2685  * @param string $position
2686  * @return string
2687  */
2688  public function encodeHeader($str, $position = 'text')
2689  {
2690  $matchcount = 0;
2691  switch (strtolower($position)) {
2692  case 'phrase':
2693  if (!preg_match('/[\200-\377]/', $str)) {
2694  // Can't use addslashes as we don't know the value of magic_quotes_sybase
2695  $encoded = addcslashes($str, "\0..\37\177\\\"");
2696  if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
2697  return ($encoded);
2698  } else {
2699  return ("\"$encoded\"");
2700  }
2701  }
2702  $matchcount = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
2703  break;
2704  /** @noinspection PhpMissingBreakStatementInspection */
2705  case 'comment':
2706  $matchcount = preg_match_all('/[()"]/', $str, $matches);
2707  // Intentional fall-through
2708  case 'text':
2709  default:
2710  $matchcount += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
2711  break;
2712  }
2713 
2714  //There are no chars that need encoding
2715  if ($matchcount == 0) {
2716  return ($str);
2717  }
2718 
2719  $maxlen = 75 - 7 - strlen($this->CharSet);
2720  // Try to select the encoding which should produce the shortest output
2721  if ($matchcount > strlen($str) / 3) {
2722  // More than a third of the content will need encoding, so B encoding will be most efficient
2723  $encoding = 'B';
2724  if (function_exists('mb_strlen') && $this->hasMultiBytes($str)) {
2725  // Use a custom function which correctly encodes and wraps long
2726  // multibyte strings without breaking lines within a character
2727  $encoded = $this->base64EncodeWrapMB($str, "\n");
2728  } else {
2729  $encoded = base64_encode($str);
2730  $maxlen -= $maxlen % 4;
2731  $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
2732  }
2733  } else {
2734  $encoding = 'Q';
2735  $encoded = $this->encodeQ($str, $position);
2736  $encoded = $this->wrapText($encoded, $maxlen, true);
2737  $encoded = str_replace('=' . self::CRLF, "\n", trim($encoded));
2738  }
2739 
2740  $encoded = preg_replace('/^(.*)$/m', ' =?' . $this->CharSet . "?$encoding?\\1?=", $encoded);
2741  $encoded = trim(str_replace("\n", $this->LE, $encoded));
2742 
2743  return $encoded;
2744  }
2745 
2746  /**
2747  * Check if a string contains multi-byte characters.
2748  * @access public
2749  * @param string $str multi-byte text to wrap encode
2750  * @return boolean
2751  */
2752  public function hasMultiBytes($str)
2753  {
2754  if (function_exists('mb_strlen')) {
2755  return (strlen($str) > mb_strlen($str, $this->CharSet));
2756  } else { // Assume no multibytes (we can't handle without mbstring functions anyway)
2757  return false;
2758  }
2759  }
2760 
2761  /**
2762  * Does a string contain any 8-bit chars (in any charset)?
2763  * @param string $text
2764  * @return boolean
2765  */
2766  public function has8bitChars($text)
2767  {
2768  return (boolean)preg_match('/[\x80-\xFF]/', $text);
2769  }
2770 
2771  /**
2772  * Encode and wrap long multibyte strings for mail headers
2773  * without breaking lines within a character.
2774  * Adapted from a function by paravoid
2775  * @link http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283
2776  * @access public
2777  * @param string $str multi-byte text to wrap encode
2778  * @param string $linebreak string to use as linefeed/end-of-line
2779  * @return string
2780  */
2781  public function base64EncodeWrapMB($str, $linebreak = null)
2782  {
2783  $start = '=?' . $this->CharSet . '?B?';
2784  $end = '?=';
2785  $encoded = '';
2786  if ($linebreak === null) {
2787  $linebreak = $this->LE;
2788  }
2789 
2790  $mb_length = mb_strlen($str, $this->CharSet);
2791  // Each line must have length <= 75, including $start and $end
2792  $length = 75 - strlen($start) - strlen($end);
2793  // Average multi-byte ratio
2794  $ratio = $mb_length / strlen($str);
2795  // Base64 has a 4:3 ratio
2796  $avgLength = floor($length * $ratio * .75);
2797 
2798  for ($i = 0; $i < $mb_length; $i += $offset) {
2799  $lookBack = 0;
2800  do {
2801  $offset = $avgLength - $lookBack;
2802  $chunk = mb_substr($str, $i, $offset, $this->CharSet);
2803  $chunk = base64_encode($chunk);
2804  $lookBack++;
2805  } while (strlen($chunk) > $length);
2806  $encoded .= $chunk . $linebreak;
2807  }
2808 
2809  // Chomp the last linefeed
2810  $encoded = substr($encoded, 0, -strlen($linebreak));
2811  return $encoded;
2812  }
2813 
2814  /**
2815  * Encode a string in quoted-printable format.
2816  * According to RFC2045 section 6.7.
2817  * @access public
2818  * @param string $string The text to encode
2819  * @param integer $line_max Number of chars allowed on a line before wrapping
2820  * @return string
2821  * @link http://www.php.net/manual/en/function.quoted-printable-decode.php#89417 Adapted from this comment
2822  */
2823  public function encodeQP($string, $line_max = 76)
2824  {
2825  // Use native function if it's available (>= PHP5.3)
2826  if (function_exists('quoted_printable_encode')) {
2827  return quoted_printable_encode($string);
2828  }
2829  // Fall back to a pure PHP implementation
2830  $string = str_replace(
2831  array('%20', '%0D%0A.', '%0D%0A', '%'),
2832  array(' ', "\r\n=2E", "\r\n", '='),
2833  rawurlencode($string)
2834  );
2835  return preg_replace('/[^\r\n]{' . ($line_max - 3) . '}[^=\r\n]{2}/', "$0=\r\n", $string);
2836  }
2837 
2838  /**
2839  * Backward compatibility wrapper for an old QP encoding function that was removed.
2840  * @see PHPMailer::encodeQP()
2841  * @access public
2842  * @param string $string
2843  * @param integer $line_max
2844  * @param boolean $space_conv
2845  * @return string
2846  * @deprecated Use encodeQP instead.
2847  */
2848  public function encodeQPphp(
2849  $string,
2850  $line_max = 76,
2851  /** @noinspection PhpUnusedParameterInspection */ $space_conv = false
2852  ) {
2853  return $this->encodeQP($string, $line_max);
2854  }
2855 
2856  /**
2857  * Encode a string using Q encoding.
2858  * @link http://tools.ietf.org/html/rfc2047
2859  * @param string $str the text to encode
2860  * @param string $position Where the text is going to be used, see the RFC for what that means
2861  * @access public
2862  * @return string
2863  */
2864  public function encodeQ($str, $position = 'text')
2865  {
2866  // There should not be any EOL in the string
2867  $pattern = '';
2868  $encoded = str_replace(array("\r", "\n"), '', $str);
2869  switch (strtolower($position)) {
2870  case 'phrase':
2871  // RFC 2047 section 5.3
2872  $pattern = '^A-Za-z0-9!*+\/ -';
2873  break;
2874  /** @noinspection PhpMissingBreakStatementInspection */
2875  case 'comment':
2876  // RFC 2047 section 5.2
2877  $pattern = '\(\)"';
2878  // intentional fall-through
2879  // for this reason we build the $pattern without including delimiters and []
2880  case 'text':
2881  default:
2882  // RFC 2047 section 5.1
2883  // Replace every high ascii, control, =, ? and _ characters
2884  $pattern = '\000-\011\013\014\016-\037\075\077\137\177-\377' . $pattern;
2885  break;
2886  }
2887  $matches = array();
2888  if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) {
2889  // If the string contains an '=', make sure it's the first thing we replace
2890  // so as to avoid double-encoding
2891  $eqkey = array_search('=', $matches[0]);
2892  if (false !== $eqkey) {
2893  unset($matches[0][$eqkey]);
2894  array_unshift($matches[0], '=');
2895  }
2896  foreach (array_unique($matches[0]) as $char) {
2897  $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded);
2898  }
2899  }
2900  // Replace every spaces to _ (more readable than =20)
2901  return str_replace(' ', '_', $encoded);
2902  }
2903 
2904  /**
2905  * Add a string or binary attachment (non-filesystem).
2906  * This method can be used to attach ascii or binary data,
2907  * such as a BLOB record from a database.
2908  * @param string $string String attachment data.
2909  * @param string $filename Name of the attachment.
2910  * @param string $encoding File encoding (see $Encoding).
2911  * @param string $type File extension (MIME) type.
2912  * @param string $disposition Disposition to use
2913  * @return void
2914  */
2915  public function addStringAttachment(
2916  $string,
2917  $filename,
2918  $encoding = 'base64',
2919  $type = '',
2920  $disposition = 'attachment'
2921  ) {
2922  // If a MIME type is not specified, try to work it out from the file name
2923  if ($type == '') {
2924  $type = self::filenameToType($filename);
2925  }
2926  // Append to $attachment array
2927  $this->attachment[] = array(
2928  0 => $string,
2929  1 => $filename,
2930  2 => basename($filename),
2931  3 => $encoding,
2932  4 => $type,
2933  5 => true, // isStringAttachment
2934  6 => $disposition,
2935  7 => 0
2936  );
2937  }
2938 
2939  /**
2940  * Add an embedded (inline) attachment from a file.
2941  * This can include images, sounds, and just about any other document type.
2942  * These differ from 'regular' attachments in that they are intended to be
2943  * displayed inline with the message, not just attached for download.
2944  * This is used in HTML messages that embed the images
2945  * the HTML refers to using the $cid value.
2946  * @param string $path Path to the attachment.
2947  * @param string $cid Content ID of the attachment; Use this to reference
2948  * the content when using an embedded image in HTML.
2949  * @param string $name Overrides the attachment name.
2950  * @param string $encoding File encoding (see $Encoding).
2951  * @param string $type File MIME type.
2952  * @param string $disposition Disposition to use
2953  * @return boolean True on successfully adding an attachment
2954  */
2955  public function addEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = '', $disposition = 'inline')
2956  {
2957  if (!@is_file($path)) {
2958  $this->setError($this->lang('file_access') . $path);
2959  return false;
2960  }
2961 
2962  // If a MIME type is not specified, try to work it out from the file name
2963  if ($type == '') {
2964  $type = self::filenameToType($path);
2965  }
2966 
2967  $filename = basename($path);
2968  if ($name == '') {
2969  $name = $filename;
2970  }
2971 
2972  // Append to $attachment array
2973  $this->attachment[] = array(
2974  0 => $path,
2975  1 => $filename,
2976  2 => $name,
2977  3 => $encoding,
2978  4 => $type,
2979  5 => false, // isStringAttachment
2980  6 => $disposition,
2981  7 => $cid
2982  );
2983  return true;
2984  }
2985 
2986  /**
2987  * Add an embedded stringified attachment.
2988  * This can include images, sounds, and just about any other document type.
2989  * Be sure to set the $type to an image type for images:
2990  * JPEG images use 'image/jpeg', GIF uses 'image/gif', PNG uses 'image/png'.
2991  * @param string $string The attachment binary data.
2992  * @param string $cid Content ID of the attachment; Use this to reference
2993  * the content when using an embedded image in HTML.
2994  * @param string $name
2995  * @param string $encoding File encoding (see $Encoding).
2996  * @param string $type MIME type.
2997  * @param string $disposition Disposition to use
2998  * @return boolean True on successfully adding an attachment
2999  */
3000  public function addStringEmbeddedImage(
3001  $string,
3002  $cid,
3003  $name = '',
3004  $encoding = 'base64',
3005  $type = '',
3006  $disposition = 'inline'
3007  ) {
3008  // If a MIME type is not specified, try to work it out from the name
3009  if ($type == '' and !empty($name)) {
3010  $type = self::filenameToType($name);
3011  }
3012 
3013  // Append to $attachment array
3014  $this->attachment[] = array(
3015  0 => $string,
3016  1 => $name,
3017  2 => $name,
3018  3 => $encoding,
3019  4 => $type,
3020  5 => true, // isStringAttachment
3021  6 => $disposition,
3022  7 => $cid
3023  );
3024  return true;
3025  }
3026 
3027  /**
3028  * Check if an inline attachment is present.
3029  * @access public
3030  * @return boolean
3031  */
3032  public function inlineImageExists()
3033  {
3034  foreach ($this->attachment as $attachment) {
3035  if ($attachment[6] == 'inline') {
3036  return true;
3037  }
3038  }
3039  return false;
3040  }
3041 
3042  /**
3043  * Check if an attachment (non-inline) is present.
3044  * @return boolean
3045  */
3046  public function attachmentExists()
3047  {
3048  foreach ($this->attachment as $attachment) {
3049  if ($attachment[6] == 'attachment') {
3050  return true;
3051  }
3052  }
3053  return false;
3054  }
3055 
3056  /**
3057  * Check if this message has an alternative body set.
3058  * @return boolean
3059  */
3060  public function alternativeExists()
3061  {
3062  return !empty($this->AltBody);
3063  }
3064 
3065  /**
3066  * Clear queued addresses of given kind.
3067  * @access protected
3068  * @param string $kind 'to', 'cc', or 'bcc'
3069  * @return void
3070  */
3071  public function clearQueuedAddresses($kind)
3072  {
3074  foreach ($RecipientsQueue as $address => $params) {
3075  if ($params[0] == $kind) {
3076  unset($this->RecipientsQueue[$address]);
3077  }
3078  }
3079  }
3080 
3081  /**
3082  * Clear all To recipients.
3083  * @return void
3084  */
3085  public function clearAddresses()
3086  {
3087  foreach ($this->to as $to) {
3088  unset($this->all_recipients[strtolower($to[0])]);
3089  }
3090  $this->to = array();
3091  $this->clearQueuedAddresses('to');
3092  }
3093 
3094  /**
3095  * Clear all CC recipients.
3096  * @return void
3097  */
3098  public function clearCCs()
3099  {
3100  foreach ($this->cc as $cc) {
3101  unset($this->all_recipients[strtolower($cc[0])]);
3102  }
3103  $this->cc = array();
3104  $this->clearQueuedAddresses('cc');
3105  }
3106 
3107  /**
3108  * Clear all BCC recipients.
3109  * @return void
3110  */
3111  public function clearBCCs()
3112  {
3113  foreach ($this->bcc as $bcc) {
3114  unset($this->all_recipients[strtolower($bcc[0])]);
3115  }
3116  $this->bcc = array();
3117  $this->clearQueuedAddresses('bcc');
3118  }
3119 
3120  /**
3121  * Clear all ReplyTo recipients.
3122  * @return void
3123  */
3124  public function clearReplyTos()
3125  {
3126  $this->ReplyTo = array();
3127  $this->ReplyToQueue = array();
3128  }
3129 
3130  /**
3131  * Clear all recipient types.
3132  * @return void
3133  */
3134  public function clearAllRecipients()
3135  {
3136  $this->to = array();
3137  $this->cc = array();
3138  $this->bcc = array();
3139  $this->all_recipients = array();
3140  $this->RecipientsQueue = array();
3141  }
3142 
3143  /**
3144  * Clear all filesystem, string, and binary attachments.
3145  * @return void
3146  */
3147  public function clearAttachments()
3148  {
3149  $this->attachment = array();
3150  }
3151 
3152  /**
3153  * Clear all custom headers.
3154  * @return void
3155  */
3156  public function clearCustomHeaders()
3157  {
3158  $this->CustomHeader = array();
3159  }
3160 
3161  /**
3162  * Add an error message to the error container.
3163  * @access protected
3164  * @param string $msg
3165  * @return void
3166  */
3167  protected function setError($msg)
3168  {
3169  $this->error_count++;
3170  if ($this->Mailer == 'smtp' and !is_null($this->smtp)) {
3171  $lasterror = $this->smtp->getError();
3172  if (!empty($lasterror['error'])) {
3173  $msg .= $this->lang('smtp_error') . $lasterror['error'];
3174  if (!empty($lasterror['detail'])) {
3175  $msg .= ' Detail: '. $lasterror['detail'];
3176  }
3177  if (!empty($lasterror['smtp_code'])) {
3178  $msg .= ' SMTP code: ' . $lasterror['smtp_code'];
3179  }
3180  if (!empty($lasterror['smtp_code_ex'])) {
3181  $msg .= ' Additional SMTP info: ' . $lasterror['smtp_code_ex'];
3182  }
3183  }
3184  }
3185  $this->ErrorInfo = $msg;
3186  }
3187 
3188  /**
3189  * Return an RFC 822 formatted date.
3190  * @access public
3191  * @return string
3192  * @static
3193  */
3194  public static function rfcDate()
3195  {
3196  // Set the time zone to whatever the default is to avoid 500 errors
3197  // Will default to UTC if it's not set properly in php.ini
3198  date_default_timezone_set(@date_default_timezone_get());
3199  return date('D, j M Y H:i:s O');
3200  }
3201 
3202  /**
3203  * Get the server hostname.
3204  * Returns 'localhost.localdomain' if unknown.
3205  * @access protected
3206  * @return string
3207  */
3208  protected function serverHostname()
3209  {
3210  $result = 'localhost.localdomain';
3211  if (!empty($this->Hostname)) {
3212  $result = $this->Hostname;
3213  } elseif (isset($_SERVER) and array_key_exists('SERVER_NAME', $_SERVER) and !empty($_SERVER['SERVER_NAME'])) {
3214  $result = $_SERVER['SERVER_NAME'];
3215  } elseif (function_exists('gethostname') && gethostname() !== false) {
3216  $result = gethostname();
3217  } elseif (php_uname('n') !== false) {
3218  $result = php_uname('n');
3219  }
3220  return $result;
3221  }
3222 
3223  /**
3224  * Get an error message in the current language.
3225  * @access protected
3226  * @param string $key
3227  * @return string
3228  */
3229  protected function lang($key)
3230  {
3231  if (count($this->language) < 1) {
3232  $this->setLanguage('en'); // set the default language
3233  }
3234 
3235  if (array_key_exists($key, $this->language)) {
3236  if ($key == 'smtp_connect_failed') {
3237  //Include a link to troubleshooting docs on SMTP connection failure
3238  //this is by far the biggest cause of support questions
3239  //but it's usually not PHPMailer's fault.
3240  return $this->language[$key] . ' https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting';
3241  }
3242  return $this->language[$key];
3243  } else {
3244  //Return the key as a fallback
3245  return $key;
3246  }
3247  }
3248 
3249  /**
3250  * Check if an error occurred.
3251  * @access public
3252  * @return boolean True if an error did occur.
3253  */
3254  public function isError()
3255  {
3256  return ($this->error_count > 0);
3257  }
3258 
3259  /**
3260  * Ensure consistent line endings in a string.
3261  * Changes every end of line from CRLF, CR or LF to $this->LE.
3262  * @access public
3263  * @param string $str String to fixEOL
3264  * @return string
3265  */
3266  public function fixEOL($str)
3267  {
3268  // Normalise to \n
3269  $nstr = str_replace(array("\r\n", "\r"), "\n", $str);
3270  // Now convert LE as needed
3271  if ($this->LE !== "\n") {
3272  $nstr = str_replace("\n", $this->LE, $nstr);
3273  }
3274  return $nstr;
3275  }
3276 
3277  /**
3278  * Add a custom header.
3279  * $name value can be overloaded to contain
3280  * both header name and value (name:value)
3281  * @access public
3282  * @param string $name Custom header name
3283  * @param string $value Header value
3284  * @return void
3285  */
3286  public function addCustomHeader($name, $value = null)
3287  {
3288  if ($value === null) {
3289  // Value passed in as name:value
3290  $this->CustomHeader[] = explode(':', $name, 2);
3291  } else {
3292  $this->CustomHeader[] = array($name, $value);
3293  }
3294  }
3295 
3296  /**
3297  * Returns all custom headers.
3298  * @return array
3299  */
3300  public function getCustomHeaders()
3301  {
3302  return $this->CustomHeader;
3303  }
3304 
3305  /**
3306  * Create a message from an HTML string.
3307  * Automatically makes modifications for inline images and backgrounds
3308  * and creates a plain-text version by converting the HTML.
3309  * Overwrites any existing values in $this->Body and $this->AltBody
3310  * @access public
3311  * @param string $message HTML message string
3312  * @param string $basedir baseline directory for path
3313  * @param boolean|callable $advanced Whether to use the internal HTML to text converter
3314  * or your own custom converter @see PHPMailer::html2text()
3315  * @return string $message
3316  */
3317  public function msgHTML($message, $basedir = '', $advanced = false)
3318  {
3319  preg_match_all('/(src|background)=["\'](.*)["\']/Ui', $message, $images);
3320  if (array_key_exists(2, $images)) {
3321  foreach ($images[2] as $imgindex => $url) {
3322  // Convert data URIs into embedded images
3323  if (preg_match('#^data:(image[^;,]*)(;base64)?,#', $url, $match)) {
3324  $data = substr($url, strpos($url, ','));
3325  if ($match[2]) {
3326  $data = base64_decode($data);
3327  } else {
3328  $data = rawurldecode($data);
3329  }
3330  $cid = md5($url) . '@phpmailer.0'; // RFC2392 S 2
3331  if ($this->addStringEmbeddedImage($data, $cid, 'embed' . $imgindex, 'base64', $match[1])) {
3332  $message = str_replace(
3333  $images[0][$imgindex],
3334  $images[1][$imgindex] . '="cid:' . $cid . '"',
3335  $message
3336  );
3337  }
3338  } elseif (substr($url, 0, 4) !== 'cid:' && !preg_match('#^[A-z]+://#', $url)) {
3339  // Do not change urls for absolute images (thanks to corvuscorax)
3340  // Do not change urls that are already inline images
3341  $filename = basename($url);
3342  $directory = dirname($url);
3343  if ($directory == '.') {
3344  $directory = '';
3345  }
3346  $cid = md5($url) . '@phpmailer.0'; // RFC2392 S 2
3347  if (strlen($basedir) > 1 && substr($basedir, -1) != '/') {
3348  $basedir .= '/';
3349  }
3350  if (strlen($directory) > 1 && substr($directory, -1) != '/') {
3351  $directory .= '/';
3352  }
3353  if ($this->addEmbeddedImage(
3354  $basedir . $directory . $filename,
3355  $cid,
3356  $filename,
3357  'base64',
3358  self::_mime_types((string)self::mb_pathinfo($filename, PATHINFO_EXTENSION))
3359  )
3360  ) {
3361  $message = preg_replace(
3362  '/' . $images[1][$imgindex] . '=["\']' . preg_quote($url, '/') . '["\']/Ui',
3363  $images[1][$imgindex] . '="cid:' . $cid . '"',
3364  $message
3365  );
3366  }
3367  }
3368  }
3369  }
3370  $this->isHTML(true);
3371  // Convert all message body line breaks to CRLF, makes quoted-printable encoding work much better
3372  $this->Body = $this->normalizeBreaks($message);
3373  $this->AltBody = $this->normalizeBreaks($this->html2text($message, $advanced));
3374  if (empty($this->AltBody)) {
3375  $this->AltBody = 'To view this email message, open it in a program that understands HTML!' .
3376  self::CRLF . self::CRLF;
3377  }
3378  return $this->Body;
3379  }
3380 
3381  /**
3382  * Convert an HTML string into plain text.
3383  * This is used by msgHTML().
3384  * Note - older versions of this function used a bundled advanced converter
3385  * which was been removed for license reasons in #232
3386  * Example usage:
3387  * <code>
3388  * // Use default conversion
3389  * $plain = $mail->html2text($html);
3390  * // Use your own custom converter
3391  * $plain = $mail->html2text($html, function($html) {
3392  * $converter = new MyHtml2text($html);
3393  * return $converter->get_text();
3394  * });
3395  * </code>
3396  * @param string $html The HTML text to convert
3397  * @param boolean|callable $advanced Any boolean value to use the internal converter,
3398  * or provide your own callable for custom conversion.
3399  * @return string
3400  */
3401  public function html2text($html, $advanced = false)
3402  {
3403  if (is_callable($advanced)) {
3404  return call_user_func($advanced, $html);
3405  }
3406  return html_entity_decode(
3407  trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/si', '', $html))),
3408  ENT_QUOTES,
3409  $this->CharSet
3410  );
3411  }
3412 
3413  /**
3414  * Get the MIME type for a file extension.
3415  * @param string $ext File extension
3416  * @access public
3417  * @return string MIME type of file.
3418  * @static
3419  */
3420  public static function _mime_types($ext = '')
3421  {
3422  $mimes = array(
3423  'xl' => 'application/excel',
3424  'js' => 'application/javascript',
3425  'hqx' => 'application/mac-binhex40',
3426  'cpt' => 'application/mac-compactpro',
3427  'bin' => 'application/macbinary',
3428  'doc' => 'application/msword',
3429  'word' => 'application/msword',
3430  'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
3431  'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
3432  'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
3433  'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
3434  'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
3435  'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
3436  'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
3437  'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
3438  'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
3439  'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
3440  'class' => 'application/octet-stream',
3441  'dll' => 'application/octet-stream',
3442  'dms' => 'application/octet-stream',
3443  'exe' => 'application/octet-stream',
3444  'lha' => 'application/octet-stream',
3445  'lzh' => 'application/octet-stream',
3446  'psd' => 'application/octet-stream',
3447  'sea' => 'application/octet-stream',
3448  'so' => 'application/octet-stream',
3449  'oda' => 'application/oda',
3450  'pdf' => 'application/pdf',
3451  'ai' => 'application/postscript',
3452  'eps' => 'application/postscript',
3453  'ps' => 'application/postscript',
3454  'smi' => 'application/smil',
3455  'smil' => 'application/smil',
3456  'mif' => 'application/vnd.mif',
3457  'xls' => 'application/vnd.ms-excel',
3458  'ppt' => 'application/vnd.ms-powerpoint',
3459  'wbxml' => 'application/vnd.wap.wbxml',
3460  'wmlc' => 'application/vnd.wap.wmlc',
3461  'dcr' => 'application/x-director',
3462  'dir' => 'application/x-director',
3463  'dxr' => 'application/x-director',
3464  'dvi' => 'application/x-dvi',
3465  'gtar' => 'application/x-gtar',
3466  'php3' => 'application/x-httpd-php',
3467  'php4' => 'application/x-httpd-php',
3468  'php' => 'application/x-httpd-php',
3469  'phtml' => 'application/x-httpd-php',
3470  'phps' => 'application/x-httpd-php-source',
3471  'swf' => 'application/x-shockwave-flash',
3472  'sit' => 'application/x-stuffit',
3473  'tar' => 'application/x-tar',
3474  'tgz' => 'application/x-tar',
3475  'xht' => 'application/xhtml+xml',
3476  'xhtml' => 'application/xhtml+xml',
3477  'zip' => 'application/zip',
3478  'mid' => 'audio/midi',
3479  'midi' => 'audio/midi',
3480  'mp2' => 'audio/mpeg',
3481  'mp3' => 'audio/mpeg',
3482  'mpga' => 'audio/mpeg',
3483  'aif' => 'audio/x-aiff',
3484  'aifc' => 'audio/x-aiff',
3485  'aiff' => 'audio/x-aiff',
3486  'ram' => 'audio/x-pn-realaudio',
3487  'rm' => 'audio/x-pn-realaudio',
3488  'rpm' => 'audio/x-pn-realaudio-plugin',
3489  'ra' => 'audio/x-realaudio',
3490  'wav' => 'audio/x-wav',
3491  'bmp' => 'image/bmp',
3492  'gif' => 'image/gif',
3493  'jpeg' => 'image/jpeg',
3494  'jpe' => 'image/jpeg',
3495  'jpg' => 'image/jpeg',
3496  'png' => 'image/png',
3497  'tiff' => 'image/tiff',
3498  'tif' => 'image/tiff',
3499  'eml' => 'message/rfc822',
3500  'css' => 'text/css',
3501  'html' => 'text/html',
3502  'htm' => 'text/html',
3503  'shtml' => 'text/html',
3504  'log' => 'text/plain',
3505  'text' => 'text/plain',
3506  'txt' => 'text/plain',
3507  'rtx' => 'text/richtext',
3508  'rtf' => 'text/rtf',
3509  'vcf' => 'text/vcard',
3510  'vcard' => 'text/vcard',
3511  'xml' => 'text/xml',
3512  'xsl' => 'text/xml',
3513  'mpeg' => 'video/mpeg',
3514  'mpe' => 'video/mpeg',
3515  'mpg' => 'video/mpeg',
3516  'mov' => 'video/quicktime',
3517  'qt' => 'video/quicktime',
3518  'rv' => 'video/vnd.rn-realvideo',
3519  'avi' => 'video/x-msvideo',
3520  'movie' => 'video/x-sgi-movie'
3521  );
3522  if (array_key_exists(strtolower($ext), $mimes)) {
3523  return $mimes[strtolower($ext)];
3524  }
3525  return 'application/octet-stream';
3526  }
3527 
3528  /**
3529  * Map a file name to a MIME type.
3530  * Defaults to 'application/octet-stream', i.e.. arbitrary binary data.
3531  * @param string $filename A file name or full path, does not need to exist as a file
3532  * @return string
3533  * @static
3534  */
3535  public static function filenameToType($filename)
3536  {
3537  // In case the path is a URL, strip any query string before getting extension
3538  $qpos = strpos($filename, '?');
3539  if (false !== $qpos) {
3540  $filename = substr($filename, 0, $qpos);
3541  }
3542  $pathinfo = self::mb_pathinfo($filename);
3543  return self::_mime_types($pathinfo['extension']);
3544  }
3545 
3546  /**
3547  * Multi-byte-safe pathinfo replacement.
3548  * Drop-in replacement for pathinfo(), but multibyte-safe, cross-platform-safe, old-version-safe.
3549  * Works similarly to the one in PHP >= 5.2.0
3550  * @link http://www.php.net/manual/en/function.pathinfo.php#107461
3551  * @param string $path A filename or path, does not need to exist as a file
3552  * @param integer|string $options Either a PATHINFO_* constant,
3553  * or a string name to return only the specified piece, allows 'filename' to work on PHP < 5.2
3554  * @return string|array
3555  * @static
3556  */
3557  public static function mb_pathinfo($path, $options = null)
3558  {
3559  $ret = array('dirname' => '', 'basename' => '', 'extension' => '', 'filename' => '');
3560  $pathinfo = array();
3561  if (preg_match('%^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^\.\\\\/]+?)|))[\\\\/\.]*$%im', $path, $pathinfo)) {
3562  if (array_key_exists(1, $pathinfo)) {
3563  $ret['dirname'] = $pathinfo[1];
3564  }
3565  if (array_key_exists(2, $pathinfo)) {
3566  $ret['basename'] = $pathinfo[2];
3567  }
3568  if (array_key_exists(5, $pathinfo)) {
3569  $ret['extension'] = $pathinfo[5];
3570  }
3571  if (array_key_exists(3, $pathinfo)) {
3572  $ret['filename'] = $pathinfo[3];
3573  }
3574  }
3575  switch ($options) {
3576  case PATHINFO_DIRNAME:
3577  case 'dirname':
3578  return $ret['dirname'];
3579  case PATHINFO_BASENAME:
3580  case 'basename':
3581  return $ret['basename'];
3582  case PATHINFO_EXTENSION:
3583  case 'extension':
3584  return $ret['extension'];
3585  case PATHINFO_FILENAME:
3586  case 'filename':
3587  return $ret['filename'];
3588  default:
3589  return $ret;
3590  }
3591  }
3592 
3593  /**
3594  * Set or reset instance properties.
3595  * You should avoid this function - it's more verbose, less efficient, more error-prone and
3596  * harder to debug than setting properties directly.
3597  * Usage Example:
3598  * `$mail->set('SMTPSecure', 'tls');`
3599  * is the same as:
3600  * `$mail->SMTPSecure = 'tls';`
3601  * @access public
3602  * @param string $name The property name to set
3603  * @param mixed $value The value to set the property to
3604  * @return boolean
3605  * @TODO Should this not be using the __set() magic function?
3606  */
3607  public function set($name, $value = '')
3608  {
3609  if (property_exists($this, $name)) {
3610  $this->$name = $value;
3611  return true;
3612  } else {
3613  $this->setError($this->lang('variable_set') . $name);
3614  return false;
3615  }
3616  }
3617 
3618  /**
3619  * Strip newlines to prevent header injection.
3620  * @access public
3621  * @param string $str
3622  * @return string
3623  */
3624  public function secureHeader($str)
3625  {
3626  return trim(str_replace(array("\r", "\n"), '', $str));
3627  }
3628 
3629  /**
3630  * Normalize line breaks in a string.
3631  * Converts UNIX LF, Mac CR and Windows CRLF line breaks into a single line break format.
3632  * Defaults to CRLF (for message bodies) and preserves consecutive breaks.
3633  * @param string $text
3634  * @param string $breaktype What kind of line break to use, defaults to CRLF
3635  * @return string
3636  * @access public
3637  * @static
3638  */
3639  public static function normalizeBreaks($text, $breaktype = "\r\n")
3640  {
3641  return preg_replace('/(\r\n|\r|\n)/ms', $breaktype, $text);
3642  }
3643 
3644  /**
3645  * Set the public and private key files and password for S/MIME signing.
3646  * @access public
3647  * @param string $cert_filename
3648  * @param string $key_filename
3649  * @param string $key_pass Password for private key
3650  * @param string $extracerts_filename Optional path to chain certificate
3651  */
3652  public function sign($cert_filename, $key_filename, $key_pass, $extracerts_filename = '')
3653  {
3654  $this->sign_cert_file = $cert_filename;
3655  $this->sign_key_file = $key_filename;
3656  $this->sign_key_pass = $key_pass;
3657  $this->sign_extracerts_file = $extracerts_filename;
3658  }
3659 
3660  /**
3661  * Quoted-Printable-encode a DKIM header.
3662  * @access public
3663  * @param string $txt
3664  * @return string
3665  */
3666  public function DKIM_QP($txt)
3667  {
3668  $line = '';
3669  for ($i = 0; $i < strlen($txt); $i++) {
3670  $ord = ord($txt[$i]);
3671  if (((0x21 <= $ord) && ($ord <= 0x3A)) || $ord == 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E))) {
3672  $line .= $txt[$i];
3673  } else {
3674  $line .= '=' . sprintf('%02X', $ord);
3675  }
3676  }
3677  return $line;
3678  }
3679 
3680  /**
3681  * Generate a DKIM signature.
3682  * @access public
3683  * @param string $signHeader
3684  * @throws phpmailerException
3685  * @return string
3686  */
3687  public function DKIM_Sign($signHeader)
3688  {
3689  if (!defined('PKCS7_TEXT')) {
3690  if ($this->exceptions) {
3691  throw new phpmailerException($this->lang('extension_missing') . 'openssl');
3692  }
3693  return '';
3694  }
3695  $privKeyStr = file_get_contents($this->DKIM_private);
3696  if ($this->DKIM_passphrase != '') {
3697  $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase);
3698  } else {
3699  $privKey = $privKeyStr;
3700  }
3701  if (openssl_sign($signHeader, $signature, $privKey)) {
3702  return base64_encode($signature);
3703  }
3704  return '';
3705  }
3706 
3707  /**
3708  * Generate a DKIM canonicalization header.
3709  * @access public
3710  * @param string $signHeader Header
3711  * @return string
3712  */
3713  public function DKIM_HeaderC($signHeader)
3714  {
3715  $signHeader = preg_replace('/\r\n\s+/', ' ', $signHeader);
3716  $lines = explode("\r\n", $signHeader);
3717  foreach ($lines as $key => $line) {
3718  list($heading, $value) = explode(':', $line, 2);
3719  $heading = strtolower($heading);
3720  $value = preg_replace('/\s+/', ' ', $value); // Compress useless spaces
3721  $lines[$key] = $heading . ':' . trim($value); // Don't forget to remove WSP around the value
3722  }
3723  $signHeader = implode("\r\n", $lines);
3724  return $signHeader;
3725  }
3726 
3727  /**
3728  * Generate a DKIM canonicalization body.
3729  * @access public
3730  * @param string $body Message Body
3731  * @return string
3732  */
3733  public function DKIM_BodyC($body)
3734  {
3735  if ($body == '') {
3736  return "\r\n";
3737  }
3738  // stabilize line endings
3739  $body = str_replace("\r\n", "\n", $body);
3740  $body = str_replace("\n", "\r\n", $body);
3741  // END stabilize line endings
3742  while (substr($body, strlen($body) - 4, 4) == "\r\n\r\n") {
3743  $body = substr($body, 0, strlen($body) - 2);
3744  }
3745  return $body;
3746  }
3747 
3748  /**
3749  * Create the DKIM header and body in a new message header.
3750  * @access public
3751  * @param string $headers_line Header lines
3752  * @param string $subject Subject
3753  * @param string $body Body
3754  * @return string
3755  */
3756  public function DKIM_Add($headers_line, $subject, $body)
3757  {
3758  $DKIMsignatureType = 'rsa-sha1'; // Signature & hash algorithms
3759  $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body
3760  $DKIMquery = 'dns/txt'; // Query method
3761  $DKIMtime = time(); // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone)
3762  $subject_header = "Subject: $subject";
3763  $headers = explode($this->LE, $headers_line);
3764  $from_header = '';
3765  $to_header = '';
3766  $current = '';
3767  foreach ($headers as $header) {
3768  if (strpos($header, 'From:') === 0) {
3769  $from_header = $header;
3770  $current = 'from_header';
3771  } elseif (strpos($header, 'To:') === 0) {
3772  $to_header = $header;
3773  $current = 'to_header';
3774  } else {
3775  if (!empty($$current) && strpos($header, ' =?') === 0) {
3776  $$current .= $header;
3777  } else {
3778  $current = '';
3779  }
3780  }
3781  }
3782  $from = str_replace('|', '=7C', $this->DKIM_QP($from_header));
3783  $to = str_replace('|', '=7C', $this->DKIM_QP($to_header));
3784  $subject = str_replace(
3785  '|',
3786  '=7C',
3787  $this->DKIM_QP($subject_header)
3788  ); // Copied header fields (dkim-quoted-printable)
3789  $body = $this->DKIM_BodyC($body);
3790  $DKIMlen = strlen($body); // Length of body
3791  $DKIMb64 = base64_encode(pack('H*', sha1($body))); // Base64 of packed binary SHA-1 hash of body
3792  if ('' == $this->DKIM_identity) {
3793  $ident = '';
3794  } else {
3795  $ident = ' i=' . $this->DKIM_identity . ';';
3796  }
3797  $dkimhdrs = 'DKIM-Signature: v=1; a=' .
3798  $DKIMsignatureType . '; q=' .
3799  $DKIMquery . '; l=' .
3800  $DKIMlen . '; s=' .
3801  $this->DKIM_selector .
3802  ";\r\n" .
3803  "\tt=" . $DKIMtime . '; c=' . $DKIMcanonicalization . ";\r\n" .
3804  "\th=From:To:Subject;\r\n" .
3805  "\td=" . $this->DKIM_domain . ';' . $ident . "\r\n" .
3806  "\tz=$from\r\n" .
3807  "\t|$to\r\n" .
3808  "\t|$subject;\r\n" .
3809  "\tbh=" . $DKIMb64 . ";\r\n" .
3810  "\tb=";
3811  $toSign = $this->DKIM_HeaderC(
3812  $from_header . "\r\n" .
3813  $to_header . "\r\n" .
3814  $subject_header . "\r\n" .
3815  $dkimhdrs
3816  );
3817  $signed = $this->DKIM_Sign($toSign);
3818  return $dkimhdrs . $signed . "\r\n";
3819  }
3820 
3821  /**
3822  * Detect if a string contains a line longer than the maximum line length allowed.
3823  * @param string $str
3824  * @return boolean
3825  * @static
3826  */
3827  public static function hasLineLongerThanMax($str)
3828  {
3829  //+2 to include CRLF line break for a 1000 total
3830  return (boolean)preg_match('/^(.{'.(self::MAX_LINE_LENGTH + 2).',})/m', $str);
3831  }
3832 
3833  /**
3834  * Allows for public read access to 'to' property.
3835  * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included.
3836  * @access public
3837  * @return array
3838  */
3839  public function getToAddresses()
3840  {
3841  return $this->to;
3842  }
3843 
3844  /**
3845  * Allows for public read access to 'cc' property.
3846  * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included.
3847  * @access public
3848  * @return array
3849  */
3850  public function getCcAddresses()
3851  {
3852  return $this->cc;
3853  }
3854 
3855  /**
3856  * Allows for public read access to 'bcc' property.
3857  * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included.
3858  * @access public
3859  * @return array
3860  */
3861  public function getBccAddresses()
3862  {
3863  return $this->bcc;
3864  }
3865 
3866  /**
3867  * Allows for public read access to 'ReplyTo' property.
3868  * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included.
3869  * @access public
3870  * @return array
3871  */
3872  public function getReplyToAddresses()
3873  {
3874  return $this->ReplyTo;
3875  }
3876 
3877  /**
3878  * Allows for public read access to 'all_recipients' property.
3879  * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included.
3880  * @access public
3881  * @return array
3882  */
3883  public function getAllRecipientAddresses()
3884  {
3885  return $this->all_recipients;
3886  }
3887 
3888  /**
3889  * Perform a callback.
3890  * @param boolean $isSent
3891  * @param array $to
3892  * @param array $cc
3893  * @param array $bcc
3894  * @param string $subject
3895  * @param string $body
3896  * @param string $from
3897  */
3898  protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body, $from)
3899  {
3900  if (!empty($this->action_function) && is_callable($this->action_function)) {
3901  $params = array($isSent, $to, $cc, $bcc, $subject, $body, $from);
3902  call_user_func_array($this->action_function, $params);
3903  }
3904  }
3905 }
3906 
3907 /**
3908  * PHPMailer exception handler
3909  * @package PHPMailer
3910  */
3911 class phpmailerException extends Exception
3912 {
3913  /**
3914  * Prettify error message output
3915  * @return string
3916  */
3917  public function errorMessage()
3918  {
3919  $errorMsg = '<strong>' . $this->getMessage() . "</strong><br />\n";
3920  return $errorMsg;
3921  }
3922 }
addCustomHeader($name, $value=null)
addStringAttachment($string, $filename, $encoding= 'base64', $type= '', $disposition= 'attachment')
const STOP_CONTINUE
isHTML($isHtml=true)
encodeQ($str, $position= 'text')
attachAll($disposition_type, $boundary)
$ratio
parseAddresses($addrstr, $useimap=true)
const MAX_LINE_LENGTH
smtpSend($header, $body)
addAttachment($path, $name= '', $encoding= 'base64', $type= '', $disposition= 'attachment')
DKIM_HeaderC($signHeader)
doCallback($isSent, $to, $cc, $bcc, $subject, $body, $from)
$ret
mailSend($header, $body)
$message
__construct($exceptions=false)
$filename
punyencodeAddress($address)
wrapText($message, $length, $qp_mode=false)
$file
set($name, $value= '')
encodeFile($path, $encoding= 'base64')
addOrEnqueueAnAddress($kind, $address, $name)
sendmailSend($header, $body)
encodeQP($string, $line_max=76)
addStringEmbeddedImage($string, $cid, $name= '', $encoding= 'base64', $type= '', $disposition= 'inline')
const STOP_CRITICAL
getBoundary($boundary, $charSet, $contentType, $encoding)
$subject
encodeQPphp($string, $line_max=76, $space_conv=false)
addAnAddress($kind, $address, $name= '')
addEmbeddedImage($path, $cid, $name= '', $encoding= 'base64', $type= '', $disposition= 'inline')
addBCC($address, $name= '')
static normalizeBreaks($text, $breaktype="\r\n")
addCC($address, $name= '')
DKIM_Add($headers_line, $subject, $body)
DKIM_Sign($signHeader)
static isShellSafe($string)
$PHPMAILER_LANG['authenticate']
const STOP_MESSAGE
headerLine($name, $value)
static mb_pathinfo($path, $options=null)
clearQueuedAddresses($kind)
static validateAddress($address, $patternselect= 'auto')
msgHTML($message, $basedir= '', $advanced=false)
utf8CharBoundary($encodedText, $maxLength)
$path
Definition: dav.php:39
static filenameToType($filename)
addrAppend($type, $addr)
base64EncodeWrapMB($str, $linebreak=null)
global $_SERVER
static hasLineLongerThanMax($str)
encodeString($str, $encoding= 'base64')
html2text($html, $advanced=false)
$from
static _mime_types($ext= '')
static rfcDate()
textLine($value)
setFrom($address, $name= '', $auto=true)
sign($cert_filename, $key_filename, $key_pass, $extracerts_filename= '')
endBoundary($boundary)
setLanguage($langcode= 'en', $lang_path= '')
encodeHeader($str, $position= 'text')
$value
smtpConnect($options=array())
addReplyTo($address, $name= '')
addAddress($address, $name= '')
has8bitChars($text)
$data
← centre documentaire © anakeen