MDL-67373 lib: Upgrade PHPmailer to 6.1.3
[moodle.git] / lib / phpmailer / src / PHPMailer.php
blobd6524afedabb0fd2765c2645c3aee81838302d82
1 <?php
2 /**
3 * PHPMailer - PHP email creation and transport class.
4 * PHP Version 5.5.
6 * @see https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
8 * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
9 * @author Jim Jagielski (jimjag) <jimjag@gmail.com>
10 * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
11 * @author Brent R. Matzelle (original founder)
12 * @copyright 2012 - 2019 Marcus Bointon
13 * @copyright 2010 - 2012 Jim Jagielski
14 * @copyright 2004 - 2009 Andy Prevost
15 * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
16 * @note This program is distributed in the hope that it will be useful - WITHOUT
17 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
18 * FITNESS FOR A PARTICULAR PURPOSE.
21 namespace PHPMailer\PHPMailer;
23 /**
24 * PHPMailer - PHP email creation and transport class.
26 * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
27 * @author Jim Jagielski (jimjag) <jimjag@gmail.com>
28 * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
29 * @author Brent R. Matzelle (original founder)
31 class PHPMailer
33 const CHARSET_ASCII = 'us-ascii';
34 const CHARSET_ISO88591 = 'iso-8859-1';
35 const CHARSET_UTF8 = 'utf-8';
37 const CONTENT_TYPE_PLAINTEXT = 'text/plain';
38 const CONTENT_TYPE_TEXT_CALENDAR = 'text/calendar';
39 const CONTENT_TYPE_TEXT_HTML = 'text/html';
40 const CONTENT_TYPE_MULTIPART_ALTERNATIVE = 'multipart/alternative';
41 const CONTENT_TYPE_MULTIPART_MIXED = 'multipart/mixed';
42 const CONTENT_TYPE_MULTIPART_RELATED = 'multipart/related';
44 const ENCODING_7BIT = '7bit';
45 const ENCODING_8BIT = '8bit';
46 const ENCODING_BASE64 = 'base64';
47 const ENCODING_BINARY = 'binary';
48 const ENCODING_QUOTED_PRINTABLE = 'quoted-printable';
50 const ENCRYPTION_STARTTLS = 'tls';
51 const ENCRYPTION_SMTPS = 'ssl';
53 const ICAL_METHOD_REQUEST = 'REQUEST';
54 const ICAL_METHOD_PUBLISH = 'PUBLISH';
55 const ICAL_METHOD_REPLY = 'REPLY';
56 const ICAL_METHOD_ADD = 'ADD';
57 const ICAL_METHOD_CANCEL = 'CANCEL';
58 const ICAL_METHOD_REFRESH = 'REFRESH';
59 const ICAL_METHOD_COUNTER = 'COUNTER';
60 const ICAL_METHOD_DECLINECOUNTER = 'DECLINECOUNTER';
62 /**
63 * Email priority.
64 * Options: null (default), 1 = High, 3 = Normal, 5 = low.
65 * When null, the header is not set at all.
67 * @var int
69 public $Priority;
71 /**
72 * The character set of the message.
74 * @var string
76 public $CharSet = self::CHARSET_ISO88591;
78 /**
79 * The MIME Content-type of the message.
81 * @var string
83 public $ContentType = self::CONTENT_TYPE_PLAINTEXT;
85 /**
86 * The message encoding.
87 * Options: "8bit", "7bit", "binary", "base64", and "quoted-printable".
89 * @var string
91 public $Encoding = self::ENCODING_8BIT;
93 /**
94 * Holds the most recent mailer error message.
96 * @var string
98 public $ErrorInfo = '';
101 * The From email address for the message.
103 * @var string
105 public $From = 'root@localhost';
108 * The From name of the message.
110 * @var string
112 public $FromName = 'Root User';
115 * The envelope sender of the message.
116 * This will usually be turned into a Return-Path header by the receiver,
117 * and is the address that bounces will be sent to.
118 * If not empty, will be passed via `-f` to sendmail or as the 'MAIL FROM' value over SMTP.
120 * @var string
122 public $Sender = '';
125 * The Subject of the message.
127 * @var string
129 public $Subject = '';
132 * An HTML or plain text message body.
133 * If HTML then call isHTML(true).
135 * @var string
137 public $Body = '';
140 * The plain-text message body.
141 * This body can be read by mail clients that do not have HTML email
142 * capability such as mutt & Eudora.
143 * Clients that can read HTML will view the normal Body.
145 * @var string
147 public $AltBody = '';
150 * An iCal message part body.
151 * Only supported in simple alt or alt_inline message types
152 * To generate iCal event structures, use classes like EasyPeasyICS or iCalcreator.
154 * @see http://sprain.ch/blog/downloads/php-class-easypeasyics-create-ical-files-with-php/
155 * @see http://kigkonsult.se/iCalcreator/
157 * @var string
159 public $Ical = '';
162 * Value-array of "method" in Contenttype header "text/calendar"
164 * @var string[]
166 protected static $IcalMethods = [
167 self::ICAL_METHOD_REQUEST,
168 self::ICAL_METHOD_PUBLISH,
169 self::ICAL_METHOD_REPLY,
170 self::ICAL_METHOD_ADD,
171 self::ICAL_METHOD_CANCEL,
172 self::ICAL_METHOD_REFRESH,
173 self::ICAL_METHOD_COUNTER,
174 self::ICAL_METHOD_DECLINECOUNTER,
178 * The complete compiled MIME message body.
180 * @var string
182 protected $MIMEBody = '';
185 * The complete compiled MIME message headers.
187 * @var string
189 protected $MIMEHeader = '';
192 * Extra headers that createHeader() doesn't fold in.
194 * @var string
196 protected $mailHeader = '';
199 * Word-wrap the message body to this number of chars.
200 * Set to 0 to not wrap. A useful value here is 78, for RFC2822 section 2.1.1 compliance.
202 * @see static::STD_LINE_LENGTH
204 * @var int
206 public $WordWrap = 0;
209 * Which method to use to send mail.
210 * Options: "mail", "sendmail", or "smtp".
212 * @var string
214 public $Mailer = 'mail';
217 * The path to the sendmail program.
219 * @var string
221 public $Sendmail = '/usr/sbin/sendmail';
224 * Whether mail() uses a fully sendmail-compatible MTA.
225 * One which supports sendmail's "-oi -f" options.
227 * @var bool
229 public $UseSendmailOptions = true;
232 * The email address that a reading confirmation should be sent to, also known as read receipt.
234 * @var string
236 public $ConfirmReadingTo = '';
239 * The hostname to use in the Message-ID header and as default HELO string.
240 * If empty, PHPMailer attempts to find one with, in order,
241 * $_SERVER['SERVER_NAME'], gethostname(), php_uname('n'), or the value
242 * 'localhost.localdomain'.
244 * @see PHPMailer::$Helo
246 * @var string
248 public $Hostname = '';
251 * An ID to be used in the Message-ID header.
252 * If empty, a unique id will be generated.
253 * You can set your own, but it must be in the format "<id@domain>",
254 * as defined in RFC5322 section 3.6.4 or it will be ignored.
256 * @see https://tools.ietf.org/html/rfc5322#section-3.6.4
258 * @var string
260 public $MessageID = '';
263 * The message Date to be used in the Date header.
264 * If empty, the current date will be added.
266 * @var string
268 public $MessageDate = '';
271 * SMTP hosts.
272 * Either a single hostname or multiple semicolon-delimited hostnames.
273 * You can also specify a different port
274 * for each host by using this format: [hostname:port]
275 * (e.g. "smtp1.example.com:25;smtp2.example.com").
276 * You can also specify encryption type, for example:
277 * (e.g. "tls://smtp1.example.com:587;ssl://smtp2.example.com:465").
278 * Hosts will be tried in order.
280 * @var string
282 public $Host = 'localhost';
285 * The default SMTP server port.
287 * @var int
289 public $Port = 25;
292 * The SMTP HELO/EHLO name used for the SMTP connection.
293 * Default is $Hostname. If $Hostname is empty, PHPMailer attempts to find
294 * one with the same method described above for $Hostname.
296 * @see PHPMailer::$Hostname
298 * @var string
300 public $Helo = '';
303 * What kind of encryption to use on the SMTP connection.
304 * Options: '', static::ENCRYPTION_STARTTLS, or static::ENCRYPTION_SMTPS.
306 * @var string
308 public $SMTPSecure = '';
311 * Whether to enable TLS encryption automatically if a server supports it,
312 * even if `SMTPSecure` is not set to 'tls'.
313 * Be aware that in PHP >= 5.6 this requires that the server's certificates are valid.
315 * @var bool
317 public $SMTPAutoTLS = true;
320 * Whether to use SMTP authentication.
321 * Uses the Username and Password properties.
323 * @see PHPMailer::$Username
324 * @see PHPMailer::$Password
326 * @var bool
328 public $SMTPAuth = false;
331 * Options array passed to stream_context_create when connecting via SMTP.
333 * @var array
335 public $SMTPOptions = [];
338 * SMTP username.
340 * @var string
342 public $Username = '';
345 * SMTP password.
347 * @var string
349 public $Password = '';
352 * SMTP auth type.
353 * Options are CRAM-MD5, LOGIN, PLAIN, XOAUTH2, attempted in that order if not specified.
355 * @var string
357 public $AuthType = '';
360 * An instance of the PHPMailer OAuth class.
362 * @var OAuth
364 protected $oauth;
367 * The SMTP server timeout in seconds.
368 * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2.
370 * @var int
372 public $Timeout = 300;
375 * Comma separated list of DSN notifications
376 * 'NEVER' under no circumstances a DSN must be returned to the sender.
377 * If you use NEVER all other notifications will be ignored.
378 * 'SUCCESS' will notify you when your mail has arrived at its destination.
379 * 'FAILURE' will arrive if an error occurred during delivery.
380 * 'DELAY' will notify you if there is an unusual delay in delivery, but the actual
381 * delivery's outcome (success or failure) is not yet decided.
383 * @see https://tools.ietf.org/html/rfc3461 See section 4.1 for more information about NOTIFY
385 public $dsn = '';
388 * SMTP class debug output mode.
389 * Debug output level.
390 * Options:
391 * * SMTP::DEBUG_OFF: No output
392 * * SMTP::DEBUG_CLIENT: Client messages
393 * * SMTP::DEBUG_SERVER: Client and server messages
394 * * SMTP::DEBUG_CONNECTION: As SERVER plus connection status
395 * * SMTP::DEBUG_LOWLEVEL: Noisy, low-level data output, rarely needed
397 * @see SMTP::$do_debug
399 * @var int
401 public $SMTPDebug = 0;
404 * How to handle debug output.
405 * Options:
406 * * `echo` Output plain-text as-is, appropriate for CLI
407 * * `html` Output escaped, line breaks converted to `<br>`, appropriate for browser output
408 * * `error_log` Output to error log as configured in php.ini
409 * By default PHPMailer will use `echo` if run from a `cli` or `cli-server` SAPI, `html` otherwise.
410 * Alternatively, you can provide a callable expecting two params: a message string and the debug level:
412 * ```php
413 * $mail->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";};
414 * ```
416 * Alternatively, you can pass in an instance of a PSR-3 compatible logger, though only `debug`
417 * level output is used:
419 * ```php
420 * $mail->Debugoutput = new myPsr3Logger;
421 * ```
423 * @see SMTP::$Debugoutput
425 * @var string|callable|\Psr\Log\LoggerInterface
427 public $Debugoutput = 'echo';
430 * Whether to keep SMTP connection open after each message.
431 * If this is set to true then to close the connection
432 * requires an explicit call to smtpClose().
434 * @var bool
436 public $SMTPKeepAlive = false;
439 * Whether to split multiple to addresses into multiple messages
440 * or send them all in one message.
441 * Only supported in `mail` and `sendmail` transports, not in SMTP.
443 * @var bool
445 public $SingleTo = false;
448 * Storage for addresses when SingleTo is enabled.
450 * @var array
452 protected $SingleToArray = [];
455 * Whether to generate VERP addresses on send.
456 * Only applicable when sending via SMTP.
458 * @see https://en.wikipedia.org/wiki/Variable_envelope_return_path
459 * @see http://www.postfix.org/VERP_README.html Postfix VERP info
461 * @var bool
463 public $do_verp = false;
466 * Whether to allow sending messages with an empty body.
468 * @var bool
470 public $AllowEmpty = false;
473 * DKIM selector.
475 * @var string
477 public $DKIM_selector = '';
480 * DKIM Identity.
481 * Usually the email address used as the source of the email.
483 * @var string
485 public $DKIM_identity = '';
488 * DKIM passphrase.
489 * Used if your key is encrypted.
491 * @var string
493 public $DKIM_passphrase = '';
496 * DKIM signing domain name.
498 * @example 'example.com'
500 * @var string
502 public $DKIM_domain = '';
505 * DKIM Copy header field values for diagnostic use.
507 * @var bool
509 public $DKIM_copyHeaderFields = true;
512 * DKIM Extra signing headers.
514 * @example ['List-Unsubscribe', 'List-Help']
516 * @var array
518 public $DKIM_extraHeaders = [];
521 * DKIM private key file path.
523 * @var string
525 public $DKIM_private = '';
528 * DKIM private key string.
530 * If set, takes precedence over `$DKIM_private`.
532 * @var string
534 public $DKIM_private_string = '';
537 * Callback Action function name.
539 * The function that handles the result of the send email action.
540 * It is called out by send() for each email sent.
542 * Value can be any php callable: http://www.php.net/is_callable
544 * Parameters:
545 * bool $result result of the send action
546 * array $to email addresses of the recipients
547 * array $cc cc email addresses
548 * array $bcc bcc email addresses
549 * string $subject the subject
550 * string $body the email body
551 * string $from email address of sender
552 * string $extra extra information of possible use
553 * "smtp_transaction_id' => last smtp transaction id
555 * @var string
557 public $action_function = '';
560 * What to put in the X-Mailer header.
561 * Options: An empty string for PHPMailer default, whitespace/null for none, or a string to use.
563 * @var string|null
565 public $XMailer = '';
568 * Which validator to use by default when validating email addresses.
569 * May be a callable to inject your own validator, but there are several built-in validators.
570 * The default validator uses PHP's FILTER_VALIDATE_EMAIL filter_var option.
572 * @see PHPMailer::validateAddress()
574 * @var string|callable
576 public static $validator = 'php';
579 * An instance of the SMTP sender class.
581 * @var SMTP
583 protected $smtp;
586 * The array of 'to' names and addresses.
588 * @var array
590 protected $to = [];
593 * The array of 'cc' names and addresses.
595 * @var array
597 protected $cc = [];
600 * The array of 'bcc' names and addresses.
602 * @var array
604 protected $bcc = [];
607 * The array of reply-to names and addresses.
609 * @var array
611 protected $ReplyTo = [];
614 * An array of all kinds of addresses.
615 * Includes all of $to, $cc, $bcc.
617 * @see PHPMailer::$to
618 * @see PHPMailer::$cc
619 * @see PHPMailer::$bcc
621 * @var array
623 protected $all_recipients = [];
626 * An array of names and addresses queued for validation.
627 * In send(), valid and non duplicate entries are moved to $all_recipients
628 * and one of $to, $cc, or $bcc.
629 * This array is used only for addresses with IDN.
631 * @see PHPMailer::$to
632 * @see PHPMailer::$cc
633 * @see PHPMailer::$bcc
634 * @see PHPMailer::$all_recipients
636 * @var array
638 protected $RecipientsQueue = [];
641 * An array of reply-to names and addresses queued for validation.
642 * In send(), valid and non duplicate entries are moved to $ReplyTo.
643 * This array is used only for addresses with IDN.
645 * @see PHPMailer::$ReplyTo
647 * @var array
649 protected $ReplyToQueue = [];
652 * The array of attachments.
654 * @var array
656 protected $attachment = [];
659 * The array of custom headers.
661 * @var array
663 protected $CustomHeader = [];
666 * The most recent Message-ID (including angular brackets).
668 * @var string
670 protected $lastMessageID = '';
673 * The message's MIME type.
675 * @var string
677 protected $message_type = '';
680 * The array of MIME boundary strings.
682 * @var array
684 protected $boundary = [];
687 * The array of available languages.
689 * @var array
691 protected $language = [];
694 * The number of errors encountered.
696 * @var int
698 protected $error_count = 0;
701 * The S/MIME certificate file path.
703 * @var string
705 protected $sign_cert_file = '';
708 * The S/MIME key file path.
710 * @var string
712 protected $sign_key_file = '';
715 * The optional S/MIME extra certificates ("CA Chain") file path.
717 * @var string
719 protected $sign_extracerts_file = '';
722 * The S/MIME password for the key.
723 * Used only if the key is encrypted.
725 * @var string
727 protected $sign_key_pass = '';
730 * Whether to throw exceptions for errors.
732 * @var bool
734 protected $exceptions = false;
737 * Unique ID used for message ID and boundaries.
739 * @var string
741 protected $uniqueid = '';
744 * The PHPMailer Version number.
746 * @var string
748 const VERSION = '6.1.3';
751 * Error severity: message only, continue processing.
753 * @var int
755 const STOP_MESSAGE = 0;
758 * Error severity: message, likely ok to continue processing.
760 * @var int
762 const STOP_CONTINUE = 1;
765 * Error severity: message, plus full stop, critical error reached.
767 * @var int
769 const STOP_CRITICAL = 2;
772 * SMTP RFC standard line ending.
774 * @var string
776 protected static $LE = "\r\n";
779 * The maximum line length supported by mail().
781 * Background: mail() will sometimes corrupt messages
782 * with headers headers longer than 65 chars, see #818.
784 * @var int
786 const MAIL_MAX_LINE_LENGTH = 63;
789 * The maximum line length allowed by RFC 2822 section 2.1.1.
791 * @var int
793 const MAX_LINE_LENGTH = 998;
796 * The lower maximum line length allowed by RFC 2822 section 2.1.1.
797 * This length does NOT include the line break
798 * 76 means that lines will be 77 or 78 chars depending on whether
799 * the line break format is LF or CRLF; both are valid.
801 * @var int
803 const STD_LINE_LENGTH = 76;
806 * Constructor.
808 * @param bool $exceptions Should we throw external exceptions?
810 public function __construct($exceptions = null)
812 if (null !== $exceptions) {
813 $this->exceptions = (bool) $exceptions;
815 //Pick an appropriate debug output format automatically
816 $this->Debugoutput = (strpos(PHP_SAPI, 'cli') !== false ? 'echo' : 'html');
820 * Destructor.
822 public function __destruct()
824 //Close any open SMTP connection nicely
825 $this->smtpClose();
829 * Call mail() in a safe_mode-aware fashion.
830 * Also, unless sendmail_path points to sendmail (or something that
831 * claims to be sendmail), don't pass params (not a perfect fix,
832 * but it will do).
834 * @param string $to To
835 * @param string $subject Subject
836 * @param string $body Message Body
837 * @param string $header Additional Header(s)
838 * @param string|null $params Params
840 * @return bool
842 private function mailPassthru($to, $subject, $body, $header, $params)
844 //Check overloading of mail function to avoid double-encoding
845 if (ini_get('mbstring.func_overload') & 1) {
846 $subject = $this->secureHeader($subject);
847 } else {
848 $subject = $this->encodeHeader($this->secureHeader($subject));
850 //Calling mail() with null params breaks
851 if (!$this->UseSendmailOptions || null === $params) {
852 $result = @mail($to, $subject, $body, $header);
853 } else {
854 $result = @mail($to, $subject, $body, $header, $params);
857 return $result;
861 * Output debugging info via user-defined method.
862 * Only generates output if SMTP debug output is enabled (@see SMTP::$do_debug).
864 * @see PHPMailer::$Debugoutput
865 * @see PHPMailer::$SMTPDebug
867 * @param string $str
869 protected function edebug($str)
871 if ($this->SMTPDebug <= 0) {
872 return;
874 //Is this a PSR-3 logger?
875 if ($this->Debugoutput instanceof \Psr\Log\LoggerInterface) {
876 $this->Debugoutput->debug($str);
878 return;
880 //Avoid clash with built-in function names
881 if (is_callable($this->Debugoutput) && !in_array($this->Debugoutput, ['error_log', 'html', 'echo'])) {
882 call_user_func($this->Debugoutput, $str, $this->SMTPDebug);
884 return;
886 switch ($this->Debugoutput) {
887 case 'error_log':
888 //Don't output, just log
889 error_log($str);
890 break;
891 case 'html':
892 //Cleans up output a bit for a better looking, HTML-safe output
893 echo htmlentities(
894 preg_replace('/[\r\n]+/', '', $str),
895 ENT_QUOTES,
896 'UTF-8'
897 ), "<br>\n";
898 break;
899 case 'echo':
900 default:
901 //Normalize line breaks
902 $str = preg_replace('/\r\n|\r/m', "\n", $str);
903 echo gmdate('Y-m-d H:i:s'),
904 "\t",
905 //Trim trailing space
906 trim(
907 //Indent for readability, except for trailing break
908 str_replace(
909 "\n",
910 "\n \t ",
911 trim($str)
914 "\n";
919 * Sets message type to HTML or plain.
921 * @param bool $isHtml True for HTML mode
923 public function isHTML($isHtml = true)
925 if ($isHtml) {
926 $this->ContentType = static::CONTENT_TYPE_TEXT_HTML;
927 } else {
928 $this->ContentType = static::CONTENT_TYPE_PLAINTEXT;
933 * Send messages using SMTP.
935 public function isSMTP()
937 $this->Mailer = 'smtp';
941 * Send messages using PHP's mail() function.
943 public function isMail()
945 $this->Mailer = 'mail';
949 * Send messages using $Sendmail.
951 public function isSendmail()
953 $ini_sendmail_path = ini_get('sendmail_path');
955 if (false === stripos($ini_sendmail_path, 'sendmail')) {
956 $this->Sendmail = '/usr/sbin/sendmail';
957 } else {
958 $this->Sendmail = $ini_sendmail_path;
960 $this->Mailer = 'sendmail';
964 * Send messages using qmail.
966 public function isQmail()
968 $ini_sendmail_path = ini_get('sendmail_path');
970 if (false === stripos($ini_sendmail_path, 'qmail')) {
971 $this->Sendmail = '/var/qmail/bin/qmail-inject';
972 } else {
973 $this->Sendmail = $ini_sendmail_path;
975 $this->Mailer = 'qmail';
979 * Add a "To" address.
981 * @param string $address The email address to send to
982 * @param string $name
984 * @throws Exception
986 * @return bool true on success, false if address already used or invalid in some way
988 public function addAddress($address, $name = '')
990 return $this->addOrEnqueueAnAddress('to', $address, $name);
994 * Add a "CC" address.
996 * @param string $address The email address to send to
997 * @param string $name
999 * @throws Exception
1001 * @return bool true on success, false if address already used or invalid in some way
1003 public function addCC($address, $name = '')
1005 return $this->addOrEnqueueAnAddress('cc', $address, $name);
1009 * Add a "BCC" address.
1011 * @param string $address The email address to send to
1012 * @param string $name
1014 * @throws Exception
1016 * @return bool true on success, false if address already used or invalid in some way
1018 public function addBCC($address, $name = '')
1020 return $this->addOrEnqueueAnAddress('bcc', $address, $name);
1024 * Add a "Reply-To" address.
1026 * @param string $address The email address to reply to
1027 * @param string $name
1029 * @throws Exception
1031 * @return bool true on success, false if address already used or invalid in some way
1033 public function addReplyTo($address, $name = '')
1035 return $this->addOrEnqueueAnAddress('Reply-To', $address, $name);
1039 * Add an address to one of the recipient arrays or to the ReplyTo array. Because PHPMailer
1040 * can't validate addresses with an IDN without knowing the PHPMailer::$CharSet (that can still
1041 * be modified after calling this function), addition of such addresses is delayed until send().
1042 * Addresses that have been added already return false, but do not throw exceptions.
1044 * @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo'
1045 * @param string $address The email address to send, resp. to reply to
1046 * @param string $name
1048 * @throws Exception
1050 * @return bool true on success, false if address already used or invalid in some way
1052 protected function addOrEnqueueAnAddress($kind, $address, $name)
1054 $address = trim($address);
1055 $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
1056 $pos = strrpos($address, '@');
1057 if (false === $pos) {
1058 // At-sign is missing.
1059 $error_message = sprintf(
1060 '%s (%s): %s',
1061 $this->lang('invalid_address'),
1062 $kind,
1063 $address
1065 $this->setError($error_message);
1066 $this->edebug($error_message);
1067 if ($this->exceptions) {
1068 throw new Exception($error_message);
1071 return false;
1073 $params = [$kind, $address, $name];
1074 // Enqueue addresses with IDN until we know the PHPMailer::$CharSet.
1075 if (static::idnSupported() && $this->has8bitChars(substr($address, ++$pos))) {
1076 if ('Reply-To' !== $kind) {
1077 if (!array_key_exists($address, $this->RecipientsQueue)) {
1078 $this->RecipientsQueue[$address] = $params;
1080 return true;
1082 } elseif (!array_key_exists($address, $this->ReplyToQueue)) {
1083 $this->ReplyToQueue[$address] = $params;
1085 return true;
1088 return false;
1091 // Immediately add standard addresses without IDN.
1092 return call_user_func_array([$this, 'addAnAddress'], $params);
1096 * Add an address to one of the recipient arrays or to the ReplyTo array.
1097 * Addresses that have been added already return false, but do not throw exceptions.
1099 * @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo'
1100 * @param string $address The email address to send, resp. to reply to
1101 * @param string $name
1103 * @throws Exception
1105 * @return bool true on success, false if address already used or invalid in some way
1107 protected function addAnAddress($kind, $address, $name = '')
1109 if (!in_array($kind, ['to', 'cc', 'bcc', 'Reply-To'])) {
1110 $error_message = sprintf(
1111 '%s: %s',
1112 $this->lang('Invalid recipient kind'),
1113 $kind
1115 $this->setError($error_message);
1116 $this->edebug($error_message);
1117 if ($this->exceptions) {
1118 throw new Exception($error_message);
1121 return false;
1123 if (!static::validateAddress($address)) {
1124 $error_message = sprintf(
1125 '%s (%s): %s',
1126 $this->lang('invalid_address'),
1127 $kind,
1128 $address
1130 $this->setError($error_message);
1131 $this->edebug($error_message);
1132 if ($this->exceptions) {
1133 throw new Exception($error_message);
1136 return false;
1138 if ('Reply-To' !== $kind) {
1139 if (!array_key_exists(strtolower($address), $this->all_recipients)) {
1140 $this->{$kind}[] = [$address, $name];
1141 $this->all_recipients[strtolower($address)] = true;
1143 return true;
1145 } elseif (!array_key_exists(strtolower($address), $this->ReplyTo)) {
1146 $this->ReplyTo[strtolower($address)] = [$address, $name];
1148 return true;
1151 return false;
1155 * Parse and validate a string containing one or more RFC822-style comma-separated email addresses
1156 * of the form "display name <address>" into an array of name/address pairs.
1157 * Uses the imap_rfc822_parse_adrlist function if the IMAP extension is available.
1158 * Note that quotes in the name part are removed.
1160 * @see http://www.andrew.cmu.edu/user/agreen1/testing/mrbs/web/Mail/RFC822.php A more careful implementation
1162 * @param string $addrstr The address list string
1163 * @param bool $useimap Whether to use the IMAP extension to parse the list
1165 * @return array
1167 public static function parseAddresses($addrstr, $useimap = true)
1169 $addresses = [];
1170 if ($useimap && function_exists('imap_rfc822_parse_adrlist')) {
1171 //Use this built-in parser if it's available
1172 $list = imap_rfc822_parse_adrlist($addrstr, '');
1173 foreach ($list as $address) {
1174 if (('.SYNTAX-ERROR.' !== $address->host) && static::validateAddress(
1175 $address->mailbox . '@' . $address->host
1176 )) {
1177 $addresses[] = [
1178 'name' => (property_exists($address, 'personal') ? $address->personal : ''),
1179 'address' => $address->mailbox . '@' . $address->host,
1183 } else {
1184 //Use this simpler parser
1185 $list = explode(',', $addrstr);
1186 foreach ($list as $address) {
1187 $address = trim($address);
1188 //Is there a separate name part?
1189 if (strpos($address, '<') === false) {
1190 //No separate name, just use the whole thing
1191 if (static::validateAddress($address)) {
1192 $addresses[] = [
1193 'name' => '',
1194 'address' => $address,
1197 } else {
1198 list($name, $email) = explode('<', $address);
1199 $email = trim(str_replace('>', '', $email));
1200 if (static::validateAddress($email)) {
1201 $addresses[] = [
1202 'name' => trim(str_replace(['"', "'"], '', $name)),
1203 'address' => $email,
1210 return $addresses;
1214 * Set the From and FromName properties.
1216 * @param string $address
1217 * @param string $name
1218 * @param bool $auto Whether to also set the Sender address, defaults to true
1220 * @throws Exception
1222 * @return bool
1224 public function setFrom($address, $name = '', $auto = true)
1226 $address = trim($address);
1227 $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
1228 // Don't validate now addresses with IDN. Will be done in send().
1229 $pos = strrpos($address, '@');
1230 if ((false === $pos)
1231 || ((!$this->has8bitChars(substr($address, ++$pos)) || !static::idnSupported())
1232 && !static::validateAddress($address))
1234 $error_message = sprintf(
1235 '%s (From): %s',
1236 $this->lang('invalid_address'),
1237 $address
1239 $this->setError($error_message);
1240 $this->edebug($error_message);
1241 if ($this->exceptions) {
1242 throw new Exception($error_message);
1245 return false;
1247 $this->From = $address;
1248 $this->FromName = $name;
1249 if ($auto && empty($this->Sender)) {
1250 $this->Sender = $address;
1253 return true;
1257 * Return the Message-ID header of the last email.
1258 * Technically this is the value from the last time the headers were created,
1259 * but it's also the message ID of the last sent message except in
1260 * pathological cases.
1262 * @return string
1264 public function getLastMessageID()
1266 return $this->lastMessageID;
1270 * Check that a string looks like an email address.
1271 * Validation patterns supported:
1272 * * `auto` Pick best pattern automatically;
1273 * * `pcre8` Use the squiloople.com pattern, requires PCRE > 8.0;
1274 * * `pcre` Use old PCRE implementation;
1275 * * `php` Use PHP built-in FILTER_VALIDATE_EMAIL;
1276 * * `html5` Use the pattern given by the HTML5 spec for 'email' type form input elements.
1277 * * `noregex` Don't use a regex: super fast, really dumb.
1278 * Alternatively you may pass in a callable to inject your own validator, for example:
1280 * ```php
1281 * PHPMailer::validateAddress('user@example.com', function($address) {
1282 * return (strpos($address, '@') !== false);
1283 * });
1284 * ```
1286 * You can also set the PHPMailer::$validator static to a callable, allowing built-in methods to use your validator.
1288 * @param string $address The email address to check
1289 * @param string|callable $patternselect Which pattern to use
1291 * @return bool
1293 public static function validateAddress($address, $patternselect = null)
1295 if (null === $patternselect) {
1296 $patternselect = static::$validator;
1298 if (is_callable($patternselect)) {
1299 return $patternselect($address);
1301 //Reject line breaks in addresses; it's valid RFC5322, but not RFC5321
1302 if (strpos($address, "\n") !== false || strpos($address, "\r") !== false) {
1303 return false;
1305 switch ($patternselect) {
1306 case 'pcre': //Kept for BC
1307 case 'pcre8':
1309 * A more complex and more permissive version of the RFC5322 regex on which FILTER_VALIDATE_EMAIL
1310 * is based.
1311 * In addition to the addresses allowed by filter_var, also permits:
1312 * * dotless domains: `a@b`
1313 * * comments: `1234 @ local(blah) .machine .example`
1314 * * quoted elements: `'"test blah"@example.org'`
1315 * * numeric TLDs: `a@b.123`
1316 * * unbracketed IPv4 literals: `a@192.168.0.1`
1317 * * IPv6 literals: 'first.last@[IPv6:a1::]'
1318 * Not all of these will necessarily work for sending!
1320 * @see http://squiloople.com/2009/12/20/email-address-validation/
1321 * @copyright 2009-2010 Michael Rushton
1322 * Feel free to use and redistribute this code. But please keep this copyright notice.
1324 return (bool) preg_match(
1325 '/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)' .
1326 '((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)' .
1327 '(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)' .
1328 '([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*' .
1329 '(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)' .
1330 '(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}' .
1331 '|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:' .
1332 '|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}' .
1333 '|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD',
1334 $address
1336 case 'html5':
1338 * This is the pattern used in the HTML5 spec for validation of 'email' type form input elements.
1340 * @see http://www.whatwg.org/specs/web-apps/current-work/#e-mail-state-(type=email)
1342 return (bool) preg_match(
1343 '/^[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}' .
1344 '[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/sD',
1345 $address
1347 case 'php':
1348 default:
1349 return (bool) filter_var($address, FILTER_VALIDATE_EMAIL);
1354 * Tells whether IDNs (Internationalized Domain Names) are supported or not. This requires the
1355 * `intl` and `mbstring` PHP extensions.
1357 * @return bool `true` if required functions for IDN support are present
1359 public static function idnSupported()
1361 return function_exists('idn_to_ascii') && function_exists('mb_convert_encoding');
1365 * Converts IDN in given email address to its ASCII form, also known as punycode, if possible.
1366 * Important: Address must be passed in same encoding as currently set in PHPMailer::$CharSet.
1367 * This function silently returns unmodified address if:
1368 * - No conversion is necessary (i.e. domain name is not an IDN, or is already in ASCII form)
1369 * - Conversion to punycode is impossible (e.g. required PHP functions are not available)
1370 * or fails for any reason (e.g. domain contains characters not allowed in an IDN).
1372 * @see PHPMailer::$CharSet
1374 * @param string $address The email address to convert
1376 * @return string The encoded address in ASCII form
1378 public function punyencodeAddress($address)
1380 // Verify we have required functions, CharSet, and at-sign.
1381 $pos = strrpos($address, '@');
1382 if (!empty($this->CharSet) &&
1383 false !== $pos &&
1384 static::idnSupported()
1386 $domain = substr($address, ++$pos);
1387 // Verify CharSet string is a valid one, and domain properly encoded in this CharSet.
1388 if ($this->has8bitChars($domain) && @mb_check_encoding($domain, $this->CharSet)) {
1389 $domain = mb_convert_encoding($domain, 'UTF-8', $this->CharSet);
1390 //Ignore IDE complaints about this line - method signature changed in PHP 5.4
1391 $errorcode = 0;
1392 $punycode = idn_to_ascii($domain, $errorcode, INTL_IDNA_VARIANT_UTS46);
1393 if (false !== $punycode) {
1394 return substr($address, 0, $pos) . $punycode;
1399 return $address;
1403 * Create a message and send it.
1404 * Uses the sending method specified by $Mailer.
1406 * @throws Exception
1408 * @return bool false on error - See the ErrorInfo property for details of the error
1410 public function send()
1412 try {
1413 if (!$this->preSend()) {
1414 return false;
1417 return $this->postSend();
1418 } catch (Exception $exc) {
1419 $this->mailHeader = '';
1420 $this->setError($exc->getMessage());
1421 if ($this->exceptions) {
1422 throw $exc;
1425 return false;
1430 * Prepare a message for sending.
1432 * @throws Exception
1434 * @return bool
1436 public function preSend()
1438 if ('smtp' === $this->Mailer
1439 || ('mail' === $this->Mailer && stripos(PHP_OS, 'WIN') === 0)
1441 //SMTP mandates RFC-compliant line endings
1442 //and it's also used with mail() on Windows
1443 static::setLE("\r\n");
1444 } else {
1445 //Maintain backward compatibility with legacy Linux command line mailers
1446 static::setLE(PHP_EOL);
1448 //Check for buggy PHP versions that add a header with an incorrect line break
1449 if ('mail' === $this->Mailer
1450 && ((PHP_VERSION_ID >= 70000 && PHP_VERSION_ID < 70017)
1451 || (PHP_VERSION_ID >= 70100 && PHP_VERSION_ID < 70103))
1452 && ini_get('mail.add_x_header') === '1'
1453 && stripos(PHP_OS, 'WIN') === 0
1455 trigger_error(
1456 'Your version of PHP is affected by a bug that may result in corrupted messages.' .
1457 ' To fix it, switch to sending using SMTP, disable the mail.add_x_header option in' .
1458 ' your php.ini, switch to MacOS or Linux, or upgrade your PHP to version 7.0.17+ or 7.1.3+.',
1459 E_USER_WARNING
1463 try {
1464 $this->error_count = 0; // Reset errors
1465 $this->mailHeader = '';
1467 // Dequeue recipient and Reply-To addresses with IDN
1468 foreach (array_merge($this->RecipientsQueue, $this->ReplyToQueue) as $params) {
1469 $params[1] = $this->punyencodeAddress($params[1]);
1470 call_user_func_array([$this, 'addAnAddress'], $params);
1472 if (count($this->to) + count($this->cc) + count($this->bcc) < 1) {
1473 throw new Exception($this->lang('provide_address'), self::STOP_CRITICAL);
1476 // Validate From, Sender, and ConfirmReadingTo addresses
1477 foreach (['From', 'Sender', 'ConfirmReadingTo'] as $address_kind) {
1478 $this->$address_kind = trim($this->$address_kind);
1479 if (empty($this->$address_kind)) {
1480 continue;
1482 $this->$address_kind = $this->punyencodeAddress($this->$address_kind);
1483 if (!static::validateAddress($this->$address_kind)) {
1484 $error_message = sprintf(
1485 '%s (%s): %s',
1486 $this->lang('invalid_address'),
1487 $address_kind,
1488 $this->$address_kind
1490 $this->setError($error_message);
1491 $this->edebug($error_message);
1492 if ($this->exceptions) {
1493 throw new Exception($error_message);
1496 return false;
1500 // Set whether the message is multipart/alternative
1501 if ($this->alternativeExists()) {
1502 $this->ContentType = static::CONTENT_TYPE_MULTIPART_ALTERNATIVE;
1505 $this->setMessageType();
1506 // Refuse to send an empty message unless we are specifically allowing it
1507 if (!$this->AllowEmpty && empty($this->Body)) {
1508 throw new Exception($this->lang('empty_message'), self::STOP_CRITICAL);
1511 //Trim subject consistently
1512 $this->Subject = trim($this->Subject);
1513 // Create body before headers in case body makes changes to headers (e.g. altering transfer encoding)
1514 $this->MIMEHeader = '';
1515 $this->MIMEBody = $this->createBody();
1516 // createBody may have added some headers, so retain them
1517 $tempheaders = $this->MIMEHeader;
1518 $this->MIMEHeader = $this->createHeader();
1519 $this->MIMEHeader .= $tempheaders;
1521 // To capture the complete message when using mail(), create
1522 // an extra header list which createHeader() doesn't fold in
1523 if ('mail' === $this->Mailer) {
1524 if (count($this->to) > 0) {
1525 $this->mailHeader .= $this->addrAppend('To', $this->to);
1526 } else {
1527 $this->mailHeader .= $this->headerLine('To', 'undisclosed-recipients:;');
1529 $this->mailHeader .= $this->headerLine(
1530 'Subject',
1531 $this->encodeHeader($this->secureHeader($this->Subject))
1535 // Sign with DKIM if enabled
1536 if (!empty($this->DKIM_domain)
1537 && !empty($this->DKIM_selector)
1538 && (!empty($this->DKIM_private_string)
1539 || (!empty($this->DKIM_private)
1540 && static::isPermittedPath($this->DKIM_private)
1541 && file_exists($this->DKIM_private)
1545 $header_dkim = $this->DKIM_Add(
1546 $this->MIMEHeader . $this->mailHeader,
1547 $this->encodeHeader($this->secureHeader($this->Subject)),
1548 $this->MIMEBody
1550 $this->MIMEHeader = rtrim($this->MIMEHeader, "\r\n ") . static::$LE .
1551 static::normalizeBreaks($header_dkim) . static::$LE;
1554 return true;
1555 } catch (Exception $exc) {
1556 $this->setError($exc->getMessage());
1557 if ($this->exceptions) {
1558 throw $exc;
1561 return false;
1566 * Actually send a message via the selected mechanism.
1568 * @throws Exception
1570 * @return bool
1572 public function postSend()
1574 try {
1575 // Choose the mailer and send through it
1576 switch ($this->Mailer) {
1577 case 'sendmail':
1578 case 'qmail':
1579 return $this->sendmailSend($this->MIMEHeader, $this->MIMEBody);
1580 case 'smtp':
1581 return $this->smtpSend($this->MIMEHeader, $this->MIMEBody);
1582 case 'mail':
1583 return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
1584 default:
1585 $sendMethod = $this->Mailer . 'Send';
1586 if (method_exists($this, $sendMethod)) {
1587 return $this->$sendMethod($this->MIMEHeader, $this->MIMEBody);
1590 return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
1592 } catch (Exception $exc) {
1593 $this->setError($exc->getMessage());
1594 $this->edebug($exc->getMessage());
1595 if ($this->exceptions) {
1596 throw $exc;
1600 return false;
1604 * Send mail using the $Sendmail program.
1606 * @see PHPMailer::$Sendmail
1608 * @param string $header The message headers
1609 * @param string $body The message body
1611 * @throws Exception
1613 * @return bool
1615 protected function sendmailSend($header, $body)
1617 $header = rtrim($header, "\r\n ") . static::$LE . static::$LE;
1619 // CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped.
1620 if (!empty($this->Sender) && self::isShellSafe($this->Sender)) {
1621 if ('qmail' === $this->Mailer) {
1622 $sendmailFmt = '%s -f%s';
1623 } else {
1624 $sendmailFmt = '%s -oi -f%s -t';
1626 } elseif ('qmail' === $this->Mailer) {
1627 $sendmailFmt = '%s';
1628 } else {
1629 $sendmailFmt = '%s -oi -t';
1632 $sendmail = sprintf($sendmailFmt, escapeshellcmd($this->Sendmail), $this->Sender);
1634 if ($this->SingleTo) {
1635 foreach ($this->SingleToArray as $toAddr) {
1636 $mail = @popen($sendmail, 'w');
1637 if (!$mail) {
1638 throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1640 fwrite($mail, 'To: ' . $toAddr . "\n");
1641 fwrite($mail, $header);
1642 fwrite($mail, $body);
1643 $result = pclose($mail);
1644 $this->doCallback(
1645 ($result === 0),
1646 [$toAddr],
1647 $this->cc,
1648 $this->bcc,
1649 $this->Subject,
1650 $body,
1651 $this->From,
1654 if (0 !== $result) {
1655 throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1658 } else {
1659 $mail = @popen($sendmail, 'w');
1660 if (!$mail) {
1661 throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1663 fwrite($mail, $header);
1664 fwrite($mail, $body);
1665 $result = pclose($mail);
1666 $this->doCallback(
1667 ($result === 0),
1668 $this->to,
1669 $this->cc,
1670 $this->bcc,
1671 $this->Subject,
1672 $body,
1673 $this->From,
1676 if (0 !== $result) {
1677 throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1681 return true;
1685 * Fix CVE-2016-10033 and CVE-2016-10045 by disallowing potentially unsafe shell characters.
1686 * Note that escapeshellarg and escapeshellcmd are inadequate for our purposes, especially on Windows.
1688 * @see https://github.com/PHPMailer/PHPMailer/issues/924 CVE-2016-10045 bug report
1690 * @param string $string The string to be validated
1692 * @return bool
1694 protected static function isShellSafe($string)
1696 // Future-proof
1697 if (escapeshellcmd($string) !== $string
1698 || !in_array(escapeshellarg($string), ["'$string'", "\"$string\""])
1700 return false;
1703 $length = strlen($string);
1705 for ($i = 0; $i < $length; ++$i) {
1706 $c = $string[$i];
1708 // All other characters have a special meaning in at least one common shell, including = and +.
1709 // Full stop (.) has a special meaning in cmd.exe, but its impact should be negligible here.
1710 // Note that this does permit non-Latin alphanumeric characters based on the current locale.
1711 if (!ctype_alnum($c) && strpos('@_-.', $c) === false) {
1712 return false;
1716 return true;
1720 * Check whether a file path is of a permitted type.
1721 * Used to reject URLs and phar files from functions that access local file paths,
1722 * such as addAttachment.
1724 * @param string $path A relative or absolute path to a file
1726 * @return bool
1728 protected static function isPermittedPath($path)
1730 return !preg_match('#^[a-z]+://#i', $path);
1734 * Send mail using the PHP mail() function.
1736 * @see http://www.php.net/manual/en/book.mail.php
1738 * @param string $header The message headers
1739 * @param string $body The message body
1741 * @throws Exception
1743 * @return bool
1745 protected function mailSend($header, $body)
1747 $header = rtrim($header, "\r\n ") . static::$LE . static::$LE;
1749 $toArr = [];
1750 foreach ($this->to as $toaddr) {
1751 $toArr[] = $this->addrFormat($toaddr);
1753 $to = implode(', ', $toArr);
1755 $params = null;
1756 //This sets the SMTP envelope sender which gets turned into a return-path header by the receiver
1757 //A space after `-f` is optional, but there is a long history of its presence
1758 //causing problems, so we don't use one
1759 //Exim docs: http://www.exim.org/exim-html-current/doc/html/spec_html/ch-the_exim_command_line.html
1760 //Sendmail docs: http://www.sendmail.org/~ca/email/man/sendmail.html
1761 //Qmail docs: http://www.qmail.org/man/man8/qmail-inject.html
1762 //Example problem: https://www.drupal.org/node/1057954
1763 // CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped.
1764 if (!empty($this->Sender) && static::validateAddress($this->Sender) && self::isShellSafe($this->Sender)) {
1765 $params = sprintf('-f%s', $this->Sender);
1767 if (!empty($this->Sender) && static::validateAddress($this->Sender)) {
1768 $old_from = ini_get('sendmail_from');
1769 ini_set('sendmail_from', $this->Sender);
1771 $result = false;
1772 if ($this->SingleTo && count($toArr) > 1) {
1773 foreach ($toArr as $toAddr) {
1774 $result = $this->mailPassthru($toAddr, $this->Subject, $body, $header, $params);
1775 $this->doCallback($result, [$toAddr], $this->cc, $this->bcc, $this->Subject, $body, $this->From, []);
1777 } else {
1778 $result = $this->mailPassthru($to, $this->Subject, $body, $header, $params);
1779 $this->doCallback($result, $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From, []);
1781 if (isset($old_from)) {
1782 ini_set('sendmail_from', $old_from);
1784 if (!$result) {
1785 throw new Exception($this->lang('instantiate'), self::STOP_CRITICAL);
1788 return true;
1792 * Get an instance to use for SMTP operations.
1793 * Override this function to load your own SMTP implementation,
1794 * or set one with setSMTPInstance.
1796 * @return SMTP
1798 public function getSMTPInstance()
1800 if (!is_object($this->smtp)) {
1801 $this->smtp = new SMTP();
1804 return $this->smtp;
1808 * Provide an instance to use for SMTP operations.
1810 * @return SMTP
1812 public function setSMTPInstance(SMTP $smtp)
1814 $this->smtp = $smtp;
1816 return $this->smtp;
1820 * Send mail via SMTP.
1821 * Returns false if there is a bad MAIL FROM, RCPT, or DATA input.
1823 * @see PHPMailer::setSMTPInstance() to use a different class.
1825 * @uses \PHPMailer\PHPMailer\SMTP
1827 * @param string $header The message headers
1828 * @param string $body The message body
1830 * @throws Exception
1832 * @return bool
1834 protected function smtpSend($header, $body)
1836 $header = rtrim($header, "\r\n ") . static::$LE . static::$LE;
1837 $bad_rcpt = [];
1838 if (!$this->smtpConnect($this->SMTPOptions)) {
1839 throw new Exception($this->lang('smtp_connect_failed'), self::STOP_CRITICAL);
1841 //Sender already validated in preSend()
1842 if ('' === $this->Sender) {
1843 $smtp_from = $this->From;
1844 } else {
1845 $smtp_from = $this->Sender;
1847 if (!$this->smtp->mail($smtp_from)) {
1848 $this->setError($this->lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp->getError()));
1849 throw new Exception($this->ErrorInfo, self::STOP_CRITICAL);
1852 $callbacks = [];
1853 // Attempt to send to all recipients
1854 foreach ([$this->to, $this->cc, $this->bcc] as $togroup) {
1855 foreach ($togroup as $to) {
1856 if (!$this->smtp->recipient($to[0], $this->dsn)) {
1857 $error = $this->smtp->getError();
1858 $bad_rcpt[] = ['to' => $to[0], 'error' => $error['detail']];
1859 $isSent = false;
1860 } else {
1861 $isSent = true;
1864 $callbacks[] = ['issent'=>$isSent, 'to'=>$to[0]];
1868 // Only send the DATA command if we have viable recipients
1869 if ((count($this->all_recipients) > count($bad_rcpt)) && !$this->smtp->data($header . $body)) {
1870 throw new Exception($this->lang('data_not_accepted'), self::STOP_CRITICAL);
1873 $smtp_transaction_id = $this->smtp->getLastTransactionID();
1875 if ($this->SMTPKeepAlive) {
1876 $this->smtp->reset();
1877 } else {
1878 $this->smtp->quit();
1879 $this->smtp->close();
1882 foreach ($callbacks as $cb) {
1883 $this->doCallback(
1884 $cb['issent'],
1885 [$cb['to']],
1888 $this->Subject,
1889 $body,
1890 $this->From,
1891 ['smtp_transaction_id' => $smtp_transaction_id]
1895 //Create error message for any bad addresses
1896 if (count($bad_rcpt) > 0) {
1897 $errstr = '';
1898 foreach ($bad_rcpt as $bad) {
1899 $errstr .= $bad['to'] . ': ' . $bad['error'];
1901 throw new Exception($this->lang('recipients_failed') . $errstr, self::STOP_CONTINUE);
1904 return true;
1908 * Initiate a connection to an SMTP server.
1909 * Returns false if the operation failed.
1911 * @param array $options An array of options compatible with stream_context_create()
1913 * @throws Exception
1915 * @uses \PHPMailer\PHPMailer\SMTP
1917 * @return bool
1919 public function smtpConnect($options = null)
1921 if (null === $this->smtp) {
1922 $this->smtp = $this->getSMTPInstance();
1925 //If no options are provided, use whatever is set in the instance
1926 if (null === $options) {
1927 $options = $this->SMTPOptions;
1930 // Already connected?
1931 if ($this->smtp->connected()) {
1932 return true;
1935 $this->smtp->setTimeout($this->Timeout);
1936 $this->smtp->setDebugLevel($this->SMTPDebug);
1937 $this->smtp->setDebugOutput($this->Debugoutput);
1938 $this->smtp->setVerp($this->do_verp);
1939 $hosts = explode(';', $this->Host);
1940 $lastexception = null;
1942 foreach ($hosts as $hostentry) {
1943 $hostinfo = [];
1944 if (!preg_match(
1945 '/^((ssl|tls):\/\/)*([a-zA-Z\d.-]*|\[[a-fA-F\d:]+]):?(\d*)$/',
1946 trim($hostentry),
1947 $hostinfo
1948 )) {
1949 $this->edebug($this->lang('connect_host') . ' ' . $hostentry);
1950 // Not a valid host entry
1951 continue;
1953 // $hostinfo[2]: optional ssl or tls prefix
1954 // $hostinfo[3]: the hostname
1955 // $hostinfo[4]: optional port number
1956 // The host string prefix can temporarily override the current setting for SMTPSecure
1957 // If it's not specified, the default value is used
1959 //Check the host name is a valid name or IP address before trying to use it
1960 if (!static::isValidHost($hostinfo[3])) {
1961 $this->edebug($this->lang('connect_host') . ' ' . $hostentry);
1962 continue;
1964 $prefix = '';
1965 $secure = $this->SMTPSecure;
1966 $tls = (static::ENCRYPTION_STARTTLS === $this->SMTPSecure);
1967 if ('ssl' === $hostinfo[2] || ('' === $hostinfo[2] && static::ENCRYPTION_SMTPS === $this->SMTPSecure)) {
1968 $prefix = 'ssl://';
1969 $tls = false; // Can't have SSL and TLS at the same time
1970 $secure = static::ENCRYPTION_SMTPS;
1971 } elseif ('tls' === $hostinfo[2]) {
1972 $tls = true;
1973 // tls doesn't use a prefix
1974 $secure = static::ENCRYPTION_STARTTLS;
1976 //Do we need the OpenSSL extension?
1977 $sslext = defined('OPENSSL_ALGO_SHA256');
1978 if (static::ENCRYPTION_STARTTLS === $secure || static::ENCRYPTION_SMTPS === $secure) {
1979 //Check for an OpenSSL constant rather than using extension_loaded, which is sometimes disabled
1980 if (!$sslext) {
1981 throw new Exception($this->lang('extension_missing') . 'openssl', self::STOP_CRITICAL);
1984 $host = $hostinfo[3];
1985 $port = $this->Port;
1986 $tport = (int) $hostinfo[4];
1987 if ($tport > 0 && $tport < 65536) {
1988 $port = $tport;
1990 if ($this->smtp->connect($prefix . $host, $port, $this->Timeout, $options)) {
1991 try {
1992 if ($this->Helo) {
1993 $hello = $this->Helo;
1994 } else {
1995 $hello = $this->serverHostname();
1997 $this->smtp->hello($hello);
1998 //Automatically enable TLS encryption if:
1999 // * it's not disabled
2000 // * we have openssl extension
2001 // * we are not already using SSL
2002 // * the server offers STARTTLS
2003 if ($this->SMTPAutoTLS && $sslext && 'ssl' !== $secure && $this->smtp->getServerExt('STARTTLS')) {
2004 $tls = true;
2006 if ($tls) {
2007 if (!$this->smtp->startTLS()) {
2008 throw new Exception($this->lang('connect_host'));
2010 // We must resend EHLO after TLS negotiation
2011 $this->smtp->hello($hello);
2013 if ($this->SMTPAuth && !$this->smtp->authenticate(
2014 $this->Username,
2015 $this->Password,
2016 $this->AuthType,
2017 $this->oauth
2018 )) {
2019 throw new Exception($this->lang('authenticate'));
2022 return true;
2023 } catch (Exception $exc) {
2024 $lastexception = $exc;
2025 $this->edebug($exc->getMessage());
2026 // We must have connected, but then failed TLS or Auth, so close connection nicely
2027 $this->smtp->quit();
2031 // If we get here, all connection attempts have failed, so close connection hard
2032 $this->smtp->close();
2033 // As we've caught all exceptions, just report whatever the last one was
2034 if ($this->exceptions && null !== $lastexception) {
2035 throw $lastexception;
2038 return false;
2042 * Close the active SMTP session if one exists.
2044 public function smtpClose()
2046 if ((null !== $this->smtp) && $this->smtp->connected()) {
2047 $this->smtp->quit();
2048 $this->smtp->close();
2053 * Set the language for error messages.
2054 * Returns false if it cannot load the language file.
2055 * The default language is English.
2057 * @param string $langcode ISO 639-1 2-character language code (e.g. French is "fr")
2058 * @param string $lang_path Path to the language file directory, with trailing separator (slash)
2060 * @return bool
2062 public function setLanguage($langcode = 'en', $lang_path = '')
2064 // Backwards compatibility for renamed language codes
2065 $renamed_langcodes = [
2066 'br' => 'pt_br',
2067 'cz' => 'cs',
2068 'dk' => 'da',
2069 'no' => 'nb',
2070 'se' => 'sv',
2071 'rs' => 'sr',
2072 'tg' => 'tl',
2075 if (isset($renamed_langcodes[$langcode])) {
2076 $langcode = $renamed_langcodes[$langcode];
2079 // Define full set of translatable strings in English
2080 $PHPMAILER_LANG = [
2081 'authenticate' => 'SMTP Error: Could not authenticate.',
2082 'connect_host' => 'SMTP Error: Could not connect to SMTP host.',
2083 'data_not_accepted' => 'SMTP Error: data not accepted.',
2084 'empty_message' => 'Message body empty',
2085 'encoding' => 'Unknown encoding: ',
2086 'execute' => 'Could not execute: ',
2087 'file_access' => 'Could not access file: ',
2088 'file_open' => 'File Error: Could not open file: ',
2089 'from_failed' => 'The following From address failed: ',
2090 'instantiate' => 'Could not instantiate mail function.',
2091 'invalid_address' => 'Invalid address: ',
2092 'mailer_not_supported' => ' mailer is not supported.',
2093 'provide_address' => 'You must provide at least one recipient email address.',
2094 'recipients_failed' => 'SMTP Error: The following recipients failed: ',
2095 'signing' => 'Signing Error: ',
2096 'smtp_connect_failed' => 'SMTP connect() failed.',
2097 'smtp_error' => 'SMTP server error: ',
2098 'variable_set' => 'Cannot set or reset variable: ',
2099 'extension_missing' => 'Extension missing: ',
2101 if (empty($lang_path)) {
2102 // Calculate an absolute path so it can work if CWD is not here
2103 $lang_path = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'language' . DIRECTORY_SEPARATOR;
2105 //Validate $langcode
2106 if (!preg_match('/^[a-z]{2}(?:_[a-zA-Z]{2})?$/', $langcode)) {
2107 $langcode = 'en';
2109 $foundlang = true;
2110 $lang_file = $lang_path . 'phpmailer.lang-' . $langcode . '.php';
2111 // There is no English translation file
2112 if ('en' !== $langcode) {
2113 // Make sure language file path is readable
2114 if (!static::isPermittedPath($lang_file) || !file_exists($lang_file)) {
2115 $foundlang = false;
2116 } else {
2117 // Overwrite language-specific strings.
2118 // This way we'll never have missing translation keys.
2119 $foundlang = include $lang_file;
2122 $this->language = $PHPMAILER_LANG;
2124 return (bool) $foundlang; // Returns false if language not found
2128 * Get the array of strings for the current language.
2130 * @return array
2132 public function getTranslations()
2134 return $this->language;
2138 * Create recipient headers.
2140 * @param string $type
2141 * @param array $addr An array of recipients,
2142 * where each recipient is a 2-element indexed array with element 0 containing an address
2143 * and element 1 containing a name, like:
2144 * [['joe@example.com', 'Joe User'], ['zoe@example.com', 'Zoe User']]
2146 * @return string
2148 public function addrAppend($type, $addr)
2150 $addresses = [];
2151 foreach ($addr as $address) {
2152 $addresses[] = $this->addrFormat($address);
2155 return $type . ': ' . implode(', ', $addresses) . static::$LE;
2159 * Format an address for use in a message header.
2161 * @param array $addr A 2-element indexed array, element 0 containing an address, element 1 containing a name like
2162 * ['joe@example.com', 'Joe User']
2164 * @return string
2166 public function addrFormat($addr)
2168 if (empty($addr[1])) { // No name provided
2169 return $this->secureHeader($addr[0]);
2172 return $this->encodeHeader($this->secureHeader($addr[1]), 'phrase') .
2173 ' <' . $this->secureHeader($addr[0]) . '>';
2177 * Word-wrap message.
2178 * For use with mailers that do not automatically perform wrapping
2179 * and for quoted-printable encoded messages.
2180 * Original written by philippe.
2182 * @param string $message The message to wrap
2183 * @param int $length The line length to wrap to
2184 * @param bool $qp_mode Whether to run in Quoted-Printable mode
2186 * @return string
2188 public function wrapText($message, $length, $qp_mode = false)
2190 if ($qp_mode) {
2191 $soft_break = sprintf(' =%s', static::$LE);
2192 } else {
2193 $soft_break = static::$LE;
2195 // If utf-8 encoding is used, we will need to make sure we don't
2196 // split multibyte characters when we wrap
2197 $is_utf8 = static::CHARSET_UTF8 === strtolower($this->CharSet);
2198 $lelen = strlen(static::$LE);
2199 $crlflen = strlen(static::$LE);
2201 $message = static::normalizeBreaks($message);
2202 //Remove a trailing line break
2203 if (substr($message, -$lelen) === static::$LE) {
2204 $message = substr($message, 0, -$lelen);
2207 //Split message into lines
2208 $lines = explode(static::$LE, $message);
2209 //Message will be rebuilt in here
2210 $message = '';
2211 foreach ($lines as $line) {
2212 $words = explode(' ', $line);
2213 $buf = '';
2214 $firstword = true;
2215 foreach ($words as $word) {
2216 if ($qp_mode && (strlen($word) > $length)) {
2217 $space_left = $length - strlen($buf) - $crlflen;
2218 if (!$firstword) {
2219 if ($space_left > 20) {
2220 $len = $space_left;
2221 if ($is_utf8) {
2222 $len = $this->utf8CharBoundary($word, $len);
2223 } elseif ('=' === substr($word, $len - 1, 1)) {
2224 --$len;
2225 } elseif ('=' === substr($word, $len - 2, 1)) {
2226 $len -= 2;
2228 $part = substr($word, 0, $len);
2229 $word = substr($word, $len);
2230 $buf .= ' ' . $part;
2231 $message .= $buf . sprintf('=%s', static::$LE);
2232 } else {
2233 $message .= $buf . $soft_break;
2235 $buf = '';
2237 while ($word !== '') {
2238 if ($length <= 0) {
2239 break;
2241 $len = $length;
2242 if ($is_utf8) {
2243 $len = $this->utf8CharBoundary($word, $len);
2244 } elseif ('=' === substr($word, $len - 1, 1)) {
2245 --$len;
2246 } elseif ('=' === substr($word, $len - 2, 1)) {
2247 $len -= 2;
2249 $part = substr($word, 0, $len);
2250 $word = (string) substr($word, $len);
2252 if ($word !== '') {
2253 $message .= $part . sprintf('=%s', static::$LE);
2254 } else {
2255 $buf = $part;
2258 } else {
2259 $buf_o = $buf;
2260 if (!$firstword) {
2261 $buf .= ' ';
2263 $buf .= $word;
2265 if ('' !== $buf_o && strlen($buf) > $length) {
2266 $message .= $buf_o . $soft_break;
2267 $buf = $word;
2270 $firstword = false;
2272 $message .= $buf . static::$LE;
2275 return $message;
2279 * Find the last character boundary prior to $maxLength in a utf-8
2280 * quoted-printable encoded string.
2281 * Original written by Colin Brown.
2283 * @param string $encodedText utf-8 QP text
2284 * @param int $maxLength Find the last character boundary prior to this length
2286 * @return int
2288 public function utf8CharBoundary($encodedText, $maxLength)
2290 $foundSplitPos = false;
2291 $lookBack = 3;
2292 while (!$foundSplitPos) {
2293 $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
2294 $encodedCharPos = strpos($lastChunk, '=');
2295 if (false !== $encodedCharPos) {
2296 // Found start of encoded character byte within $lookBack block.
2297 // Check the encoded byte value (the 2 chars after the '=')
2298 $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
2299 $dec = hexdec($hex);
2300 if ($dec < 128) {
2301 // Single byte character.
2302 // If the encoded char was found at pos 0, it will fit
2303 // otherwise reduce maxLength to start of the encoded char
2304 if ($encodedCharPos > 0) {
2305 $maxLength -= $lookBack - $encodedCharPos;
2307 $foundSplitPos = true;
2308 } elseif ($dec >= 192) {
2309 // First byte of a multi byte character
2310 // Reduce maxLength to split at start of character
2311 $maxLength -= $lookBack - $encodedCharPos;
2312 $foundSplitPos = true;
2313 } elseif ($dec < 192) {
2314 // Middle byte of a multi byte character, look further back
2315 $lookBack += 3;
2317 } else {
2318 // No encoded character found
2319 $foundSplitPos = true;
2323 return $maxLength;
2327 * Apply word wrapping to the message body.
2328 * Wraps the message body to the number of chars set in the WordWrap property.
2329 * You should only do this to plain-text bodies as wrapping HTML tags may break them.
2330 * This is called automatically by createBody(), so you don't need to call it yourself.
2332 public function setWordWrap()
2334 if ($this->WordWrap < 1) {
2335 return;
2338 switch ($this->message_type) {
2339 case 'alt':
2340 case 'alt_inline':
2341 case 'alt_attach':
2342 case 'alt_inline_attach':
2343 $this->AltBody = $this->wrapText($this->AltBody, $this->WordWrap);
2344 break;
2345 default:
2346 $this->Body = $this->wrapText($this->Body, $this->WordWrap);
2347 break;
2352 * Assemble message headers.
2354 * @return string The assembled headers
2356 public function createHeader()
2358 $result = '';
2360 $result .= $this->headerLine('Date', '' === $this->MessageDate ? self::rfcDate() : $this->MessageDate);
2362 // To be created automatically by mail()
2363 if ($this->SingleTo) {
2364 if ('mail' !== $this->Mailer) {
2365 foreach ($this->to as $toaddr) {
2366 $this->SingleToArray[] = $this->addrFormat($toaddr);
2369 } elseif (count($this->to) > 0) {
2370 if ('mail' !== $this->Mailer) {
2371 $result .= $this->addrAppend('To', $this->to);
2373 } elseif (count($this->cc) === 0) {
2374 $result .= $this->headerLine('To', 'undisclosed-recipients:;');
2377 $result .= $this->addrAppend('From', [[trim($this->From), $this->FromName]]);
2379 // sendmail and mail() extract Cc from the header before sending
2380 if (count($this->cc) > 0) {
2381 $result .= $this->addrAppend('Cc', $this->cc);
2384 // sendmail and mail() extract Bcc from the header before sending
2385 if ((
2386 'sendmail' === $this->Mailer || 'qmail' === $this->Mailer || 'mail' === $this->Mailer
2388 && count($this->bcc) > 0
2390 $result .= $this->addrAppend('Bcc', $this->bcc);
2393 if (count($this->ReplyTo) > 0) {
2394 $result .= $this->addrAppend('Reply-To', $this->ReplyTo);
2397 // mail() sets the subject itself
2398 if ('mail' !== $this->Mailer) {
2399 $result .= $this->headerLine('Subject', $this->encodeHeader($this->secureHeader($this->Subject)));
2402 // Only allow a custom message ID if it conforms to RFC 5322 section 3.6.4
2403 // https://tools.ietf.org/html/rfc5322#section-3.6.4
2404 if ('' !== $this->MessageID && preg_match('/^<.*@.*>$/', $this->MessageID)) {
2405 $this->lastMessageID = $this->MessageID;
2406 } else {
2407 $this->lastMessageID = sprintf('<%s@%s>', $this->uniqueid, $this->serverHostname());
2409 $result .= $this->headerLine('Message-ID', $this->lastMessageID);
2410 if (null !== $this->Priority) {
2411 $result .= $this->headerLine('X-Priority', $this->Priority);
2413 if ('' === $this->XMailer) {
2414 $result .= $this->headerLine(
2415 'X-Mailer',
2416 'PHPMailer ' . self::VERSION . ' (https://github.com/PHPMailer/PHPMailer)'
2418 } else {
2419 $myXmailer = trim($this->XMailer);
2420 if ($myXmailer) {
2421 $result .= $this->headerLine('X-Mailer', $myXmailer);
2425 if ('' !== $this->ConfirmReadingTo) {
2426 $result .= $this->headerLine('Disposition-Notification-To', '<' . $this->ConfirmReadingTo . '>');
2429 // Add custom headers
2430 foreach ($this->CustomHeader as $header) {
2431 $result .= $this->headerLine(
2432 trim($header[0]),
2433 $this->encodeHeader(trim($header[1]))
2436 if (!$this->sign_key_file) {
2437 $result .= $this->headerLine('MIME-Version', '1.0');
2438 $result .= $this->getMailMIME();
2441 return $result;
2445 * Get the message MIME type headers.
2447 * @return string
2449 public function getMailMIME()
2451 $result = '';
2452 $ismultipart = true;
2453 switch ($this->message_type) {
2454 case 'inline':
2455 $result .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';');
2456 $result .= $this->textLine(' boundary="' . $this->boundary[1] . '"');
2457 break;
2458 case 'attach':
2459 case 'inline_attach':
2460 case 'alt_attach':
2461 case 'alt_inline_attach':
2462 $result .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_MIXED . ';');
2463 $result .= $this->textLine(' boundary="' . $this->boundary[1] . '"');
2464 break;
2465 case 'alt':
2466 case 'alt_inline':
2467 $result .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_ALTERNATIVE . ';');
2468 $result .= $this->textLine(' boundary="' . $this->boundary[1] . '"');
2469 break;
2470 default:
2471 // Catches case 'plain': and case '':
2472 $result .= $this->textLine('Content-Type: ' . $this->ContentType . '; charset=' . $this->CharSet);
2473 $ismultipart = false;
2474 break;
2476 // RFC1341 part 5 says 7bit is assumed if not specified
2477 if (static::ENCODING_7BIT !== $this->Encoding) {
2478 // RFC 2045 section 6.4 says multipart MIME parts may only use 7bit, 8bit or binary CTE
2479 if ($ismultipart) {
2480 if (static::ENCODING_8BIT === $this->Encoding) {
2481 $result .= $this->headerLine('Content-Transfer-Encoding', static::ENCODING_8BIT);
2483 // The only remaining alternatives are quoted-printable and base64, which are both 7bit compatible
2484 } else {
2485 $result .= $this->headerLine('Content-Transfer-Encoding', $this->Encoding);
2489 if ('mail' !== $this->Mailer) {
2490 // $result .= static::$LE;
2493 return $result;
2497 * Returns the whole MIME message.
2498 * Includes complete headers and body.
2499 * Only valid post preSend().
2501 * @see PHPMailer::preSend()
2503 * @return string
2505 public function getSentMIMEMessage()
2507 return rtrim($this->MIMEHeader . $this->mailHeader, "\n\r") . static::$LE . static::$LE . $this->MIMEBody;
2511 * Create a unique ID to use for boundaries.
2513 * @return string
2515 protected function generateId()
2517 $len = 32; //32 bytes = 256 bits
2518 $bytes = '';
2519 if (function_exists('random_bytes')) {
2520 try {
2521 $bytes = random_bytes($len);
2522 } catch (\Exception $e) {
2523 //Do nothing
2525 } elseif (function_exists('openssl_random_pseudo_bytes')) {
2526 /** @noinspection CryptographicallySecureRandomnessInspection */
2527 $bytes = openssl_random_pseudo_bytes($len);
2529 if ($bytes === '') {
2530 //We failed to produce a proper random string, so make do.
2531 //Use a hash to force the length to the same as the other methods
2532 $bytes = hash('sha256', uniqid((string) mt_rand(), true), true);
2535 //We don't care about messing up base64 format here, just want a random string
2536 return str_replace(['=', '+', '/'], '', base64_encode(hash('sha256', $bytes, true)));
2540 * Assemble the message body.
2541 * Returns an empty string on failure.
2543 * @throws Exception
2545 * @return string The assembled message body
2547 public function createBody()
2549 $body = '';
2550 //Create unique IDs and preset boundaries
2551 $this->uniqueid = $this->generateId();
2552 $this->boundary[1] = 'b1_' . $this->uniqueid;
2553 $this->boundary[2] = 'b2_' . $this->uniqueid;
2554 $this->boundary[3] = 'b3_' . $this->uniqueid;
2556 if ($this->sign_key_file) {
2557 $body .= $this->getMailMIME() . static::$LE;
2560 $this->setWordWrap();
2562 $bodyEncoding = $this->Encoding;
2563 $bodyCharSet = $this->CharSet;
2564 //Can we do a 7-bit downgrade?
2565 if (static::ENCODING_8BIT === $bodyEncoding && !$this->has8bitChars($this->Body)) {
2566 $bodyEncoding = static::ENCODING_7BIT;
2567 //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit
2568 $bodyCharSet = static::CHARSET_ASCII;
2570 //If lines are too long, and we're not already using an encoding that will shorten them,
2571 //change to quoted-printable transfer encoding for the body part only
2572 if (static::ENCODING_BASE64 !== $this->Encoding && static::hasLineLongerThanMax($this->Body)) {
2573 $bodyEncoding = static::ENCODING_QUOTED_PRINTABLE;
2576 $altBodyEncoding = $this->Encoding;
2577 $altBodyCharSet = $this->CharSet;
2578 //Can we do a 7-bit downgrade?
2579 if (static::ENCODING_8BIT === $altBodyEncoding && !$this->has8bitChars($this->AltBody)) {
2580 $altBodyEncoding = static::ENCODING_7BIT;
2581 //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit
2582 $altBodyCharSet = static::CHARSET_ASCII;
2584 //If lines are too long, and we're not already using an encoding that will shorten them,
2585 //change to quoted-printable transfer encoding for the alt body part only
2586 if (static::ENCODING_BASE64 !== $altBodyEncoding && static::hasLineLongerThanMax($this->AltBody)) {
2587 $altBodyEncoding = static::ENCODING_QUOTED_PRINTABLE;
2589 //Use this as a preamble in all multipart message types
2590 $mimepre = 'This is a multi-part message in MIME format.' . static::$LE;
2591 switch ($this->message_type) {
2592 case 'inline':
2593 $body .= $mimepre;
2594 $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
2595 $body .= $this->encodeString($this->Body, $bodyEncoding);
2596 $body .= static::$LE;
2597 $body .= $this->attachAll('inline', $this->boundary[1]);
2598 break;
2599 case 'attach':
2600 $body .= $mimepre;
2601 $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
2602 $body .= $this->encodeString($this->Body, $bodyEncoding);
2603 $body .= static::$LE;
2604 $body .= $this->attachAll('attachment', $this->boundary[1]);
2605 break;
2606 case 'inline_attach':
2607 $body .= $mimepre;
2608 $body .= $this->textLine('--' . $this->boundary[1]);
2609 $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';');
2610 $body .= $this->textLine(' boundary="' . $this->boundary[2] . '";');
2611 $body .= $this->textLine(' type="' . static::CONTENT_TYPE_TEXT_HTML . '"');
2612 $body .= static::$LE;
2613 $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, '', $bodyEncoding);
2614 $body .= $this->encodeString($this->Body, $bodyEncoding);
2615 $body .= static::$LE;
2616 $body .= $this->attachAll('inline', $this->boundary[2]);
2617 $body .= static::$LE;
2618 $body .= $this->attachAll('attachment', $this->boundary[1]);
2619 break;
2620 case 'alt':
2621 $body .= $mimepre;
2622 $body .= $this->getBoundary(
2623 $this->boundary[1],
2624 $altBodyCharSet,
2625 static::CONTENT_TYPE_PLAINTEXT,
2626 $altBodyEncoding
2628 $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
2629 $body .= static::$LE;
2630 $body .= $this->getBoundary(
2631 $this->boundary[1],
2632 $bodyCharSet,
2633 static::CONTENT_TYPE_TEXT_HTML,
2634 $bodyEncoding
2636 $body .= $this->encodeString($this->Body, $bodyEncoding);
2637 $body .= static::$LE;
2638 if (!empty($this->Ical)) {
2639 $method = static::ICAL_METHOD_REQUEST;
2640 foreach (static::$IcalMethods as $imethod) {
2641 if (stripos($this->Ical, 'METHOD:' . $imethod) !== false) {
2642 $method = $imethod;
2643 break;
2646 $body .= $this->getBoundary(
2647 $this->boundary[1],
2649 static::CONTENT_TYPE_TEXT_CALENDAR . '; method=' . $method,
2652 $body .= $this->encodeString($this->Ical, $this->Encoding);
2653 $body .= static::$LE;
2655 $body .= $this->endBoundary($this->boundary[1]);
2656 break;
2657 case 'alt_inline':
2658 $body .= $mimepre;
2659 $body .= $this->getBoundary(
2660 $this->boundary[1],
2661 $altBodyCharSet,
2662 static::CONTENT_TYPE_PLAINTEXT,
2663 $altBodyEncoding
2665 $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
2666 $body .= static::$LE;
2667 $body .= $this->textLine('--' . $this->boundary[1]);
2668 $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';');
2669 $body .= $this->textLine(' boundary="' . $this->boundary[2] . '";');
2670 $body .= $this->textLine(' type="' . static::CONTENT_TYPE_TEXT_HTML . '"');
2671 $body .= static::$LE;
2672 $body .= $this->getBoundary(
2673 $this->boundary[2],
2674 $bodyCharSet,
2675 static::CONTENT_TYPE_TEXT_HTML,
2676 $bodyEncoding
2678 $body .= $this->encodeString($this->Body, $bodyEncoding);
2679 $body .= static::$LE;
2680 $body .= $this->attachAll('inline', $this->boundary[2]);
2681 $body .= static::$LE;
2682 $body .= $this->endBoundary($this->boundary[1]);
2683 break;
2684 case 'alt_attach':
2685 $body .= $mimepre;
2686 $body .= $this->textLine('--' . $this->boundary[1]);
2687 $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_ALTERNATIVE . ';');
2688 $body .= $this->textLine(' boundary="' . $this->boundary[2] . '"');
2689 $body .= static::$LE;
2690 $body .= $this->getBoundary(
2691 $this->boundary[2],
2692 $altBodyCharSet,
2693 static::CONTENT_TYPE_PLAINTEXT,
2694 $altBodyEncoding
2696 $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
2697 $body .= static::$LE;
2698 $body .= $this->getBoundary(
2699 $this->boundary[2],
2700 $bodyCharSet,
2701 static::CONTENT_TYPE_TEXT_HTML,
2702 $bodyEncoding
2704 $body .= $this->encodeString($this->Body, $bodyEncoding);
2705 $body .= static::$LE;
2706 if (!empty($this->Ical)) {
2707 $method = static::ICAL_METHOD_REQUEST;
2708 foreach (static::$IcalMethods as $imethod) {
2709 if (stripos($this->Ical, 'METHOD:' . $imethod) !== false) {
2710 $method = $imethod;
2711 break;
2714 $body .= $this->getBoundary(
2715 $this->boundary[2],
2717 static::CONTENT_TYPE_TEXT_CALENDAR . '; method=' . $method,
2720 $body .= $this->encodeString($this->Ical, $this->Encoding);
2722 $body .= $this->endBoundary($this->boundary[2]);
2723 $body .= static::$LE;
2724 $body .= $this->attachAll('attachment', $this->boundary[1]);
2725 break;
2726 case 'alt_inline_attach':
2727 $body .= $mimepre;
2728 $body .= $this->textLine('--' . $this->boundary[1]);
2729 $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_ALTERNATIVE . ';');
2730 $body .= $this->textLine(' boundary="' . $this->boundary[2] . '"');
2731 $body .= static::$LE;
2732 $body .= $this->getBoundary(
2733 $this->boundary[2],
2734 $altBodyCharSet,
2735 static::CONTENT_TYPE_PLAINTEXT,
2736 $altBodyEncoding
2738 $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
2739 $body .= static::$LE;
2740 $body .= $this->textLine('--' . $this->boundary[2]);
2741 $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';');
2742 $body .= $this->textLine(' boundary="' . $this->boundary[3] . '";');
2743 $body .= $this->textLine(' type="' . static::CONTENT_TYPE_TEXT_HTML . '"');
2744 $body .= static::$LE;
2745 $body .= $this->getBoundary(
2746 $this->boundary[3],
2747 $bodyCharSet,
2748 static::CONTENT_TYPE_TEXT_HTML,
2749 $bodyEncoding
2751 $body .= $this->encodeString($this->Body, $bodyEncoding);
2752 $body .= static::$LE;
2753 $body .= $this->attachAll('inline', $this->boundary[3]);
2754 $body .= static::$LE;
2755 $body .= $this->endBoundary($this->boundary[2]);
2756 $body .= static::$LE;
2757 $body .= $this->attachAll('attachment', $this->boundary[1]);
2758 break;
2759 default:
2760 // Catch case 'plain' and case '', applies to simple `text/plain` and `text/html` body content types
2761 //Reset the `Encoding` property in case we changed it for line length reasons
2762 $this->Encoding = $bodyEncoding;
2763 $body .= $this->encodeString($this->Body, $this->Encoding);
2764 break;
2767 if ($this->isError()) {
2768 $body = '';
2769 if ($this->exceptions) {
2770 throw new Exception($this->lang('empty_message'), self::STOP_CRITICAL);
2772 } elseif ($this->sign_key_file) {
2773 try {
2774 if (!defined('PKCS7_TEXT')) {
2775 throw new Exception($this->lang('extension_missing') . 'openssl');
2778 $file = tempnam(sys_get_temp_dir(), 'srcsign');
2779 $signed = tempnam(sys_get_temp_dir(), 'mailsign');
2780 file_put_contents($file, $body);
2782 //Workaround for PHP bug https://bugs.php.net/bug.php?id=69197
2783 if (empty($this->sign_extracerts_file)) {
2784 $sign = @openssl_pkcs7_sign(
2785 $file,
2786 $signed,
2787 'file://' . realpath($this->sign_cert_file),
2788 ['file://' . realpath($this->sign_key_file), $this->sign_key_pass],
2791 } else {
2792 $sign = @openssl_pkcs7_sign(
2793 $file,
2794 $signed,
2795 'file://' . realpath($this->sign_cert_file),
2796 ['file://' . realpath($this->sign_key_file), $this->sign_key_pass],
2798 PKCS7_DETACHED,
2799 $this->sign_extracerts_file
2803 @unlink($file);
2804 if ($sign) {
2805 $body = file_get_contents($signed);
2806 @unlink($signed);
2807 //The message returned by openssl contains both headers and body, so need to split them up
2808 $parts = explode("\n\n", $body, 2);
2809 $this->MIMEHeader .= $parts[0] . static::$LE . static::$LE;
2810 $body = $parts[1];
2811 } else {
2812 @unlink($signed);
2813 throw new Exception($this->lang('signing') . openssl_error_string());
2815 } catch (Exception $exc) {
2816 $body = '';
2817 if ($this->exceptions) {
2818 throw $exc;
2823 return $body;
2827 * Return the start of a message boundary.
2829 * @param string $boundary
2830 * @param string $charSet
2831 * @param string $contentType
2832 * @param string $encoding
2834 * @return string
2836 protected function getBoundary($boundary, $charSet, $contentType, $encoding)
2838 $result = '';
2839 if ('' === $charSet) {
2840 $charSet = $this->CharSet;
2842 if ('' === $contentType) {
2843 $contentType = $this->ContentType;
2845 if ('' === $encoding) {
2846 $encoding = $this->Encoding;
2848 $result .= $this->textLine('--' . $boundary);
2849 $result .= sprintf('Content-Type: %s; charset=%s', $contentType, $charSet);
2850 $result .= static::$LE;
2851 // RFC1341 part 5 says 7bit is assumed if not specified
2852 if (static::ENCODING_7BIT !== $encoding) {
2853 $result .= $this->headerLine('Content-Transfer-Encoding', $encoding);
2855 $result .= static::$LE;
2857 return $result;
2861 * Return the end of a message boundary.
2863 * @param string $boundary
2865 * @return string
2867 protected function endBoundary($boundary)
2869 return static::$LE . '--' . $boundary . '--' . static::$LE;
2873 * Set the message type.
2874 * PHPMailer only supports some preset message types, not arbitrary MIME structures.
2876 protected function setMessageType()
2878 $type = [];
2879 if ($this->alternativeExists()) {
2880 $type[] = 'alt';
2882 if ($this->inlineImageExists()) {
2883 $type[] = 'inline';
2885 if ($this->attachmentExists()) {
2886 $type[] = 'attach';
2888 $this->message_type = implode('_', $type);
2889 if ('' === $this->message_type) {
2890 //The 'plain' message_type refers to the message having a single body element, not that it is plain-text
2891 $this->message_type = 'plain';
2896 * Format a header line.
2898 * @param string $name
2899 * @param string|int $value
2901 * @return string
2903 public function headerLine($name, $value)
2905 return $name . ': ' . $value . static::$LE;
2909 * Return a formatted mail line.
2911 * @param string $value
2913 * @return string
2915 public function textLine($value)
2917 return $value . static::$LE;
2921 * Add an attachment from a path on the filesystem.
2922 * Never use a user-supplied path to a file!
2923 * Returns false if the file could not be found or read.
2924 * Explicitly *does not* support passing URLs; PHPMailer is not an HTTP client.
2925 * If you need to do that, fetch the resource yourself and pass it in via a local file or string.
2927 * @param string $path Path to the attachment
2928 * @param string $name Overrides the attachment name
2929 * @param string $encoding File encoding (see $Encoding)
2930 * @param string $type File extension (MIME) type
2931 * @param string $disposition Disposition to use
2933 * @throws Exception
2935 * @return bool
2937 public function addAttachment(
2938 $path,
2939 $name = '',
2940 $encoding = self::ENCODING_BASE64,
2941 $type = '',
2942 $disposition = 'attachment'
2944 try {
2945 if (!static::isPermittedPath($path) || !@is_file($path)) {
2946 throw new Exception($this->lang('file_access') . $path, self::STOP_CONTINUE);
2949 // If a MIME type is not specified, try to work it out from the file name
2950 if ('' === $type) {
2951 $type = static::filenameToType($path);
2954 $filename = (string) static::mb_pathinfo($path, PATHINFO_BASENAME);
2955 if ('' === $name) {
2956 $name = $filename;
2959 if (!$this->validateEncoding($encoding)) {
2960 throw new Exception($this->lang('encoding') . $encoding);
2963 $this->attachment[] = [
2964 0 => $path,
2965 1 => $filename,
2966 2 => $name,
2967 3 => $encoding,
2968 4 => $type,
2969 5 => false, // isStringAttachment
2970 6 => $disposition,
2971 7 => $name,
2973 } catch (Exception $exc) {
2974 $this->setError($exc->getMessage());
2975 $this->edebug($exc->getMessage());
2976 if ($this->exceptions) {
2977 throw $exc;
2980 return false;
2983 return true;
2987 * Return the array of attachments.
2989 * @return array
2991 public function getAttachments()
2993 return $this->attachment;
2997 * Attach all file, string, and binary attachments to the message.
2998 * Returns an empty string on failure.
3000 * @param string $disposition_type
3001 * @param string $boundary
3003 * @throws Exception
3005 * @return string
3007 protected function attachAll($disposition_type, $boundary)
3009 // Return text of body
3010 $mime = [];
3011 $cidUniq = [];
3012 $incl = [];
3014 // Add all attachments
3015 foreach ($this->attachment as $attachment) {
3016 // Check if it is a valid disposition_filter
3017 if ($attachment[6] === $disposition_type) {
3018 // Check for string attachment
3019 $string = '';
3020 $path = '';
3021 $bString = $attachment[5];
3022 if ($bString) {
3023 $string = $attachment[0];
3024 } else {
3025 $path = $attachment[0];
3028 $inclhash = hash('sha256', serialize($attachment));
3029 if (in_array($inclhash, $incl, true)) {
3030 continue;
3032 $incl[] = $inclhash;
3033 $name = $attachment[2];
3034 $encoding = $attachment[3];
3035 $type = $attachment[4];
3036 $disposition = $attachment[6];
3037 $cid = $attachment[7];
3038 if ('inline' === $disposition && array_key_exists($cid, $cidUniq)) {
3039 continue;
3041 $cidUniq[$cid] = true;
3043 $mime[] = sprintf('--%s%s', $boundary, static::$LE);
3044 //Only include a filename property if we have one
3045 if (!empty($name)) {
3046 $mime[] = sprintf(
3047 'Content-Type: %s; name="%s"%s',
3048 $type,
3049 $this->encodeHeader($this->secureHeader($name)),
3050 static::$LE
3052 } else {
3053 $mime[] = sprintf(
3054 'Content-Type: %s%s',
3055 $type,
3056 static::$LE
3059 // RFC1341 part 5 says 7bit is assumed if not specified
3060 if (static::ENCODING_7BIT !== $encoding) {
3061 $mime[] = sprintf('Content-Transfer-Encoding: %s%s', $encoding, static::$LE);
3064 //Only set Content-IDs on inline attachments
3065 if ((string) $cid !== '' && $disposition === 'inline') {
3066 $mime[] = 'Content-ID: <' . $this->encodeHeader($this->secureHeader($cid)) . '>' . static::$LE;
3069 // If a filename contains any of these chars, it should be quoted,
3070 // but not otherwise: RFC2183 & RFC2045 5.1
3071 // Fixes a warning in IETF's msglint MIME checker
3072 // Allow for bypassing the Content-Disposition header totally
3073 if (!empty($disposition)) {
3074 $encoded_name = $this->encodeHeader($this->secureHeader($name));
3075 if (preg_match('/[ ()<>@,;:"\/\[\]?=]/', $encoded_name)) {
3076 $mime[] = sprintf(
3077 'Content-Disposition: %s; filename="%s"%s',
3078 $disposition,
3079 $encoded_name,
3080 static::$LE . static::$LE
3082 } elseif (!empty($encoded_name)) {
3083 $mime[] = sprintf(
3084 'Content-Disposition: %s; filename=%s%s',
3085 $disposition,
3086 $encoded_name,
3087 static::$LE . static::$LE
3089 } else {
3090 $mime[] = sprintf(
3091 'Content-Disposition: %s%s',
3092 $disposition,
3093 static::$LE . static::$LE
3096 } else {
3097 $mime[] = static::$LE;
3100 // Encode as string attachment
3101 if ($bString) {
3102 $mime[] = $this->encodeString($string, $encoding);
3103 } else {
3104 $mime[] = $this->encodeFile($path, $encoding);
3106 if ($this->isError()) {
3107 return '';
3109 $mime[] = static::$LE;
3113 $mime[] = sprintf('--%s--%s', $boundary, static::$LE);
3115 return implode('', $mime);
3119 * Encode a file attachment in requested format.
3120 * Returns an empty string on failure.
3122 * @param string $path The full path to the file
3123 * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
3125 * @return string
3127 protected function encodeFile($path, $encoding = self::ENCODING_BASE64)
3129 try {
3130 if (!static::isPermittedPath($path) || !file_exists($path)) {
3131 throw new Exception($this->lang('file_open') . $path, self::STOP_CONTINUE);
3133 $file_buffer = file_get_contents($path);
3134 if (false === $file_buffer) {
3135 throw new Exception($this->lang('file_open') . $path, self::STOP_CONTINUE);
3137 $file_buffer = $this->encodeString($file_buffer, $encoding);
3139 return $file_buffer;
3140 } catch (Exception $exc) {
3141 $this->setError($exc->getMessage());
3143 return '';
3148 * Encode a string in requested format.
3149 * Returns an empty string on failure.
3151 * @param string $str The text to encode
3152 * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
3154 * @throws Exception
3156 * @return string
3158 public function encodeString($str, $encoding = self::ENCODING_BASE64)
3160 $encoded = '';
3161 switch (strtolower($encoding)) {
3162 case static::ENCODING_BASE64:
3163 $encoded = chunk_split(
3164 base64_encode($str),
3165 static::STD_LINE_LENGTH,
3166 static::$LE
3168 break;
3169 case static::ENCODING_7BIT:
3170 case static::ENCODING_8BIT:
3171 $encoded = static::normalizeBreaks($str);
3172 // Make sure it ends with a line break
3173 if (substr($encoded, -(strlen(static::$LE))) !== static::$LE) {
3174 $encoded .= static::$LE;
3176 break;
3177 case static::ENCODING_BINARY:
3178 $encoded = $str;
3179 break;
3180 case static::ENCODING_QUOTED_PRINTABLE:
3181 $encoded = $this->encodeQP($str);
3182 break;
3183 default:
3184 $this->setError($this->lang('encoding') . $encoding);
3185 if ($this->exceptions) {
3186 throw new Exception($this->lang('encoding') . $encoding);
3188 break;
3191 return $encoded;
3195 * Encode a header value (not including its label) optimally.
3196 * Picks shortest of Q, B, or none. Result includes folding if needed.
3197 * See RFC822 definitions for phrase, comment and text positions.
3199 * @param string $str The header value to encode
3200 * @param string $position What context the string will be used in
3202 * @return string
3204 public function encodeHeader($str, $position = 'text')
3206 $matchcount = 0;
3207 switch (strtolower($position)) {
3208 case 'phrase':
3209 if (!preg_match('/[\200-\377]/', $str)) {
3210 // Can't use addslashes as we don't know the value of magic_quotes_sybase
3211 $encoded = addcslashes($str, "\0..\37\177\\\"");
3212 if (($str === $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
3213 return $encoded;
3216 return "\"$encoded\"";
3218 $matchcount = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
3219 break;
3220 /* @noinspection PhpMissingBreakStatementInspection */
3221 case 'comment':
3222 $matchcount = preg_match_all('/[()"]/', $str, $matches);
3223 //fallthrough
3224 case 'text':
3225 default:
3226 $matchcount += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
3227 break;
3230 if ($this->has8bitChars($str)) {
3231 $charset = $this->CharSet;
3232 } else {
3233 $charset = static::CHARSET_ASCII;
3236 // Q/B encoding adds 8 chars and the charset ("` =?<charset>?[QB]?<content>?=`").
3237 $overhead = 8 + strlen($charset);
3239 if ('mail' === $this->Mailer) {
3240 $maxlen = static::MAIL_MAX_LINE_LENGTH - $overhead;
3241 } else {
3242 $maxlen = static::STD_LINE_LENGTH - $overhead;
3245 // Select the encoding that produces the shortest output and/or prevents corruption.
3246 if ($matchcount > strlen($str) / 3) {
3247 // More than 1/3 of the content needs encoding, use B-encode.
3248 $encoding = 'B';
3249 } elseif ($matchcount > 0) {
3250 // Less than 1/3 of the content needs encoding, use Q-encode.
3251 $encoding = 'Q';
3252 } elseif (strlen($str) > $maxlen) {
3253 // No encoding needed, but value exceeds max line length, use Q-encode to prevent corruption.
3254 $encoding = 'Q';
3255 } else {
3256 // No reformatting needed
3257 $encoding = false;
3260 switch ($encoding) {
3261 case 'B':
3262 if ($this->hasMultiBytes($str)) {
3263 // Use a custom function which correctly encodes and wraps long
3264 // multibyte strings without breaking lines within a character
3265 $encoded = $this->base64EncodeWrapMB($str, "\n");
3266 } else {
3267 $encoded = base64_encode($str);
3268 $maxlen -= $maxlen % 4;
3269 $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
3271 $encoded = preg_replace('/^(.*)$/m', ' =?' . $charset . "?$encoding?\\1?=", $encoded);
3272 break;
3273 case 'Q':
3274 $encoded = $this->encodeQ($str, $position);
3275 $encoded = $this->wrapText($encoded, $maxlen, true);
3276 $encoded = str_replace('=' . static::$LE, "\n", trim($encoded));
3277 $encoded = preg_replace('/^(.*)$/m', ' =?' . $charset . "?$encoding?\\1?=", $encoded);
3278 break;
3279 default:
3280 return $str;
3283 return trim(static::normalizeBreaks($encoded));
3287 * Check if a string contains multi-byte characters.
3289 * @param string $str multi-byte text to wrap encode
3291 * @return bool
3293 public function hasMultiBytes($str)
3295 if (function_exists('mb_strlen')) {
3296 return strlen($str) > mb_strlen($str, $this->CharSet);
3299 // Assume no multibytes (we can't handle without mbstring functions anyway)
3300 return false;
3304 * Does a string contain any 8-bit chars (in any charset)?
3306 * @param string $text
3308 * @return bool
3310 public function has8bitChars($text)
3312 return (bool) preg_match('/[\x80-\xFF]/', $text);
3316 * Encode and wrap long multibyte strings for mail headers
3317 * without breaking lines within a character.
3318 * Adapted from a function by paravoid.
3320 * @see http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283
3322 * @param string $str multi-byte text to wrap encode
3323 * @param string $linebreak string to use as linefeed/end-of-line
3325 * @return string
3327 public function base64EncodeWrapMB($str, $linebreak = null)
3329 $start = '=?' . $this->CharSet . '?B?';
3330 $end = '?=';
3331 $encoded = '';
3332 if (null === $linebreak) {
3333 $linebreak = static::$LE;
3336 $mb_length = mb_strlen($str, $this->CharSet);
3337 // Each line must have length <= 75, including $start and $end
3338 $length = 75 - strlen($start) - strlen($end);
3339 // Average multi-byte ratio
3340 $ratio = $mb_length / strlen($str);
3341 // Base64 has a 4:3 ratio
3342 $avgLength = floor($length * $ratio * .75);
3344 $offset = 0;
3345 for ($i = 0; $i < $mb_length; $i += $offset) {
3346 $lookBack = 0;
3347 do {
3348 $offset = $avgLength - $lookBack;
3349 $chunk = mb_substr($str, $i, $offset, $this->CharSet);
3350 $chunk = base64_encode($chunk);
3351 ++$lookBack;
3352 } while (strlen($chunk) > $length);
3353 $encoded .= $chunk . $linebreak;
3356 // Chomp the last linefeed
3357 return substr($encoded, 0, -strlen($linebreak));
3361 * Encode a string in quoted-printable format.
3362 * According to RFC2045 section 6.7.
3364 * @param string $string The text to encode
3366 * @return string
3368 public function encodeQP($string)
3370 return static::normalizeBreaks(quoted_printable_encode($string));
3374 * Encode a string using Q encoding.
3376 * @see http://tools.ietf.org/html/rfc2047#section-4.2
3378 * @param string $str the text to encode
3379 * @param string $position Where the text is going to be used, see the RFC for what that means
3381 * @return string
3383 public function encodeQ($str, $position = 'text')
3385 // There should not be any EOL in the string
3386 $pattern = '';
3387 $encoded = str_replace(["\r", "\n"], '', $str);
3388 switch (strtolower($position)) {
3389 case 'phrase':
3390 // RFC 2047 section 5.3
3391 $pattern = '^A-Za-z0-9!*+\/ -';
3392 break;
3394 * RFC 2047 section 5.2.
3395 * Build $pattern without including delimiters and []
3397 /* @noinspection PhpMissingBreakStatementInspection */
3398 case 'comment':
3399 $pattern = '\(\)"';
3400 /* Intentional fall through */
3401 case 'text':
3402 default:
3403 // RFC 2047 section 5.1
3404 // Replace every high ascii, control, =, ? and _ characters
3405 $pattern = '\000-\011\013\014\016-\037\075\077\137\177-\377' . $pattern;
3406 break;
3408 $matches = [];
3409 if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) {
3410 // If the string contains an '=', make sure it's the first thing we replace
3411 // so as to avoid double-encoding
3412 $eqkey = array_search('=', $matches[0], true);
3413 if (false !== $eqkey) {
3414 unset($matches[0][$eqkey]);
3415 array_unshift($matches[0], '=');
3417 foreach (array_unique($matches[0]) as $char) {
3418 $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded);
3421 // Replace spaces with _ (more readable than =20)
3422 // RFC 2047 section 4.2(2)
3423 return str_replace(' ', '_', $encoded);
3427 * Add a string or binary attachment (non-filesystem).
3428 * This method can be used to attach ascii or binary data,
3429 * such as a BLOB record from a database.
3431 * @param string $string String attachment data
3432 * @param string $filename Name of the attachment
3433 * @param string $encoding File encoding (see $Encoding)
3434 * @param string $type File extension (MIME) type
3435 * @param string $disposition Disposition to use
3437 * @throws Exception
3439 * @return bool True on successfully adding an attachment
3441 public function addStringAttachment(
3442 $string,
3443 $filename,
3444 $encoding = self::ENCODING_BASE64,
3445 $type = '',
3446 $disposition = 'attachment'
3448 try {
3449 // If a MIME type is not specified, try to work it out from the file name
3450 if ('' === $type) {
3451 $type = static::filenameToType($filename);
3454 if (!$this->validateEncoding($encoding)) {
3455 throw new Exception($this->lang('encoding') . $encoding);
3458 // Append to $attachment array
3459 $this->attachment[] = [
3460 0 => $string,
3461 1 => $filename,
3462 2 => static::mb_pathinfo($filename, PATHINFO_BASENAME),
3463 3 => $encoding,
3464 4 => $type,
3465 5 => true, // isStringAttachment
3466 6 => $disposition,
3467 7 => 0,
3469 } catch (Exception $exc) {
3470 $this->setError($exc->getMessage());
3471 $this->edebug($exc->getMessage());
3472 if ($this->exceptions) {
3473 throw $exc;
3476 return false;
3479 return true;
3483 * Add an embedded (inline) attachment from a file.
3484 * This can include images, sounds, and just about any other document type.
3485 * These differ from 'regular' attachments in that they are intended to be
3486 * displayed inline with the message, not just attached for download.
3487 * This is used in HTML messages that embed the images
3488 * the HTML refers to using the $cid value.
3489 * Never use a user-supplied path to a file!
3491 * @param string $path Path to the attachment
3492 * @param string $cid Content ID of the attachment; Use this to reference
3493 * the content when using an embedded image in HTML
3494 * @param string $name Overrides the attachment name
3495 * @param string $encoding File encoding (see $Encoding)
3496 * @param string $type File MIME type
3497 * @param string $disposition Disposition to use
3499 * @throws Exception
3501 * @return bool True on successfully adding an attachment
3503 public function addEmbeddedImage(
3504 $path,
3505 $cid,
3506 $name = '',
3507 $encoding = self::ENCODING_BASE64,
3508 $type = '',
3509 $disposition = 'inline'
3511 try {
3512 if (!static::isPermittedPath($path) || !@is_file($path)) {
3513 throw new Exception($this->lang('file_access') . $path, self::STOP_CONTINUE);
3516 // If a MIME type is not specified, try to work it out from the file name
3517 if ('' === $type) {
3518 $type = static::filenameToType($path);
3521 if (!$this->validateEncoding($encoding)) {
3522 throw new Exception($this->lang('encoding') . $encoding);
3525 $filename = (string) static::mb_pathinfo($path, PATHINFO_BASENAME);
3526 if ('' === $name) {
3527 $name = $filename;
3530 // Append to $attachment array
3531 $this->attachment[] = [
3532 0 => $path,
3533 1 => $filename,
3534 2 => $name,
3535 3 => $encoding,
3536 4 => $type,
3537 5 => false, // isStringAttachment
3538 6 => $disposition,
3539 7 => $cid,
3541 } catch (Exception $exc) {
3542 $this->setError($exc->getMessage());
3543 $this->edebug($exc->getMessage());
3544 if ($this->exceptions) {
3545 throw $exc;
3548 return false;
3551 return true;
3555 * Add an embedded stringified attachment.
3556 * This can include images, sounds, and just about any other document type.
3557 * If your filename doesn't contain an extension, be sure to set the $type to an appropriate MIME type.
3559 * @param string $string The attachment binary data
3560 * @param string $cid Content ID of the attachment; Use this to reference
3561 * the content when using an embedded image in HTML
3562 * @param string $name A filename for the attachment. If this contains an extension,
3563 * PHPMailer will attempt to set a MIME type for the attachment.
3564 * For example 'file.jpg' would get an 'image/jpeg' MIME type.
3565 * @param string $encoding File encoding (see $Encoding), defaults to 'base64'
3566 * @param string $type MIME type - will be used in preference to any automatically derived type
3567 * @param string $disposition Disposition to use
3569 * @throws Exception
3571 * @return bool True on successfully adding an attachment
3573 public function addStringEmbeddedImage(
3574 $string,
3575 $cid,
3576 $name = '',
3577 $encoding = self::ENCODING_BASE64,
3578 $type = '',
3579 $disposition = 'inline'
3581 try {
3582 // If a MIME type is not specified, try to work it out from the name
3583 if ('' === $type && !empty($name)) {
3584 $type = static::filenameToType($name);
3587 if (!$this->validateEncoding($encoding)) {
3588 throw new Exception($this->lang('encoding') . $encoding);
3591 // Append to $attachment array
3592 $this->attachment[] = [
3593 0 => $string,
3594 1 => $name,
3595 2 => $name,
3596 3 => $encoding,
3597 4 => $type,
3598 5 => true, // isStringAttachment
3599 6 => $disposition,
3600 7 => $cid,
3602 } catch (Exception $exc) {
3603 $this->setError($exc->getMessage());
3604 $this->edebug($exc->getMessage());
3605 if ($this->exceptions) {
3606 throw $exc;
3609 return false;
3612 return true;
3616 * Validate encodings.
3618 * @param string $encoding
3620 * @return bool
3622 protected function validateEncoding($encoding)
3624 return in_array(
3625 $encoding,
3627 self::ENCODING_7BIT,
3628 self::ENCODING_QUOTED_PRINTABLE,
3629 self::ENCODING_BASE64,
3630 self::ENCODING_8BIT,
3631 self::ENCODING_BINARY,
3633 true
3638 * Check if an embedded attachment is present with this cid.
3640 * @param string $cid
3642 * @return bool
3644 protected function cidExists($cid)
3646 foreach ($this->attachment as $attachment) {
3647 if ('inline' === $attachment[6] && $cid === $attachment[7]) {
3648 return true;
3652 return false;
3656 * Check if an inline attachment is present.
3658 * @return bool
3660 public function inlineImageExists()
3662 foreach ($this->attachment as $attachment) {
3663 if ('inline' === $attachment[6]) {
3664 return true;
3668 return false;
3672 * Check if an attachment (non-inline) is present.
3674 * @return bool
3676 public function attachmentExists()
3678 foreach ($this->attachment as $attachment) {
3679 if ('attachment' === $attachment[6]) {
3680 return true;
3684 return false;
3688 * Check if this message has an alternative body set.
3690 * @return bool
3692 public function alternativeExists()
3694 return !empty($this->AltBody);
3698 * Clear queued addresses of given kind.
3700 * @param string $kind 'to', 'cc', or 'bcc'
3702 public function clearQueuedAddresses($kind)
3704 $this->RecipientsQueue = array_filter(
3705 $this->RecipientsQueue,
3706 static function ($params) use ($kind) {
3707 return $params[0] !== $kind;
3713 * Clear all To recipients.
3715 public function clearAddresses()
3717 foreach ($this->to as $to) {
3718 unset($this->all_recipients[strtolower($to[0])]);
3720 $this->to = [];
3721 $this->clearQueuedAddresses('to');
3725 * Clear all CC recipients.
3727 public function clearCCs()
3729 foreach ($this->cc as $cc) {
3730 unset($this->all_recipients[strtolower($cc[0])]);
3732 $this->cc = [];
3733 $this->clearQueuedAddresses('cc');
3737 * Clear all BCC recipients.
3739 public function clearBCCs()
3741 foreach ($this->bcc as $bcc) {
3742 unset($this->all_recipients[strtolower($bcc[0])]);
3744 $this->bcc = [];
3745 $this->clearQueuedAddresses('bcc');
3749 * Clear all ReplyTo recipients.
3751 public function clearReplyTos()
3753 $this->ReplyTo = [];
3754 $this->ReplyToQueue = [];
3758 * Clear all recipient types.
3760 public function clearAllRecipients()
3762 $this->to = [];
3763 $this->cc = [];
3764 $this->bcc = [];
3765 $this->all_recipients = [];
3766 $this->RecipientsQueue = [];
3770 * Clear all filesystem, string, and binary attachments.
3772 public function clearAttachments()
3774 $this->attachment = [];
3778 * Clear all custom headers.
3780 public function clearCustomHeaders()
3782 $this->CustomHeader = [];
3786 * Add an error message to the error container.
3788 * @param string $msg
3790 protected function setError($msg)
3792 ++$this->error_count;
3793 if ('smtp' === $this->Mailer && null !== $this->smtp) {
3794 $lasterror = $this->smtp->getError();
3795 if (!empty($lasterror['error'])) {
3796 $msg .= $this->lang('smtp_error') . $lasterror['error'];
3797 if (!empty($lasterror['detail'])) {
3798 $msg .= ' Detail: ' . $lasterror['detail'];
3800 if (!empty($lasterror['smtp_code'])) {
3801 $msg .= ' SMTP code: ' . $lasterror['smtp_code'];
3803 if (!empty($lasterror['smtp_code_ex'])) {
3804 $msg .= ' Additional SMTP info: ' . $lasterror['smtp_code_ex'];
3808 $this->ErrorInfo = $msg;
3812 * Return an RFC 822 formatted date.
3814 * @return string
3816 public static function rfcDate()
3818 // Set the time zone to whatever the default is to avoid 500 errors
3819 // Will default to UTC if it's not set properly in php.ini
3820 date_default_timezone_set(@date_default_timezone_get());
3822 return date('D, j M Y H:i:s O');
3826 * Get the server hostname.
3827 * Returns 'localhost.localdomain' if unknown.
3829 * @return string
3831 protected function serverHostname()
3833 $result = '';
3834 if (!empty($this->Hostname)) {
3835 $result = $this->Hostname;
3836 } elseif (isset($_SERVER) && array_key_exists('SERVER_NAME', $_SERVER)) {
3837 $result = $_SERVER['SERVER_NAME'];
3838 } elseif (function_exists('gethostname') && gethostname() !== false) {
3839 $result = gethostname();
3840 } elseif (php_uname('n') !== false) {
3841 $result = php_uname('n');
3843 if (!static::isValidHost($result)) {
3844 return 'localhost.localdomain';
3847 return $result;
3851 * Validate whether a string contains a valid value to use as a hostname or IP address.
3852 * IPv6 addresses must include [], e.g. `[::1]`, not just `::1`.
3854 * @param string $host The host name or IP address to check
3856 * @return bool
3858 public static function isValidHost($host)
3860 //Simple syntax limits
3861 if (empty($host)
3862 || !is_string($host)
3863 || strlen($host) > 256
3865 return false;
3867 //Looks like a bracketed IPv6 address
3868 if (trim($host, '[]') !== $host) {
3869 return (bool) filter_var(trim($host, '[]'), FILTER_VALIDATE_IP, FILTER_FLAG_IPV6);
3871 //If removing all the dots results in a numeric string, it must be an IPv4 address.
3872 //Need to check this first because otherwise things like `999.0.0.0` are considered valid host names
3873 if (is_numeric(str_replace('.', '', $host))) {
3874 //Is it a valid IPv4 address?
3875 return (bool) filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
3877 if (filter_var('http://' . $host, FILTER_VALIDATE_URL)) {
3878 //Is it a syntactically valid hostname?
3879 return true;
3882 return false;
3886 * Get an error message in the current language.
3888 * @param string $key
3890 * @return string
3892 protected function lang($key)
3894 if (count($this->language) < 1) {
3895 $this->setLanguage(); // set the default language
3898 if (array_key_exists($key, $this->language)) {
3899 if ('smtp_connect_failed' === $key) {
3900 //Include a link to troubleshooting docs on SMTP connection failure
3901 //this is by far the biggest cause of support questions
3902 //but it's usually not PHPMailer's fault.
3903 return $this->language[$key] . ' https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting';
3906 return $this->language[$key];
3909 //Return the key as a fallback
3910 return $key;
3914 * Check if an error occurred.
3916 * @return bool True if an error did occur
3918 public function isError()
3920 return $this->error_count > 0;
3924 * Add a custom header.
3925 * $name value can be overloaded to contain
3926 * both header name and value (name:value).
3928 * @param string $name Custom header name
3929 * @param string|null $value Header value
3931 public function addCustomHeader($name, $value = null)
3933 if (null === $value) {
3934 // Value passed in as name:value
3935 $this->CustomHeader[] = explode(':', $name, 2);
3936 } else {
3937 $this->CustomHeader[] = [$name, $value];
3942 * Returns all custom headers.
3944 * @return array
3946 public function getCustomHeaders()
3948 return $this->CustomHeader;
3952 * Create a message body from an HTML string.
3953 * Automatically inlines images and creates a plain-text version by converting the HTML,
3954 * overwriting any existing values in Body and AltBody.
3955 * Do not source $message content from user input!
3956 * $basedir is prepended when handling relative URLs, e.g. <img src="/images/a.png"> and must not be empty
3957 * will look for an image file in $basedir/images/a.png and convert it to inline.
3958 * If you don't provide a $basedir, relative paths will be left untouched (and thus probably break in email)
3959 * Converts data-uri images into embedded attachments.
3960 * If you don't want to apply these transformations to your HTML, just set Body and AltBody directly.
3962 * @param string $message HTML message string
3963 * @param string $basedir Absolute path to a base directory to prepend to relative paths to images
3964 * @param bool|callable $advanced Whether to use the internal HTML to text converter
3965 * or your own custom converter @return string $message The transformed message Body
3967 * @throws Exception
3969 * @see PHPMailer::html2text()
3971 public function msgHTML($message, $basedir = '', $advanced = false)
3973 preg_match_all('/(?<!-)(src|background)=["\'](.*)["\']/Ui', $message, $images);
3974 if (array_key_exists(2, $images)) {
3975 if (strlen($basedir) > 1 && '/' !== substr($basedir, -1)) {
3976 // Ensure $basedir has a trailing /
3977 $basedir .= '/';
3979 foreach ($images[2] as $imgindex => $url) {
3980 // Convert data URIs into embedded images
3981 //e.g. "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="
3982 if (preg_match('#^data:(image/(?:jpe?g|gif|png));?(base64)?,(.+)#', $url, $match)) {
3983 if (count($match) === 4 && static::ENCODING_BASE64 === $match[2]) {
3984 $data = base64_decode($match[3]);
3985 } elseif ('' === $match[2]) {
3986 $data = rawurldecode($match[3]);
3987 } else {
3988 //Not recognised so leave it alone
3989 continue;
3991 //Hash the decoded data, not the URL, so that the same data-URI image used in multiple places
3992 //will only be embedded once, even if it used a different encoding
3993 $cid = substr(hash('sha256', $data), 0, 32) . '@phpmailer.0'; // RFC2392 S 2
3995 if (!$this->cidExists($cid)) {
3996 $this->addStringEmbeddedImage(
3997 $data,
3998 $cid,
3999 'embed' . $imgindex,
4000 static::ENCODING_BASE64,
4001 $match[1]
4004 $message = str_replace(
4005 $images[0][$imgindex],
4006 $images[1][$imgindex] . '="cid:' . $cid . '"',
4007 $message
4009 continue;
4011 if (// Only process relative URLs if a basedir is provided (i.e. no absolute local paths)
4012 !empty($basedir)
4013 // Ignore URLs containing parent dir traversal (..)
4014 && (strpos($url, '..') === false)
4015 // Do not change urls that are already inline images
4016 && 0 !== strpos($url, 'cid:')
4017 // Do not change absolute URLs, including anonymous protocol
4018 && !preg_match('#^[a-z][a-z0-9+.-]*:?//#i', $url)
4020 $filename = static::mb_pathinfo($url, PATHINFO_BASENAME);
4021 $directory = dirname($url);
4022 if ('.' === $directory) {
4023 $directory = '';
4025 // RFC2392 S 2
4026 $cid = substr(hash('sha256', $url), 0, 32) . '@phpmailer.0';
4027 if (strlen($basedir) > 1 && '/' !== substr($basedir, -1)) {
4028 $basedir .= '/';
4030 if (strlen($directory) > 1 && '/' !== substr($directory, -1)) {
4031 $directory .= '/';
4033 if ($this->addEmbeddedImage(
4034 $basedir . $directory . $filename,
4035 $cid,
4036 $filename,
4037 static::ENCODING_BASE64,
4038 static::_mime_types((string) static::mb_pathinfo($filename, PATHINFO_EXTENSION))
4041 $message = preg_replace(
4042 '/' . $images[1][$imgindex] . '=["\']' . preg_quote($url, '/') . '["\']/Ui',
4043 $images[1][$imgindex] . '="cid:' . $cid . '"',
4044 $message
4050 $this->isHTML();
4051 // Convert all message body line breaks to LE, makes quoted-printable encoding work much better
4052 $this->Body = static::normalizeBreaks($message);
4053 $this->AltBody = static::normalizeBreaks($this->html2text($message, $advanced));
4054 if (!$this->alternativeExists()) {
4055 $this->AltBody = 'This is an HTML-only message. To view it, activate HTML in your email application.'
4056 . static::$LE;
4059 return $this->Body;
4063 * Convert an HTML string into plain text.
4064 * This is used by msgHTML().
4065 * Note - older versions of this function used a bundled advanced converter
4066 * which was removed for license reasons in #232.
4067 * Example usage:
4069 * ```php
4070 * // Use default conversion
4071 * $plain = $mail->html2text($html);
4072 * // Use your own custom converter
4073 * $plain = $mail->html2text($html, function($html) {
4074 * $converter = new MyHtml2text($html);
4075 * return $converter->get_text();
4076 * });
4077 * ```
4079 * @param string $html The HTML text to convert
4080 * @param bool|callable $advanced Any boolean value to use the internal converter,
4081 * or provide your own callable for custom conversion
4083 * @return string
4085 public function html2text($html, $advanced = false)
4087 if (is_callable($advanced)) {
4088 return $advanced($html);
4091 return html_entity_decode(
4092 trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/si', '', $html))),
4093 ENT_QUOTES,
4094 $this->CharSet
4099 * Get the MIME type for a file extension.
4101 * @param string $ext File extension
4103 * @return string MIME type of file
4105 public static function _mime_types($ext = '')
4107 $mimes = [
4108 'xl' => 'application/excel',
4109 'js' => 'application/javascript',
4110 'hqx' => 'application/mac-binhex40',
4111 'cpt' => 'application/mac-compactpro',
4112 'bin' => 'application/macbinary',
4113 'doc' => 'application/msword',
4114 'word' => 'application/msword',
4115 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
4116 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
4117 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
4118 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
4119 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
4120 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
4121 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
4122 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
4123 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
4124 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
4125 'class' => 'application/octet-stream',
4126 'dll' => 'application/octet-stream',
4127 'dms' => 'application/octet-stream',
4128 'exe' => 'application/octet-stream',
4129 'lha' => 'application/octet-stream',
4130 'lzh' => 'application/octet-stream',
4131 'psd' => 'application/octet-stream',
4132 'sea' => 'application/octet-stream',
4133 'so' => 'application/octet-stream',
4134 'oda' => 'application/oda',
4135 'pdf' => 'application/pdf',
4136 'ai' => 'application/postscript',
4137 'eps' => 'application/postscript',
4138 'ps' => 'application/postscript',
4139 'smi' => 'application/smil',
4140 'smil' => 'application/smil',
4141 'mif' => 'application/vnd.mif',
4142 'xls' => 'application/vnd.ms-excel',
4143 'ppt' => 'application/vnd.ms-powerpoint',
4144 'wbxml' => 'application/vnd.wap.wbxml',
4145 'wmlc' => 'application/vnd.wap.wmlc',
4146 'dcr' => 'application/x-director',
4147 'dir' => 'application/x-director',
4148 'dxr' => 'application/x-director',
4149 'dvi' => 'application/x-dvi',
4150 'gtar' => 'application/x-gtar',
4151 'php3' => 'application/x-httpd-php',
4152 'php4' => 'application/x-httpd-php',
4153 'php' => 'application/x-httpd-php',
4154 'phtml' => 'application/x-httpd-php',
4155 'phps' => 'application/x-httpd-php-source',
4156 'swf' => 'application/x-shockwave-flash',
4157 'sit' => 'application/x-stuffit',
4158 'tar' => 'application/x-tar',
4159 'tgz' => 'application/x-tar',
4160 'xht' => 'application/xhtml+xml',
4161 'xhtml' => 'application/xhtml+xml',
4162 'zip' => 'application/zip',
4163 'mid' => 'audio/midi',
4164 'midi' => 'audio/midi',
4165 'mp2' => 'audio/mpeg',
4166 'mp3' => 'audio/mpeg',
4167 'm4a' => 'audio/mp4',
4168 'mpga' => 'audio/mpeg',
4169 'aif' => 'audio/x-aiff',
4170 'aifc' => 'audio/x-aiff',
4171 'aiff' => 'audio/x-aiff',
4172 'ram' => 'audio/x-pn-realaudio',
4173 'rm' => 'audio/x-pn-realaudio',
4174 'rpm' => 'audio/x-pn-realaudio-plugin',
4175 'ra' => 'audio/x-realaudio',
4176 'wav' => 'audio/x-wav',
4177 'mka' => 'audio/x-matroska',
4178 'bmp' => 'image/bmp',
4179 'gif' => 'image/gif',
4180 'jpeg' => 'image/jpeg',
4181 'jpe' => 'image/jpeg',
4182 'jpg' => 'image/jpeg',
4183 'png' => 'image/png',
4184 'tiff' => 'image/tiff',
4185 'tif' => 'image/tiff',
4186 'webp' => 'image/webp',
4187 'heif' => 'image/heif',
4188 'heifs' => 'image/heif-sequence',
4189 'heic' => 'image/heic',
4190 'heics' => 'image/heic-sequence',
4191 'eml' => 'message/rfc822',
4192 'css' => 'text/css',
4193 'html' => 'text/html',
4194 'htm' => 'text/html',
4195 'shtml' => 'text/html',
4196 'log' => 'text/plain',
4197 'text' => 'text/plain',
4198 'txt' => 'text/plain',
4199 'rtx' => 'text/richtext',
4200 'rtf' => 'text/rtf',
4201 'vcf' => 'text/vcard',
4202 'vcard' => 'text/vcard',
4203 'ics' => 'text/calendar',
4204 'xml' => 'text/xml',
4205 'xsl' => 'text/xml',
4206 'wmv' => 'video/x-ms-wmv',
4207 'mpeg' => 'video/mpeg',
4208 'mpe' => 'video/mpeg',
4209 'mpg' => 'video/mpeg',
4210 'mp4' => 'video/mp4',
4211 'm4v' => 'video/mp4',
4212 'mov' => 'video/quicktime',
4213 'qt' => 'video/quicktime',
4214 'rv' => 'video/vnd.rn-realvideo',
4215 'avi' => 'video/x-msvideo',
4216 'movie' => 'video/x-sgi-movie',
4217 'webm' => 'video/webm',
4218 'mkv' => 'video/x-matroska',
4220 $ext = strtolower($ext);
4221 if (array_key_exists($ext, $mimes)) {
4222 return $mimes[$ext];
4225 return 'application/octet-stream';
4229 * Map a file name to a MIME type.
4230 * Defaults to 'application/octet-stream', i.e.. arbitrary binary data.
4232 * @param string $filename A file name or full path, does not need to exist as a file
4234 * @return string
4236 public static function filenameToType($filename)
4238 // In case the path is a URL, strip any query string before getting extension
4239 $qpos = strpos($filename, '?');
4240 if (false !== $qpos) {
4241 $filename = substr($filename, 0, $qpos);
4243 $ext = static::mb_pathinfo($filename, PATHINFO_EXTENSION);
4245 return static::_mime_types($ext);
4249 * Multi-byte-safe pathinfo replacement.
4250 * Drop-in replacement for pathinfo(), but multibyte- and cross-platform-safe.
4252 * @see http://www.php.net/manual/en/function.pathinfo.php#107461
4254 * @param string $path A filename or path, does not need to exist as a file
4255 * @param int|string $options Either a PATHINFO_* constant,
4256 * or a string name to return only the specified piece
4258 * @return string|array
4260 public static function mb_pathinfo($path, $options = null)
4262 $ret = ['dirname' => '', 'basename' => '', 'extension' => '', 'filename' => ''];
4263 $pathinfo = [];
4264 if (preg_match('#^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^.\\\\/]+?)|))[\\\\/.]*$#m', $path, $pathinfo)) {
4265 if (array_key_exists(1, $pathinfo)) {
4266 $ret['dirname'] = $pathinfo[1];
4268 if (array_key_exists(2, $pathinfo)) {
4269 $ret['basename'] = $pathinfo[2];
4271 if (array_key_exists(5, $pathinfo)) {
4272 $ret['extension'] = $pathinfo[5];
4274 if (array_key_exists(3, $pathinfo)) {
4275 $ret['filename'] = $pathinfo[3];
4278 switch ($options) {
4279 case PATHINFO_DIRNAME:
4280 case 'dirname':
4281 return $ret['dirname'];
4282 case PATHINFO_BASENAME:
4283 case 'basename':
4284 return $ret['basename'];
4285 case PATHINFO_EXTENSION:
4286 case 'extension':
4287 return $ret['extension'];
4288 case PATHINFO_FILENAME:
4289 case 'filename':
4290 return $ret['filename'];
4291 default:
4292 return $ret;
4297 * Set or reset instance properties.
4298 * You should avoid this function - it's more verbose, less efficient, more error-prone and
4299 * harder to debug than setting properties directly.
4300 * Usage Example:
4301 * `$mail->set('SMTPSecure', static::ENCRYPTION_STARTTLS);`
4302 * is the same as:
4303 * `$mail->SMTPSecure = static::ENCRYPTION_STARTTLS;`.
4305 * @param string $name The property name to set
4306 * @param mixed $value The value to set the property to
4308 * @return bool
4310 public function set($name, $value = '')
4312 if (property_exists($this, $name)) {
4313 $this->$name = $value;
4315 return true;
4317 $this->setError($this->lang('variable_set') . $name);
4319 return false;
4323 * Strip newlines to prevent header injection.
4325 * @param string $str
4327 * @return string
4329 public function secureHeader($str)
4331 return trim(str_replace(["\r", "\n"], '', $str));
4335 * Normalize line breaks in a string.
4336 * Converts UNIX LF, Mac CR and Windows CRLF line breaks into a single line break format.
4337 * Defaults to CRLF (for message bodies) and preserves consecutive breaks.
4339 * @param string $text
4340 * @param string $breaktype What kind of line break to use; defaults to static::$LE
4342 * @return string
4344 public static function normalizeBreaks($text, $breaktype = null)
4346 if (null === $breaktype) {
4347 $breaktype = static::$LE;
4349 // Normalise to \n
4350 $text = str_replace(["\r\n", "\r"], "\n", $text);
4351 // Now convert LE as needed
4352 if ("\n" !== $breaktype) {
4353 $text = str_replace("\n", $breaktype, $text);
4356 return $text;
4360 * Return the current line break format string.
4362 * @return string
4364 public static function getLE()
4366 return static::$LE;
4370 * Set the line break format string, e.g. "\r\n".
4372 * @param string $le
4374 protected static function setLE($le)
4376 static::$LE = $le;
4380 * Set the public and private key files and password for S/MIME signing.
4382 * @param string $cert_filename
4383 * @param string $key_filename
4384 * @param string $key_pass Password for private key
4385 * @param string $extracerts_filename Optional path to chain certificate
4387 public function sign($cert_filename, $key_filename, $key_pass, $extracerts_filename = '')
4389 $this->sign_cert_file = $cert_filename;
4390 $this->sign_key_file = $key_filename;
4391 $this->sign_key_pass = $key_pass;
4392 $this->sign_extracerts_file = $extracerts_filename;
4396 * Quoted-Printable-encode a DKIM header.
4398 * @param string $txt
4400 * @return string
4402 public function DKIM_QP($txt)
4404 $line = '';
4405 $len = strlen($txt);
4406 for ($i = 0; $i < $len; ++$i) {
4407 $ord = ord($txt[$i]);
4408 if (((0x21 <= $ord) && ($ord <= 0x3A)) || $ord === 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E))) {
4409 $line .= $txt[$i];
4410 } else {
4411 $line .= '=' . sprintf('%02X', $ord);
4415 return $line;
4419 * Generate a DKIM signature.
4421 * @param string $signHeader
4423 * @throws Exception
4425 * @return string The DKIM signature value
4427 public function DKIM_Sign($signHeader)
4429 if (!defined('PKCS7_TEXT')) {
4430 if ($this->exceptions) {
4431 throw new Exception($this->lang('extension_missing') . 'openssl');
4434 return '';
4436 $privKeyStr = !empty($this->DKIM_private_string) ?
4437 $this->DKIM_private_string :
4438 file_get_contents($this->DKIM_private);
4439 if ('' !== $this->DKIM_passphrase) {
4440 $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase);
4441 } else {
4442 $privKey = openssl_pkey_get_private($privKeyStr);
4444 if (openssl_sign($signHeader, $signature, $privKey, 'sha256WithRSAEncryption')) {
4445 openssl_pkey_free($privKey);
4447 return base64_encode($signature);
4449 openssl_pkey_free($privKey);
4451 return '';
4455 * Generate a DKIM canonicalization header.
4456 * Uses the 'relaxed' algorithm from RFC6376 section 3.4.2.
4457 * Canonicalized headers should *always* use CRLF, regardless of mailer setting.
4459 * @see https://tools.ietf.org/html/rfc6376#section-3.4.2
4461 * @param string $signHeader Header
4463 * @return string
4465 public function DKIM_HeaderC($signHeader)
4467 //Note PCRE \s is too broad a definition of whitespace; RFC5322 defines it as `[ \t]`
4468 //@see https://tools.ietf.org/html/rfc5322#section-2.2
4469 //That means this may break if you do something daft like put vertical tabs in your headers.
4470 //Unfold header lines
4471 $signHeader = preg_replace('/\r\n[ \t]+/', ' ', $signHeader);
4472 //Break headers out into an array
4473 $lines = explode("\r\n", $signHeader);
4474 foreach ($lines as $key => $line) {
4475 //If the header is missing a :, skip it as it's invalid
4476 //This is likely to happen because the explode() above will also split
4477 //on the trailing LE, leaving an empty line
4478 if (strpos($line, ':') === false) {
4479 continue;
4481 list($heading, $value) = explode(':', $line, 2);
4482 //Lower-case header name
4483 $heading = strtolower($heading);
4484 //Collapse white space within the value, also convert WSP to space
4485 $value = preg_replace('/[ \t]+/', ' ', $value);
4486 //RFC6376 is slightly unclear here - it says to delete space at the *end* of each value
4487 //But then says to delete space before and after the colon.
4488 //Net result is the same as trimming both ends of the value.
4489 //By elimination, the same applies to the field name
4490 $lines[$key] = trim($heading, " \t") . ':' . trim($value, " \t");
4493 return implode("\r\n", $lines);
4497 * Generate a DKIM canonicalization body.
4498 * Uses the 'simple' algorithm from RFC6376 section 3.4.3.
4499 * Canonicalized bodies should *always* use CRLF, regardless of mailer setting.
4501 * @see https://tools.ietf.org/html/rfc6376#section-3.4.3
4503 * @param string $body Message Body
4505 * @return string
4507 public function DKIM_BodyC($body)
4509 if (empty($body)) {
4510 return "\r\n";
4512 // Normalize line endings to CRLF
4513 $body = static::normalizeBreaks($body, "\r\n");
4515 //Reduce multiple trailing line breaks to a single one
4516 return rtrim($body, "\r\n") . "\r\n";
4520 * Create the DKIM header and body in a new message header.
4522 * @param string $headers_line Header lines
4523 * @param string $subject Subject
4524 * @param string $body Body
4526 * @throws Exception
4528 * @return string
4530 public function DKIM_Add($headers_line, $subject, $body)
4532 $DKIMsignatureType = 'rsa-sha256'; // Signature & hash algorithms
4533 $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization methods of header & body
4534 $DKIMquery = 'dns/txt'; // Query method
4535 $DKIMtime = time();
4536 //Always sign these headers without being asked
4537 $autoSignHeaders = [
4538 'From',
4539 'To',
4540 'CC',
4541 'Date',
4542 'Subject',
4543 'Reply-To',
4544 'Message-ID',
4545 'Content-Type',
4546 'Mime-Version',
4547 'X-Mailer',
4549 if (stripos($headers_line, 'Subject') === false) {
4550 $headers_line .= 'Subject: ' . $subject . static::$LE;
4552 $headerLines = explode(static::$LE, $headers_line);
4553 $currentHeaderLabel = '';
4554 $currentHeaderValue = '';
4555 $parsedHeaders = [];
4556 $headerLineIndex = 0;
4557 $headerLineCount = count($headerLines);
4558 foreach ($headerLines as $headerLine) {
4559 $matches = [];
4560 if (preg_match('/^([^ \t]*?)(?::[ \t]*)(.*)$/', $headerLine, $matches)) {
4561 if ($currentHeaderLabel !== '') {
4562 //We were previously in another header; This is the start of a new header, so save the previous one
4563 $parsedHeaders[] = ['label' => $currentHeaderLabel, 'value' => $currentHeaderValue];
4565 $currentHeaderLabel = $matches[1];
4566 $currentHeaderValue = $matches[2];
4567 } elseif (preg_match('/^[ \t]+(.*)$/', $headerLine, $matches)) {
4568 //This is a folded continuation of the current header, so unfold it
4569 $currentHeaderValue .= ' ' . $matches[1];
4571 ++$headerLineIndex;
4572 if ($headerLineIndex >= $headerLineCount) {
4573 //This was the last line, so finish off this header
4574 $parsedHeaders[] = ['label' => $currentHeaderLabel, 'value' => $currentHeaderValue];
4577 $copiedHeaders = [];
4578 $headersToSignKeys = [];
4579 $headersToSign = [];
4580 foreach ($parsedHeaders as $header) {
4581 //Is this header one that must be included in the DKIM signature?
4582 if (in_array($header['label'], $autoSignHeaders, true)) {
4583 $headersToSignKeys[] = $header['label'];
4584 $headersToSign[] = $header['label'] . ': ' . $header['value'];
4585 if ($this->DKIM_copyHeaderFields) {
4586 $copiedHeaders[] = $header['label'] . ':' . //Note no space after this, as per RFC
4587 str_replace('|', '=7C', $this->DKIM_QP($header['value']));
4589 continue;
4591 //Is this an extra custom header we've been asked to sign?
4592 if (in_array($header['label'], $this->DKIM_extraHeaders, true)) {
4593 //Find its value in custom headers
4594 foreach ($this->CustomHeader as $customHeader) {
4595 if ($customHeader[0] === $header['label']) {
4596 $headersToSignKeys[] = $header['label'];
4597 $headersToSign[] = $header['label'] . ': ' . $header['value'];
4598 if ($this->DKIM_copyHeaderFields) {
4599 $copiedHeaders[] = $header['label'] . ':' . //Note no space after this, as per RFC
4600 str_replace('|', '=7C', $this->DKIM_QP($header['value']));
4602 //Skip straight to the next header
4603 continue 2;
4608 $copiedHeaderFields = '';
4609 if ($this->DKIM_copyHeaderFields && count($copiedHeaders) > 0) {
4610 //Assemble a DKIM 'z' tag
4611 $copiedHeaderFields = ' z=';
4612 $first = true;
4613 foreach ($copiedHeaders as $copiedHeader) {
4614 if (!$first) {
4615 $copiedHeaderFields .= static::$LE . ' |';
4617 //Fold long values
4618 if (strlen($copiedHeader) > self::STD_LINE_LENGTH - 3) {
4619 $copiedHeaderFields .= substr(
4620 chunk_split($copiedHeader, self::STD_LINE_LENGTH - 3, static::$LE . ' '),
4622 -strlen(static::$LE . ' ')
4624 } else {
4625 $copiedHeaderFields .= $copiedHeader;
4627 $first = false;
4629 $copiedHeaderFields .= ';' . static::$LE;
4631 $headerKeys = ' h=' . implode(':', $headersToSignKeys) . ';' . static::$LE;
4632 $headerValues = implode(static::$LE, $headersToSign);
4633 $body = $this->DKIM_BodyC($body);
4634 $DKIMlen = strlen($body); // Length of body
4635 $DKIMb64 = base64_encode(pack('H*', hash('sha256', $body))); // Base64 of packed binary SHA-256 hash of body
4636 $ident = '';
4637 if ('' !== $this->DKIM_identity) {
4638 $ident = ' i=' . $this->DKIM_identity . ';' . static::$LE;
4640 //The DKIM-Signature header is included in the signature *except for* the value of the `b` tag
4641 //which is appended after calculating the signature
4642 //https://tools.ietf.org/html/rfc6376#section-3.5
4643 $dkimSignatureHeader = 'DKIM-Signature: v=1;' .
4644 ' d=' . $this->DKIM_domain . ';' .
4645 ' s=' . $this->DKIM_selector . ';' . static::$LE .
4646 ' a=' . $DKIMsignatureType . ';' .
4647 ' q=' . $DKIMquery . ';' .
4648 ' l=' . $DKIMlen . ';' .
4649 ' t=' . $DKIMtime . ';' .
4650 ' c=' . $DKIMcanonicalization . ';' . static::$LE .
4651 $headerKeys .
4652 $ident .
4653 $copiedHeaderFields .
4654 ' bh=' . $DKIMb64 . ';' . static::$LE .
4655 ' b=';
4656 //Canonicalize the set of headers
4657 $canonicalizedHeaders = $this->DKIM_HeaderC(
4658 $headerValues . static::$LE . $dkimSignatureHeader
4660 $signature = $this->DKIM_Sign($canonicalizedHeaders);
4661 $signature = trim(chunk_split($signature, self::STD_LINE_LENGTH - 3, static::$LE . ' '));
4663 return static::normalizeBreaks($dkimSignatureHeader . $signature) . static::$LE;
4667 * Detect if a string contains a line longer than the maximum line length
4668 * allowed by RFC 2822 section 2.1.1.
4670 * @param string $str
4672 * @return bool
4674 public static function hasLineLongerThanMax($str)
4676 return (bool) preg_match('/^(.{' . (self::MAX_LINE_LENGTH + strlen(static::$LE)) . ',})/m', $str);
4680 * Allows for public read access to 'to' property.
4681 * Before the send() call, queued addresses (i.e. with IDN) are not yet included.
4683 * @return array
4685 public function getToAddresses()
4687 return $this->to;
4691 * Allows for public read access to 'cc' property.
4692 * Before the send() call, queued addresses (i.e. with IDN) are not yet included.
4694 * @return array
4696 public function getCcAddresses()
4698 return $this->cc;
4702 * Allows for public read access to 'bcc' property.
4703 * Before the send() call, queued addresses (i.e. with IDN) are not yet included.
4705 * @return array
4707 public function getBccAddresses()
4709 return $this->bcc;
4713 * Allows for public read access to 'ReplyTo' property.
4714 * Before the send() call, queued addresses (i.e. with IDN) are not yet included.
4716 * @return array
4718 public function getReplyToAddresses()
4720 return $this->ReplyTo;
4724 * Allows for public read access to 'all_recipients' property.
4725 * Before the send() call, queued addresses (i.e. with IDN) are not yet included.
4727 * @return array
4729 public function getAllRecipientAddresses()
4731 return $this->all_recipients;
4735 * Perform a callback.
4737 * @param bool $isSent
4738 * @param array $to
4739 * @param array $cc
4740 * @param array $bcc
4741 * @param string $subject
4742 * @param string $body
4743 * @param string $from
4744 * @param array $extra
4746 protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body, $from, $extra)
4748 if (!empty($this->action_function) && is_callable($this->action_function)) {
4749 call_user_func($this->action_function, $isSent, $to, $cc, $bcc, $subject, $body, $from, $extra);
4754 * Get the OAuth instance.
4756 * @return OAuth
4758 public function getOAuth()
4760 return $this->oauth;
4764 * Set an OAuth instance.
4766 public function setOAuth(OAuth $oauth)
4768 $this->oauth = $oauth;