3 * PHPMailer - PHP email creation and transport class.
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 - 2017 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;
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)
33 const CHARSET_ISO88591 = 'iso-8859-1';
34 const CHARSET_UTF8 = 'utf-8';
36 const CONTENT_TYPE_PLAINTEXT = 'text/plain';
37 const CONTENT_TYPE_TEXT_CALENDAR = 'text/calendar';
38 const CONTENT_TYPE_TEXT_HTML = 'text/html';
39 const CONTENT_TYPE_MULTIPART_ALTERNATIVE = 'multipart/alternative';
40 const CONTENT_TYPE_MULTIPART_MIXED = 'multipart/mixed';
41 const CONTENT_TYPE_MULTIPART_RELATED = 'multipart/related';
43 const ENCODING_7BIT = '7bit';
44 const ENCODING_8BIT = '8bit';
45 const ENCODING_BASE64 = 'base64';
46 const ENCODING_BINARY = 'binary';
47 const ENCODING_QUOTED_PRINTABLE = 'quoted-printable';
51 * Options: null (default), 1 = High, 3 = Normal, 5 = low.
52 * When null, the header is not set at all.
59 * The character set of the message.
63 public $CharSet = self::CHARSET_ISO88591;
66 * The MIME Content-type of the message.
70 public $ContentType = self::CONTENT_TYPE_PLAINTEXT;
73 * The message encoding.
74 * Options: "8bit", "7bit", "binary", "base64", and "quoted-printable".
78 public $Encoding = self::ENCODING_8BIT;
81 * Holds the most recent mailer error message.
85 public $ErrorInfo = '';
88 * The From email address for the message.
92 public $From = 'root@localhost';
95 * The From name of the message.
99 public $FromName = 'Root User';
102 * The envelope sender of the message.
103 * This will usually be turned into a Return-Path header by the receiver,
104 * and is the address that bounces will be sent to.
105 * If not empty, will be passed via `-f` to sendmail or as the 'MAIL FROM' value over SMTP.
112 * The Subject of the message.
116 public $Subject = '';
119 * An HTML or plain text message body.
120 * If HTML then call isHTML(true).
127 * The plain-text message body.
128 * This body can be read by mail clients that do not have HTML email
129 * capability such as mutt & Eudora.
130 * Clients that can read HTML will view the normal Body.
134 public $AltBody = '';
137 * An iCal message part body.
138 * Only supported in simple alt or alt_inline message types
139 * To generate iCal event structures, use classes like EasyPeasyICS or iCalcreator.
141 * @see http://sprain.ch/blog/downloads/php-class-easypeasyics-create-ical-files-with-php/
142 * @see http://kigkonsult.se/iCalcreator/
149 * The complete compiled MIME message body.
153 protected $MIMEBody = '';
156 * The complete compiled MIME message headers.
160 protected $MIMEHeader = '';
163 * Extra headers that createHeader() doesn't fold in.
167 protected $mailHeader = '';
170 * Word-wrap the message body to this number of chars.
171 * Set to 0 to not wrap. A useful value here is 78, for RFC2822 section 2.1.1 compliance.
173 * @see static::STD_LINE_LENGTH
177 public $WordWrap = 0;
180 * Which method to use to send mail.
181 * Options: "mail", "sendmail", or "smtp".
185 public $Mailer = 'mail';
188 * The path to the sendmail program.
192 public $Sendmail = '/usr/sbin/sendmail';
195 * Whether mail() uses a fully sendmail-compatible MTA.
196 * One which supports sendmail's "-oi -f" options.
200 public $UseSendmailOptions = true;
203 * The email address that a reading confirmation should be sent to, also known as read receipt.
207 public $ConfirmReadingTo = '';
210 * The hostname to use in the Message-ID header and as default HELO string.
211 * If empty, PHPMailer attempts to find one with, in order,
212 * $_SERVER['SERVER_NAME'], gethostname(), php_uname('n'), or the value
213 * 'localhost.localdomain'.
217 public $Hostname = '';
220 * An ID to be used in the Message-ID header.
221 * If empty, a unique id will be generated.
222 * You can set your own, but it must be in the format "<id@domain>",
223 * as defined in RFC5322 section 3.6.4 or it will be ignored.
225 * @see https://tools.ietf.org/html/rfc5322#section-3.6.4
229 public $MessageID = '';
232 * The message Date to be used in the Date header.
233 * If empty, the current date will be added.
237 public $MessageDate = '';
241 * Either a single hostname or multiple semicolon-delimited hostnames.
242 * You can also specify a different port
243 * for each host by using this format: [hostname:port]
244 * (e.g. "smtp1.example.com:25;smtp2.example.com").
245 * You can also specify encryption type, for example:
246 * (e.g. "tls://smtp1.example.com:587;ssl://smtp2.example.com:465").
247 * Hosts will be tried in order.
251 public $Host = 'localhost';
254 * The default SMTP server port.
261 * The SMTP HELO of the message.
262 * Default is $Hostname. If $Hostname is empty, PHPMailer attempts to find
263 * one with the same method described above for $Hostname.
265 * @see PHPMailer::$Hostname
272 * What kind of encryption to use on the SMTP connection.
273 * Options: '', 'ssl' or 'tls'.
277 public $SMTPSecure = '';
280 * Whether to enable TLS encryption automatically if a server supports it,
281 * even if `SMTPSecure` is not set to 'tls'.
282 * Be aware that in PHP >= 5.6 this requires that the server's certificates are valid.
286 public $SMTPAutoTLS = true;
289 * Whether to use SMTP authentication.
290 * Uses the Username and Password properties.
292 * @see PHPMailer::$Username
293 * @see PHPMailer::$Password
297 public $SMTPAuth = false;
300 * Options array passed to stream_context_create when connecting via SMTP.
304 public $SMTPOptions = [];
311 public $Username = '';
318 public $Password = '';
322 * Options are CRAM-MD5, LOGIN, PLAIN, XOAUTH2, attempted in that order if not specified.
326 public $AuthType = '';
329 * An instance of the PHPMailer OAuth class.
336 * The SMTP server timeout in seconds.
337 * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2.
341 public $Timeout = 300;
344 * Comma separated list of DSN notifications
345 * 'NEVER' under no circumstances a DSN must be returned to the sender.
346 * If you use NEVER all other notifications will be ignored.
347 * 'SUCCESS' will notify you when your mail has arrived at its destination.
348 * 'FAILURE' will arrive if an error occurred during delivery.
349 * 'DELAY' will notify you if there is an unusual delay in delivery, but the actual
350 * delivery's outcome (success or failure) is not yet decided.
352 * @see https://tools.ietf.org/html/rfc3461 See section 4.1 for more information about NOTIFY
357 * SMTP class debug output mode.
358 * Debug output level.
362 * * `2` Data and commands
363 * * `3` As 2 plus connection status
364 * * `4` Low-level data output.
366 * @see SMTP::$do_debug
370 public $SMTPDebug = 0;
373 * How to handle debug output.
375 * * `echo` Output plain-text as-is, appropriate for CLI
376 * * `html` Output escaped, line breaks converted to `<br>`, appropriate for browser output
377 * * `error_log` Output to error log as configured in php.ini
378 * By default PHPMailer will use `echo` if run from a `cli` or `cli-server` SAPI, `html` otherwise.
379 * Alternatively, you can provide a callable expecting two params: a message string and the debug level:
382 * $mail->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";};
385 * Alternatively, you can pass in an instance of a PSR-3 compatible logger, though only `debug`
386 * level output is used:
389 * $mail->Debugoutput = new myPsr3Logger;
392 * @see SMTP::$Debugoutput
394 * @var string|callable|\Psr\Log\LoggerInterface
396 public $Debugoutput = 'echo';
399 * Whether to keep SMTP connection open after each message.
400 * If this is set to true then to close the connection
401 * requires an explicit call to smtpClose().
405 public $SMTPKeepAlive = false;
408 * Whether to split multiple to addresses into multiple messages
409 * or send them all in one message.
410 * Only supported in `mail` and `sendmail` transports, not in SMTP.
414 public $SingleTo = false;
417 * Storage for addresses when SingleTo is enabled.
421 protected $SingleToArray = [];
424 * Whether to generate VERP addresses on send.
425 * Only applicable when sending via SMTP.
427 * @see https://en.wikipedia.org/wiki/Variable_envelope_return_path
428 * @see http://www.postfix.org/VERP_README.html Postfix VERP info
432 public $do_verp = false;
435 * Whether to allow sending messages with an empty body.
439 public $AllowEmpty = false;
446 public $DKIM_selector = '';
450 * Usually the email address used as the source of the email.
454 public $DKIM_identity = '';
458 * Used if your key is encrypted.
462 public $DKIM_passphrase = '';
465 * DKIM signing domain name.
467 * @example 'example.com'
471 public $DKIM_domain = '';
474 * DKIM Copy header field values for diagnostic use.
478 public $DKIM_copyHeaderFields = true;
481 * DKIM Extra signing headers.
483 * @example ['List-Unsubscribe', 'List-Help']
487 public $DKIM_extraHeaders = [];
490 * DKIM private key file path.
494 public $DKIM_private = '';
497 * DKIM private key string.
499 * If set, takes precedence over `$DKIM_private`.
503 public $DKIM_private_string = '';
506 * Callback Action function name.
508 * The function that handles the result of the send email action.
509 * It is called out by send() for each email sent.
511 * Value can be any php callable: http://www.php.net/is_callable
514 * bool $result result of the send action
515 * array $to email addresses of the recipients
516 * array $cc cc email addresses
517 * array $bcc bcc email addresses
518 * string $subject the subject
519 * string $body the email body
520 * string $from email address of sender
521 * string $extra extra information of possible use
522 * "smtp_transaction_id' => last smtp transaction id
526 public $action_function = '';
529 * What to put in the X-Mailer header.
530 * Options: An empty string for PHPMailer default, whitespace/null for none, or a string to use.
534 public $XMailer = '';
537 * Which validator to use by default when validating email addresses.
538 * May be a callable to inject your own validator, but there are several built-in validators.
539 * The default validator uses PHP's FILTER_VALIDATE_EMAIL filter_var option.
541 * @see PHPMailer::validateAddress()
543 * @var string|callable
545 public static $validator = 'php';
548 * An instance of the SMTP sender class.
555 * The array of 'to' names and addresses.
562 * The array of 'cc' names and addresses.
569 * The array of 'bcc' names and addresses.
576 * The array of reply-to names and addresses.
580 protected $ReplyTo = [];
583 * An array of all kinds of addresses.
584 * Includes all of $to, $cc, $bcc.
586 * @see PHPMailer::$to
587 * @see PHPMailer::$cc
588 * @see PHPMailer::$bcc
592 protected $all_recipients = [];
595 * An array of names and addresses queued for validation.
596 * In send(), valid and non duplicate entries are moved to $all_recipients
597 * and one of $to, $cc, or $bcc.
598 * This array is used only for addresses with IDN.
600 * @see PHPMailer::$to
601 * @see PHPMailer::$cc
602 * @see PHPMailer::$bcc
603 * @see PHPMailer::$all_recipients
607 protected $RecipientsQueue = [];
610 * An array of reply-to names and addresses queued for validation.
611 * In send(), valid and non duplicate entries are moved to $ReplyTo.
612 * This array is used only for addresses with IDN.
614 * @see PHPMailer::$ReplyTo
618 protected $ReplyToQueue = [];
621 * The array of attachments.
625 protected $attachment = [];
628 * The array of custom headers.
632 protected $CustomHeader = [];
635 * The most recent Message-ID (including angular brackets).
639 protected $lastMessageID = '';
642 * The message's MIME type.
646 protected $message_type = '';
649 * The array of MIME boundary strings.
653 protected $boundary = [];
656 * The array of available languages.
660 protected $language = [];
663 * The number of errors encountered.
667 protected $error_count = 0;
670 * The S/MIME certificate file path.
674 protected $sign_cert_file = '';
677 * The S/MIME key file path.
681 protected $sign_key_file = '';
684 * The optional S/MIME extra certificates ("CA Chain") file path.
688 protected $sign_extracerts_file = '';
691 * The S/MIME password for the key.
692 * Used only if the key is encrypted.
696 protected $sign_key_pass = '';
699 * Whether to throw exceptions for errors.
703 protected $exceptions = false;
706 * Unique ID used for message ID and boundaries.
710 protected $uniqueid = '';
713 * The PHPMailer Version number.
717 const VERSION = '6.0.7';
720 * Error severity: message only, continue processing.
724 const STOP_MESSAGE = 0;
727 * Error severity: message, likely ok to continue processing.
731 const STOP_CONTINUE = 1;
734 * Error severity: message, plus full stop, critical error reached.
738 const STOP_CRITICAL = 2;
741 * SMTP RFC standard line ending.
745 protected static $LE = "\r\n";
748 * The maximum line length allowed by RFC 2822 section 2.1.1.
752 const MAX_LINE_LENGTH = 998;
755 * The lower maximum line length allowed by RFC 2822 section 2.1.1.
756 * This length does NOT include the line break
757 * 76 means that lines will be 77 or 78 chars depending on whether
758 * the line break format is LF or CRLF; both are valid.
762 const STD_LINE_LENGTH = 76;
767 * @param bool $exceptions Should we throw external exceptions?
769 public function __construct($exceptions = null)
771 if (null !== $exceptions) {
772 $this->exceptions = (bool) $exceptions;
774 //Pick an appropriate debug output format automatically
775 $this->Debugoutput = (strpos(PHP_SAPI, 'cli') !== false ? 'echo' : 'html');
781 public function __destruct()
783 //Close any open SMTP connection nicely
788 * Call mail() in a safe_mode-aware fashion.
789 * Also, unless sendmail_path points to sendmail (or something that
790 * claims to be sendmail), don't pass params (not a perfect fix,
793 * @param string $to To
794 * @param string $subject Subject
795 * @param string $body Message Body
796 * @param string $header Additional Header(s)
797 * @param string|null $params Params
801 private function mailPassthru($to, $subject, $body, $header, $params)
803 //Check overloading of mail function to avoid double-encoding
804 if (ini_get('mbstring.func_overload') & 1) {
805 $subject = $this->secureHeader($subject);
807 $subject = $this->encodeHeader($this->secureHeader($subject));
809 //Calling mail() with null params breaks
810 if (!$this->UseSendmailOptions or null === $params) {
811 $result = @mail($to, $subject, $body, $header);
813 $result = @mail($to, $subject, $body, $header, $params);
820 * Output debugging info via user-defined method.
821 * Only generates output if SMTP debug output is enabled (@see SMTP::$do_debug).
823 * @see PHPMailer::$Debugoutput
824 * @see PHPMailer::$SMTPDebug
828 protected function edebug($str)
830 if ($this->SMTPDebug <= 0) {
833 //Is this a PSR-3 logger?
834 if ($this->Debugoutput instanceof \Psr\Log\LoggerInterface) {
835 $this->Debugoutput->debug($str);
839 //Avoid clash with built-in function names
840 if (!in_array($this->Debugoutput, ['error_log', 'html', 'echo']) and is_callable($this->Debugoutput)) {
841 call_user_func($this->Debugoutput, $str, $this->SMTPDebug);
845 switch ($this->Debugoutput) {
847 //Don't output, just log
851 //Cleans up output a bit for a better looking, HTML-safe output
853 preg_replace('/[\r\n]+/', '', $str),
860 //Normalize line breaks
861 $str = preg_replace('/\r\n|\r/ms', "\n", $str);
862 echo gmdate('Y-m-d H:i:s'),
864 //Trim trailing space
866 //Indent for readability, except for trailing break
878 * Sets message type to HTML or plain.
880 * @param bool $isHtml True for HTML mode
882 public function isHTML($isHtml = true)
885 $this->ContentType = static::CONTENT_TYPE_TEXT_HTML;
887 $this->ContentType = static::CONTENT_TYPE_PLAINTEXT;
892 * Send messages using SMTP.
894 public function isSMTP()
896 $this->Mailer = 'smtp';
900 * Send messages using PHP's mail() function.
902 public function isMail()
904 $this->Mailer = 'mail';
908 * Send messages using $Sendmail.
910 public function isSendmail()
912 $ini_sendmail_path = ini_get('sendmail_path');
914 if (false === stripos($ini_sendmail_path, 'sendmail')) {
915 $this->Sendmail = '/usr/sbin/sendmail';
917 $this->Sendmail = $ini_sendmail_path;
919 $this->Mailer = 'sendmail';
923 * Send messages using qmail.
925 public function isQmail()
927 $ini_sendmail_path = ini_get('sendmail_path');
929 if (false === stripos($ini_sendmail_path, 'qmail')) {
930 $this->Sendmail = '/var/qmail/bin/qmail-inject';
932 $this->Sendmail = $ini_sendmail_path;
934 $this->Mailer = 'qmail';
938 * Add a "To" address.
940 * @param string $address The email address to send to
941 * @param string $name
945 * @return bool true on success, false if address already used or invalid in some way
947 public function addAddress($address, $name = '')
949 return $this->addOrEnqueueAnAddress('to', $address, $name);
953 * Add a "CC" address.
955 * @param string $address The email address to send to
956 * @param string $name
960 * @return bool true on success, false if address already used or invalid in some way
962 public function addCC($address, $name = '')
964 return $this->addOrEnqueueAnAddress('cc', $address, $name);
968 * Add a "BCC" address.
970 * @param string $address The email address to send to
971 * @param string $name
975 * @return bool true on success, false if address already used or invalid in some way
977 public function addBCC($address, $name = '')
979 return $this->addOrEnqueueAnAddress('bcc', $address, $name);
983 * Add a "Reply-To" address.
985 * @param string $address The email address to reply to
986 * @param string $name
990 * @return bool true on success, false if address already used or invalid in some way
992 public function addReplyTo($address, $name = '')
994 return $this->addOrEnqueueAnAddress('Reply-To', $address, $name);
998 * Add an address to one of the recipient arrays or to the ReplyTo array. Because PHPMailer
999 * can't validate addresses with an IDN without knowing the PHPMailer::$CharSet (that can still
1000 * be modified after calling this function), addition of such addresses is delayed until send().
1001 * Addresses that have been added already return false, but do not throw exceptions.
1003 * @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo'
1004 * @param string $address The email address to send, resp. to reply to
1005 * @param string $name
1009 * @return bool true on success, false if address already used or invalid in some way
1011 protected function addOrEnqueueAnAddress($kind, $address, $name)
1013 $address = trim($address);
1014 $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
1015 $pos = strrpos($address, '@');
1016 if (false === $pos) {
1017 // At-sign is missing.
1018 $error_message = sprintf(
1020 $this->lang('invalid_address'),
1024 $this->setError($error_message);
1025 $this->edebug($error_message);
1026 if ($this->exceptions) {
1027 throw new Exception($error_message);
1032 $params = [$kind, $address, $name];
1033 // Enqueue addresses with IDN until we know the PHPMailer::$CharSet.
1034 if ($this->has8bitChars(substr($address, ++$pos)) and static::idnSupported()) {
1035 if ('Reply-To' != $kind) {
1036 if (!array_key_exists($address, $this->RecipientsQueue)) {
1037 $this->RecipientsQueue[$address] = $params;
1042 if (!array_key_exists($address, $this->ReplyToQueue)) {
1043 $this->ReplyToQueue[$address] = $params;
1052 // Immediately add standard addresses without IDN.
1053 return call_user_func_array([$this, 'addAnAddress'], $params);
1057 * Add an address to one of the recipient arrays or to the ReplyTo array.
1058 * Addresses that have been added already return false, but do not throw exceptions.
1060 * @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo'
1061 * @param string $address The email address to send, resp. to reply to
1062 * @param string $name
1066 * @return bool true on success, false if address already used or invalid in some way
1068 protected function addAnAddress($kind, $address, $name = '')
1070 if (!in_array($kind, ['to', 'cc', 'bcc', 'Reply-To'])) {
1071 $error_message = sprintf('%s: %s',
1072 $this->lang('Invalid recipient kind'),
1074 $this->setError($error_message);
1075 $this->edebug($error_message);
1076 if ($this->exceptions) {
1077 throw new Exception($error_message);
1082 if (!static::validateAddress($address)) {
1083 $error_message = sprintf('%s (%s): %s',
1084 $this->lang('invalid_address'),
1087 $this->setError($error_message);
1088 $this->edebug($error_message);
1089 if ($this->exceptions) {
1090 throw new Exception($error_message);
1095 if ('Reply-To' != $kind) {
1096 if (!array_key_exists(strtolower($address), $this->all_recipients)) {
1097 $this->{$kind}[] = [$address, $name];
1098 $this->all_recipients[strtolower($address)] = true;
1103 if (!array_key_exists(strtolower($address), $this->ReplyTo)) {
1104 $this->ReplyTo[strtolower($address)] = [$address, $name];
1114 * Parse and validate a string containing one or more RFC822-style comma-separated email addresses
1115 * of the form "display name <address>" into an array of name/address pairs.
1116 * Uses the imap_rfc822_parse_adrlist function if the IMAP extension is available.
1117 * Note that quotes in the name part are removed.
1119 * @see http://www.andrew.cmu.edu/user/agreen1/testing/mrbs/web/Mail/RFC822.php A more careful implementation
1121 * @param string $addrstr The address list string
1122 * @param bool $useimap Whether to use the IMAP extension to parse the list
1126 public static function parseAddresses($addrstr, $useimap = true)
1129 if ($useimap and function_exists('imap_rfc822_parse_adrlist')) {
1130 //Use this built-in parser if it's available
1131 $list = imap_rfc822_parse_adrlist($addrstr, '');
1132 foreach ($list as $address) {
1133 if ('.SYNTAX-ERROR.' != $address->host) {
1134 if (static::validateAddress($address->mailbox . '@' . $address->host)) {
1136 'name' => (property_exists($address, 'personal') ? $address->personal : ''),
1137 'address' => $address->mailbox . '@' . $address->host,
1143 //Use this simpler parser
1144 $list = explode(',', $addrstr);
1145 foreach ($list as $address) {
1146 $address = trim($address);
1147 //Is there a separate name part?
1148 if (strpos($address, '<') === false) {
1149 //No separate name, just use the whole thing
1150 if (static::validateAddress($address)) {
1153 'address' => $address,
1157 list($name, $email) = explode('<', $address);
1158 $email = trim(str_replace('>', '', $email));
1159 if (static::validateAddress($email)) {
1161 'name' => trim(str_replace(['"', "'"], '', $name)),
1162 'address' => $email,
1173 * Set the From and FromName properties.
1175 * @param string $address
1176 * @param string $name
1177 * @param bool $auto Whether to also set the Sender address, defaults to true
1183 public function setFrom($address, $name = '', $auto = true)
1185 $address = trim($address);
1186 $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
1187 // Don't validate now addresses with IDN. Will be done in send().
1188 $pos = strrpos($address, '@');
1189 if (false === $pos or
1190 (!$this->has8bitChars(substr($address, ++$pos)) or !static::idnSupported()) and
1191 !static::validateAddress($address)) {
1192 $error_message = sprintf('%s (From): %s',
1193 $this->lang('invalid_address'),
1195 $this->setError($error_message);
1196 $this->edebug($error_message);
1197 if ($this->exceptions) {
1198 throw new Exception($error_message);
1203 $this->From = $address;
1204 $this->FromName = $name;
1206 if (empty($this->Sender)) {
1207 $this->Sender = $address;
1215 * Return the Message-ID header of the last email.
1216 * Technically this is the value from the last time the headers were created,
1217 * but it's also the message ID of the last sent message except in
1218 * pathological cases.
1222 public function getLastMessageID()
1224 return $this->lastMessageID;
1228 * Check that a string looks like an email address.
1229 * Validation patterns supported:
1230 * * `auto` Pick best pattern automatically;
1231 * * `pcre8` Use the squiloople.com pattern, requires PCRE > 8.0;
1232 * * `pcre` Use old PCRE implementation;
1233 * * `php` Use PHP built-in FILTER_VALIDATE_EMAIL;
1234 * * `html5` Use the pattern given by the HTML5 spec for 'email' type form input elements.
1235 * * `noregex` Don't use a regex: super fast, really dumb.
1236 * Alternatively you may pass in a callable to inject your own validator, for example:
1239 * PHPMailer::validateAddress('user@example.com', function($address) {
1240 * return (strpos($address, '@') !== false);
1244 * You can also set the PHPMailer::$validator static to a callable, allowing built-in methods to use your validator.
1246 * @param string $address The email address to check
1247 * @param string|callable $patternselect Which pattern to use
1251 public static function validateAddress($address, $patternselect = null)
1253 if (null === $patternselect) {
1254 $patternselect = static::$validator;
1256 if (is_callable($patternselect)) {
1257 return call_user_func($patternselect, $address);
1259 //Reject line breaks in addresses; it's valid RFC5322, but not RFC5321
1260 if (strpos($address, "\n") !== false or strpos($address, "\r") !== false) {
1263 switch ($patternselect) {
1264 case 'pcre': //Kept for BC
1267 * A more complex and more permissive version of the RFC5322 regex on which FILTER_VALIDATE_EMAIL
1269 * In addition to the addresses allowed by filter_var, also permits:
1270 * * dotless domains: `a@b`
1271 * * comments: `1234 @ local(blah) .machine .example`
1272 * * quoted elements: `'"test blah"@example.org'`
1273 * * numeric TLDs: `a@b.123`
1274 * * unbracketed IPv4 literals: `a@192.168.0.1`
1275 * * IPv6 literals: 'first.last@[IPv6:a1::]'
1276 * Not all of these will necessarily work for sending!
1278 * @see http://squiloople.com/2009/12/20/email-address-validation/
1279 * @copyright 2009-2010 Michael Rushton
1280 * Feel free to use and redistribute this code. But please keep this copyright notice.
1282 return (bool) preg_match(
1283 '/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)' .
1284 '((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)' .
1285 '(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)' .
1286 '([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*' .
1287 '(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)' .
1288 '(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}' .
1289 '|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:' .
1290 '|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}' .
1291 '|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD',
1296 * This is the pattern used in the HTML5 spec for validation of 'email' type form input elements.
1298 * @see http://www.whatwg.org/specs/web-apps/current-work/#e-mail-state-(type=email)
1300 return (bool) preg_match(
1301 '/^[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}' .
1302 '[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/sD',
1307 return (bool) filter_var($address, FILTER_VALIDATE_EMAIL);
1312 * Tells whether IDNs (Internationalized Domain Names) are supported or not. This requires the
1313 * `intl` and `mbstring` PHP extensions.
1315 * @return bool `true` if required functions for IDN support are present
1317 public static function idnSupported()
1319 return function_exists('idn_to_ascii') and function_exists('mb_convert_encoding');
1323 * Converts IDN in given email address to its ASCII form, also known as punycode, if possible.
1324 * Important: Address must be passed in same encoding as currently set in PHPMailer::$CharSet.
1325 * This function silently returns unmodified address if:
1326 * - No conversion is necessary (i.e. domain name is not an IDN, or is already in ASCII form)
1327 * - Conversion to punycode is impossible (e.g. required PHP functions are not available)
1328 * or fails for any reason (e.g. domain contains characters not allowed in an IDN).
1330 * @see PHPMailer::$CharSet
1332 * @param string $address The email address to convert
1334 * @return string The encoded address in ASCII form
1336 public function punyencodeAddress($address)
1338 // Verify we have required functions, CharSet, and at-sign.
1339 $pos = strrpos($address, '@');
1340 if (static::idnSupported() and
1341 !empty($this->CharSet) and
1344 $domain = substr($address, ++$pos);
1345 // Verify CharSet string is a valid one, and domain properly encoded in this CharSet.
1346 if ($this->has8bitChars($domain) and @mb_check_encoding($domain, $this->CharSet)) {
1347 $domain = mb_convert_encoding($domain, 'UTF-8', $this->CharSet);
1348 //Ignore IDE complaints about this line - method signature changed in PHP 5.4
1350 $punycode = idn_to_ascii($domain, $errorcode, INTL_IDNA_VARIANT_UTS46);
1351 if (false !== $punycode) {
1352 return substr($address, 0, $pos) . $punycode;
1361 * Create a message and send it.
1362 * Uses the sending method specified by $Mailer.
1366 * @return bool false on error - See the ErrorInfo property for details of the error
1368 public function send()
1371 if (!$this->preSend()) {
1375 return $this->postSend();
1376 } catch (Exception $exc) {
1377 $this->mailHeader = '';
1378 $this->setError($exc->getMessage());
1379 if ($this->exceptions) {
1388 * Prepare a message for sending.
1394 public function preSend()
1396 if ('smtp' == $this->Mailer or
1397 ('mail' == $this->Mailer and stripos(PHP_OS, 'WIN') === 0)
1399 //SMTP mandates RFC-compliant line endings
1400 //and it's also used with mail() on Windows
1401 static::setLE("\r\n");
1403 //Maintain backward compatibility with legacy Linux command line mailers
1404 static::setLE(PHP_EOL);
1406 //Check for buggy PHP versions that add a header with an incorrect line break
1407 if (ini_get('mail.add_x_header') == 1
1408 and 'mail' == $this->Mailer
1409 and stripos(PHP_OS, 'WIN') === 0
1410 and ((version_compare(PHP_VERSION, '7.0.0', '>=')
1411 and version_compare(PHP_VERSION, '7.0.17', '<'))
1412 or (version_compare(PHP_VERSION, '7.1.0', '>=')
1413 and version_compare(PHP_VERSION, '7.1.3', '<')))
1416 'Your version of PHP is affected by a bug that may result in corrupted messages.' .
1417 ' To fix it, switch to sending using SMTP, disable the mail.add_x_header option in' .
1418 ' your php.ini, switch to MacOS or Linux, or upgrade your PHP to version 7.0.17+ or 7.1.3+.',
1424 $this->error_count = 0; // Reset errors
1425 $this->mailHeader = '';
1427 // Dequeue recipient and Reply-To addresses with IDN
1428 foreach (array_merge($this->RecipientsQueue, $this->ReplyToQueue) as $params) {
1429 $params[1] = $this->punyencodeAddress($params[1]);
1430 call_user_func_array([$this, 'addAnAddress'], $params);
1432 if (count($this->to) + count($this->cc) + count($this->bcc) < 1) {
1433 throw new Exception($this->lang('provide_address'), self::STOP_CRITICAL);
1436 // Validate From, Sender, and ConfirmReadingTo addresses
1437 foreach (['From', 'Sender', 'ConfirmReadingTo'] as $address_kind) {
1438 $this->$address_kind = trim($this->$address_kind);
1439 if (empty($this->$address_kind)) {
1442 $this->$address_kind = $this->punyencodeAddress($this->$address_kind);
1443 if (!static::validateAddress($this->$address_kind)) {
1444 $error_message = sprintf('%s (%s): %s',
1445 $this->lang('invalid_address'),
1447 $this->$address_kind);
1448 $this->setError($error_message);
1449 $this->edebug($error_message);
1450 if ($this->exceptions) {
1451 throw new Exception($error_message);
1458 // Set whether the message is multipart/alternative
1459 if ($this->alternativeExists()) {
1460 $this->ContentType = static::CONTENT_TYPE_MULTIPART_ALTERNATIVE;
1463 $this->setMessageType();
1464 // Refuse to send an empty message unless we are specifically allowing it
1465 if (!$this->AllowEmpty and empty($this->Body)) {
1466 throw new Exception($this->lang('empty_message'), self::STOP_CRITICAL);
1469 //Trim subject consistently
1470 $this->Subject = trim($this->Subject);
1471 // Create body before headers in case body makes changes to headers (e.g. altering transfer encoding)
1472 $this->MIMEHeader = '';
1473 $this->MIMEBody = $this->createBody();
1474 // createBody may have added some headers, so retain them
1475 $tempheaders = $this->MIMEHeader;
1476 $this->MIMEHeader = $this->createHeader();
1477 $this->MIMEHeader .= $tempheaders;
1479 // To capture the complete message when using mail(), create
1480 // an extra header list which createHeader() doesn't fold in
1481 if ('mail' == $this->Mailer) {
1482 if (count($this->to) > 0) {
1483 $this->mailHeader .= $this->addrAppend('To', $this->to);
1485 $this->mailHeader .= $this->headerLine('To', 'undisclosed-recipients:;');
1487 $this->mailHeader .= $this->headerLine(
1489 $this->encodeHeader($this->secureHeader($this->Subject))
1493 // Sign with DKIM if enabled
1494 if (!empty($this->DKIM_domain)
1495 and !empty($this->DKIM_selector)
1496 and (!empty($this->DKIM_private_string)
1497 or (!empty($this->DKIM_private)
1498 and static::isPermittedPath($this->DKIM_private)
1499 and file_exists($this->DKIM_private)
1503 $header_dkim = $this->DKIM_Add(
1504 $this->MIMEHeader . $this->mailHeader,
1505 $this->encodeHeader($this->secureHeader($this->Subject)),
1508 $this->MIMEHeader = rtrim($this->MIMEHeader, "\r\n ") . static::$LE .
1509 static::normalizeBreaks($header_dkim) . static::$LE;
1513 } catch (Exception $exc) {
1514 $this->setError($exc->getMessage());
1515 if ($this->exceptions) {
1524 * Actually send a message via the selected mechanism.
1530 public function postSend()
1533 // Choose the mailer and send through it
1534 switch ($this->Mailer) {
1537 return $this->sendmailSend($this->MIMEHeader, $this->MIMEBody);
1539 return $this->smtpSend($this->MIMEHeader, $this->MIMEBody);
1541 return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
1543 $sendMethod = $this->Mailer . 'Send';
1544 if (method_exists($this, $sendMethod)) {
1545 return $this->$sendMethod($this->MIMEHeader, $this->MIMEBody);
1548 return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
1550 } catch (Exception $exc) {
1551 $this->setError($exc->getMessage());
1552 $this->edebug($exc->getMessage());
1553 if ($this->exceptions) {
1562 * Send mail using the $Sendmail program.
1564 * @see PHPMailer::$Sendmail
1566 * @param string $header The message headers
1567 * @param string $body The message body
1573 protected function sendmailSend($header, $body)
1575 // CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped.
1576 if (!empty($this->Sender) and self::isShellSafe($this->Sender)) {
1577 if ('qmail' == $this->Mailer) {
1578 $sendmailFmt = '%s -f%s';
1580 $sendmailFmt = '%s -oi -f%s -t';
1583 if ('qmail' == $this->Mailer) {
1584 $sendmailFmt = '%s';
1586 $sendmailFmt = '%s -oi -t';
1590 $sendmail = sprintf($sendmailFmt, escapeshellcmd($this->Sendmail), $this->Sender);
1592 if ($this->SingleTo) {
1593 foreach ($this->SingleToArray as $toAddr) {
1594 $mail = @popen($sendmail, 'w');
1596 throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1598 fwrite($mail, 'To: ' . $toAddr . "\n");
1599 fwrite($mail, $header);
1600 fwrite($mail, $body);
1601 $result = pclose($mail);
1612 if (0 !== $result) {
1613 throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1617 $mail = @popen($sendmail, 'w');
1619 throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1621 fwrite($mail, $header);
1622 fwrite($mail, $body);
1623 $result = pclose($mail);
1634 if (0 !== $result) {
1635 throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1643 * Fix CVE-2016-10033 and CVE-2016-10045 by disallowing potentially unsafe shell characters.
1644 * Note that escapeshellarg and escapeshellcmd are inadequate for our purposes, especially on Windows.
1646 * @see https://github.com/PHPMailer/PHPMailer/issues/924 CVE-2016-10045 bug report
1648 * @param string $string The string to be validated
1652 protected static function isShellSafe($string)
1655 if (escapeshellcmd($string) !== $string
1656 or !in_array(escapeshellarg($string), ["'$string'", "\"$string\""])
1661 $length = strlen($string);
1663 for ($i = 0; $i < $length; ++$i) {
1666 // All other characters have a special meaning in at least one common shell, including = and +.
1667 // Full stop (.) has a special meaning in cmd.exe, but its impact should be negligible here.
1668 // Note that this does permit non-Latin alphanumeric characters based on the current locale.
1669 if (!ctype_alnum($c) && strpos('@_-.', $c) === false) {
1678 * Check whether a file path is of a permitted type.
1679 * Used to reject URLs and phar files from functions that access local file paths,
1680 * such as addAttachment.
1682 * @param string $path A relative or absolute path to a file
1686 protected static function isPermittedPath($path)
1688 return !preg_match('#^[a-z]+://#i', $path);
1692 * Send mail using the PHP mail() function.
1694 * @see http://www.php.net/manual/en/book.mail.php
1696 * @param string $header The message headers
1697 * @param string $body The message body
1703 protected function mailSend($header, $body)
1706 foreach ($this->to as $toaddr) {
1707 $toArr[] = $this->addrFormat($toaddr);
1709 $to = implode(', ', $toArr);
1712 //This sets the SMTP envelope sender which gets turned into a return-path header by the receiver
1713 if (!empty($this->Sender) and static::validateAddress($this->Sender)) {
1714 //A space after `-f` is optional, but there is a long history of its presence
1715 //causing problems, so we don't use one
1716 //Exim docs: http://www.exim.org/exim-html-current/doc/html/spec_html/ch-the_exim_command_line.html
1717 //Sendmail docs: http://www.sendmail.org/~ca/email/man/sendmail.html
1718 //Qmail docs: http://www.qmail.org/man/man8/qmail-inject.html
1719 //Example problem: https://www.drupal.org/node/1057954
1720 // CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped.
1721 if (self::isShellSafe($this->Sender)) {
1722 $params = sprintf('-f%s', $this->Sender);
1725 if (!empty($this->Sender) and static::validateAddress($this->Sender)) {
1726 $old_from = ini_get('sendmail_from');
1727 ini_set('sendmail_from', $this->Sender);
1730 if ($this->SingleTo and count($toArr) > 1) {
1731 foreach ($toArr as $toAddr) {
1732 $result = $this->mailPassthru($toAddr, $this->Subject, $body, $header, $params);
1733 $this->doCallback($result, [$toAddr], $this->cc, $this->bcc, $this->Subject, $body, $this->From, []);
1736 $result = $this->mailPassthru($to, $this->Subject, $body, $header, $params);
1737 $this->doCallback($result, $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From, []);
1739 if (isset($old_from)) {
1740 ini_set('sendmail_from', $old_from);
1743 throw new Exception($this->lang('instantiate'), self::STOP_CRITICAL);
1750 * Get an instance to use for SMTP operations.
1751 * Override this function to load your own SMTP implementation,
1752 * or set one with setSMTPInstance.
1756 public function getSMTPInstance()
1758 if (!is_object($this->smtp)) {
1759 $this->smtp = new SMTP();
1766 * Provide an instance to use for SMTP operations.
1772 public function setSMTPInstance(SMTP $smtp)
1774 $this->smtp = $smtp;
1780 * Send mail via SMTP.
1781 * Returns false if there is a bad MAIL FROM, RCPT, or DATA input.
1783 * @see PHPMailer::setSMTPInstance() to use a different class.
1785 * @uses \PHPMailer\PHPMailer\SMTP
1787 * @param string $header The message headers
1788 * @param string $body The message body
1794 protected function smtpSend($header, $body)
1797 if (!$this->smtpConnect($this->SMTPOptions)) {
1798 throw new Exception($this->lang('smtp_connect_failed'), self::STOP_CRITICAL);
1800 //Sender already validated in preSend()
1801 if ('' == $this->Sender) {
1802 $smtp_from = $this->From;
1804 $smtp_from = $this->Sender;
1806 if (!$this->smtp->mail($smtp_from)) {
1807 $this->setError($this->lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp->getError()));
1808 throw new Exception($this->ErrorInfo, self::STOP_CRITICAL);
1812 // Attempt to send to all recipients
1813 foreach ([$this->to, $this->cc, $this->bcc] as $togroup) {
1814 foreach ($togroup as $to) {
1815 if (!$this->smtp->recipient($to[0], $this->dsn)) {
1816 $error = $this->smtp->getError();
1817 $bad_rcpt[] = ['to' => $to[0], 'error' => $error['detail']];
1823 $callbacks[] = ['issent'=>$isSent, 'to'=>$to[0]];
1827 // Only send the DATA command if we have viable recipients
1828 if ((count($this->all_recipients) > count($bad_rcpt)) and !$this->smtp->data($header . $body)) {
1829 throw new Exception($this->lang('data_not_accepted'), self::STOP_CRITICAL);
1832 $smtp_transaction_id = $this->smtp->getLastTransactionID();
1834 if ($this->SMTPKeepAlive) {
1835 $this->smtp->reset();
1837 $this->smtp->quit();
1838 $this->smtp->close();
1841 foreach ($callbacks as $cb) {
1850 ['smtp_transaction_id' => $smtp_transaction_id]
1854 //Create error message for any bad addresses
1855 if (count($bad_rcpt) > 0) {
1857 foreach ($bad_rcpt as $bad) {
1858 $errstr .= $bad['to'] . ': ' . $bad['error'];
1860 throw new Exception(
1861 $this->lang('recipients_failed') . $errstr,
1870 * Initiate a connection to an SMTP server.
1871 * Returns false if the operation failed.
1873 * @param array $options An array of options compatible with stream_context_create()
1877 * @uses \PHPMailer\PHPMailer\SMTP
1881 public function smtpConnect($options = null)
1883 if (null === $this->smtp) {
1884 $this->smtp = $this->getSMTPInstance();
1887 //If no options are provided, use whatever is set in the instance
1888 if (null === $options) {
1889 $options = $this->SMTPOptions;
1892 // Already connected?
1893 if ($this->smtp->connected()) {
1897 $this->smtp->setTimeout($this->Timeout);
1898 $this->smtp->setDebugLevel($this->SMTPDebug);
1899 $this->smtp->setDebugOutput($this->Debugoutput);
1900 $this->smtp->setVerp($this->do_verp);
1901 $hosts = explode(';', $this->Host);
1902 $lastexception = null;
1904 foreach ($hosts as $hostentry) {
1907 '/^((ssl|tls):\/\/)*([a-zA-Z0-9\.-]*|\[[a-fA-F0-9:]+\]):?([0-9]*)$/',
1911 static::edebug($this->lang('connect_host') . ' ' . $hostentry);
1912 // Not a valid host entry
1915 // $hostinfo[2]: optional ssl or tls prefix
1916 // $hostinfo[3]: the hostname
1917 // $hostinfo[4]: optional port number
1918 // The host string prefix can temporarily override the current setting for SMTPSecure
1919 // If it's not specified, the default value is used
1921 //Check the host name is a valid name or IP address before trying to use it
1922 if (!static::isValidHost($hostinfo[3])) {
1923 static::edebug($this->lang('connect_host') . ' ' . $hostentry);
1927 $secure = $this->SMTPSecure;
1928 $tls = ('tls' == $this->SMTPSecure);
1929 if ('ssl' == $hostinfo[2] or ('' == $hostinfo[2] and 'ssl' == $this->SMTPSecure)) {
1931 $tls = false; // Can't have SSL and TLS at the same time
1933 } elseif ('tls' == $hostinfo[2]) {
1935 // tls doesn't use a prefix
1938 //Do we need the OpenSSL extension?
1939 $sslext = defined('OPENSSL_ALGO_SHA256');
1940 if ('tls' === $secure or 'ssl' === $secure) {
1941 //Check for an OpenSSL constant rather than using extension_loaded, which is sometimes disabled
1943 throw new Exception($this->lang('extension_missing') . 'openssl', self::STOP_CRITICAL);
1946 $host = $hostinfo[3];
1947 $port = $this->Port;
1948 $tport = (int) $hostinfo[4];
1949 if ($tport > 0 and $tport < 65536) {
1952 if ($this->smtp->connect($prefix . $host, $port, $this->Timeout, $options)) {
1955 $hello = $this->Helo;
1957 $hello = $this->serverHostname();
1959 $this->smtp->hello($hello);
1960 //Automatically enable TLS encryption if:
1961 // * it's not disabled
1962 // * we have openssl extension
1963 // * we are not already using SSL
1964 // * the server offers STARTTLS
1965 if ($this->SMTPAutoTLS and $sslext and 'ssl' != $secure and $this->smtp->getServerExt('STARTTLS')) {
1969 if (!$this->smtp->startTLS()) {
1970 throw new Exception($this->lang('connect_host'));
1972 // We must resend EHLO after TLS negotiation
1973 $this->smtp->hello($hello);
1975 if ($this->SMTPAuth) {
1976 if (!$this->smtp->authenticate(
1983 throw new Exception($this->lang('authenticate'));
1988 } catch (Exception $exc) {
1989 $lastexception = $exc;
1990 $this->edebug($exc->getMessage());
1991 // We must have connected, but then failed TLS or Auth, so close connection nicely
1992 $this->smtp->quit();
1996 // If we get here, all connection attempts have failed, so close connection hard
1997 $this->smtp->close();
1998 // As we've caught all exceptions, just report whatever the last one was
1999 if ($this->exceptions and null !== $lastexception) {
2000 throw $lastexception;
2007 * Close the active SMTP session if one exists.
2009 public function smtpClose()
2011 if (null !== $this->smtp) {
2012 if ($this->smtp->connected()) {
2013 $this->smtp->quit();
2014 $this->smtp->close();
2020 * Set the language for error messages.
2021 * Returns false if it cannot load the language file.
2022 * The default language is English.
2024 * @param string $langcode ISO 639-1 2-character language code (e.g. French is "fr")
2025 * @param string $lang_path Path to the language file directory, with trailing separator (slash)
2029 public function setLanguage($langcode = 'en', $lang_path = '')
2031 // Backwards compatibility for renamed language codes
2032 $renamed_langcodes = [
2042 if (isset($renamed_langcodes[$langcode])) {
2043 $langcode = $renamed_langcodes[$langcode];
2046 // Define full set of translatable strings in English
2048 'authenticate' => 'SMTP Error: Could not authenticate.',
2049 'connect_host' => 'SMTP Error: Could not connect to SMTP host.',
2050 'data_not_accepted' => 'SMTP Error: data not accepted.',
2051 'empty_message' => 'Message body empty',
2052 'encoding' => 'Unknown encoding: ',
2053 'execute' => 'Could not execute: ',
2054 'file_access' => 'Could not access file: ',
2055 'file_open' => 'File Error: Could not open file: ',
2056 'from_failed' => 'The following From address failed: ',
2057 'instantiate' => 'Could not instantiate mail function.',
2058 'invalid_address' => 'Invalid address: ',
2059 'mailer_not_supported' => ' mailer is not supported.',
2060 'provide_address' => 'You must provide at least one recipient email address.',
2061 'recipients_failed' => 'SMTP Error: The following recipients failed: ',
2062 'signing' => 'Signing Error: ',
2063 'smtp_connect_failed' => 'SMTP connect() failed.',
2064 'smtp_error' => 'SMTP server error: ',
2065 'variable_set' => 'Cannot set or reset variable: ',
2066 'extension_missing' => 'Extension missing: ',
2068 if (empty($lang_path)) {
2069 // Calculate an absolute path so it can work if CWD is not here
2070 $lang_path = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'language' . DIRECTORY_SEPARATOR;
2072 //Validate $langcode
2073 if (!preg_match('/^[a-z]{2}(?:_[a-zA-Z]{2})?$/', $langcode)) {
2077 $lang_file = $lang_path . 'phpmailer.lang-' . $langcode . '.php';
2078 // There is no English translation file
2079 if ('en' != $langcode) {
2080 // Make sure language file path is readable
2081 if (!static::isPermittedPath($lang_file) || !file_exists($lang_file)) {
2084 // Overwrite language-specific strings.
2085 // This way we'll never have missing translation keys.
2086 $foundlang = include $lang_file;
2089 $this->language = $PHPMAILER_LANG;
2091 return (bool) $foundlang; // Returns false if language not found
2095 * Get the array of strings for the current language.
2099 public function getTranslations()
2101 return $this->language;
2105 * Create recipient headers.
2107 * @param string $type
2108 * @param array $addr An array of recipients,
2109 * where each recipient is a 2-element indexed array with element 0 containing an address
2110 * and element 1 containing a name, like:
2111 * [['joe@example.com', 'Joe User'], ['zoe@example.com', 'Zoe User']]
2115 public function addrAppend($type, $addr)
2118 foreach ($addr as $address) {
2119 $addresses[] = $this->addrFormat($address);
2122 return $type . ': ' . implode(', ', $addresses) . static::$LE;
2126 * Format an address for use in a message header.
2128 * @param array $addr A 2-element indexed array, element 0 containing an address, element 1 containing a name like
2129 * ['joe@example.com', 'Joe User']
2133 public function addrFormat($addr)
2135 if (empty($addr[1])) { // No name provided
2136 return $this->secureHeader($addr[0]);
2139 return $this->encodeHeader($this->secureHeader($addr[1]), 'phrase') . ' <' . $this->secureHeader(
2145 * Word-wrap message.
2146 * For use with mailers that do not automatically perform wrapping
2147 * and for quoted-printable encoded messages.
2148 * Original written by philippe.
2150 * @param string $message The message to wrap
2151 * @param int $length The line length to wrap to
2152 * @param bool $qp_mode Whether to run in Quoted-Printable mode
2156 public function wrapText($message, $length, $qp_mode = false)
2159 $soft_break = sprintf(' =%s', static::$LE);
2161 $soft_break = static::$LE;
2163 // If utf-8 encoding is used, we will need to make sure we don't
2164 // split multibyte characters when we wrap
2165 $is_utf8 = static::CHARSET_UTF8 === strtolower($this->CharSet);
2166 $lelen = strlen(static::$LE);
2167 $crlflen = strlen(static::$LE);
2169 $message = static::normalizeBreaks($message);
2170 //Remove a trailing line break
2171 if (substr($message, -$lelen) == static::$LE) {
2172 $message = substr($message, 0, -$lelen);
2175 //Split message into lines
2176 $lines = explode(static::$LE, $message);
2177 //Message will be rebuilt in here
2179 foreach ($lines as $line) {
2180 $words = explode(' ', $line);
2183 foreach ($words as $word) {
2184 if ($qp_mode and (strlen($word) > $length)) {
2185 $space_left = $length - strlen($buf) - $crlflen;
2187 if ($space_left > 20) {
2190 $len = $this->utf8CharBoundary($word, $len);
2191 } elseif ('=' == substr($word, $len - 1, 1)) {
2193 } elseif ('=' == substr($word, $len - 2, 1)) {
2196 $part = substr($word, 0, $len);
2197 $word = substr($word, $len);
2198 $buf .= ' ' . $part;
2199 $message .= $buf . sprintf('=%s', static::$LE);
2201 $message .= $buf . $soft_break;
2205 while (strlen($word) > 0) {
2211 $len = $this->utf8CharBoundary($word, $len);
2212 } elseif ('=' == substr($word, $len - 1, 1)) {
2214 } elseif ('=' == substr($word, $len - 2, 1)) {
2217 $part = substr($word, 0, $len);
2218 $word = substr($word, $len);
2220 if (strlen($word) > 0) {
2221 $message .= $part . sprintf('=%s', static::$LE);
2233 if (strlen($buf) > $length and '' != $buf_o) {
2234 $message .= $buf_o . $soft_break;
2240 $message .= $buf . static::$LE;
2247 * Find the last character boundary prior to $maxLength in a utf-8
2248 * quoted-printable encoded string.
2249 * Original written by Colin Brown.
2251 * @param string $encodedText utf-8 QP text
2252 * @param int $maxLength Find the last character boundary prior to this length
2256 public function utf8CharBoundary($encodedText, $maxLength)
2258 $foundSplitPos = false;
2260 while (!$foundSplitPos) {
2261 $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
2262 $encodedCharPos = strpos($lastChunk, '=');
2263 if (false !== $encodedCharPos) {
2264 // Found start of encoded character byte within $lookBack block.
2265 // Check the encoded byte value (the 2 chars after the '=')
2266 $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
2267 $dec = hexdec($hex);
2269 // Single byte character.
2270 // If the encoded char was found at pos 0, it will fit
2271 // otherwise reduce maxLength to start of the encoded char
2272 if ($encodedCharPos > 0) {
2273 $maxLength -= $lookBack - $encodedCharPos;
2275 $foundSplitPos = true;
2276 } elseif ($dec >= 192) {
2277 // First byte of a multi byte character
2278 // Reduce maxLength to split at start of character
2279 $maxLength -= $lookBack - $encodedCharPos;
2280 $foundSplitPos = true;
2281 } elseif ($dec < 192) {
2282 // Middle byte of a multi byte character, look further back
2286 // No encoded character found
2287 $foundSplitPos = true;
2295 * Apply word wrapping to the message body.
2296 * Wraps the message body to the number of chars set in the WordWrap property.
2297 * You should only do this to plain-text bodies as wrapping HTML tags may break them.
2298 * This is called automatically by createBody(), so you don't need to call it yourself.
2300 public function setWordWrap()
2302 if ($this->WordWrap < 1) {
2306 switch ($this->message_type) {
2310 case 'alt_inline_attach':
2311 $this->AltBody = $this->wrapText($this->AltBody, $this->WordWrap);
2314 $this->Body = $this->wrapText($this->Body, $this->WordWrap);
2320 * Assemble message headers.
2322 * @return string The assembled headers
2324 public function createHeader()
2328 $result .= $this->headerLine('Date', '' == $this->MessageDate ? self::rfcDate() : $this->MessageDate);
2330 // To be created automatically by mail()
2331 if ($this->SingleTo) {
2332 if ('mail' != $this->Mailer) {
2333 foreach ($this->to as $toaddr) {
2334 $this->SingleToArray[] = $this->addrFormat($toaddr);
2338 if (count($this->to) > 0) {
2339 if ('mail' != $this->Mailer) {
2340 $result .= $this->addrAppend('To', $this->to);
2342 } elseif (count($this->cc) == 0) {
2343 $result .= $this->headerLine('To', 'undisclosed-recipients:;');
2347 $result .= $this->addrAppend('From', [[trim($this->From), $this->FromName]]);
2349 // sendmail and mail() extract Cc from the header before sending
2350 if (count($this->cc) > 0) {
2351 $result .= $this->addrAppend('Cc', $this->cc);
2354 // sendmail and mail() extract Bcc from the header before sending
2356 'sendmail' == $this->Mailer or 'qmail' == $this->Mailer or 'mail' == $this->Mailer
2358 and count($this->bcc) > 0
2360 $result .= $this->addrAppend('Bcc', $this->bcc);
2363 if (count($this->ReplyTo) > 0) {
2364 $result .= $this->addrAppend('Reply-To', $this->ReplyTo);
2367 // mail() sets the subject itself
2368 if ('mail' != $this->Mailer) {
2369 $result .= $this->headerLine('Subject', $this->encodeHeader($this->secureHeader($this->Subject)));
2372 // Only allow a custom message ID if it conforms to RFC 5322 section 3.6.4
2373 // https://tools.ietf.org/html/rfc5322#section-3.6.4
2374 if ('' != $this->MessageID and preg_match('/^<.*@.*>$/', $this->MessageID)) {
2375 $this->lastMessageID = $this->MessageID;
2377 $this->lastMessageID = sprintf('<%s@%s>', $this->uniqueid, $this->serverHostname());
2379 $result .= $this->headerLine('Message-ID', $this->lastMessageID);
2380 if (null !== $this->Priority) {
2381 $result .= $this->headerLine('X-Priority', $this->Priority);
2383 if ('' === $this->XMailer) {
2384 $result .= $this->headerLine(
2386 'PHPMailer ' . self::VERSION . ' (https://github.com/PHPMailer/PHPMailer)'
2389 $myXmailer = trim($this->XMailer);
2391 $result .= $this->headerLine('X-Mailer', $myXmailer);
2395 if ('' != $this->ConfirmReadingTo) {
2396 $result .= $this->headerLine('Disposition-Notification-To', '<' . $this->ConfirmReadingTo . '>');
2399 // Add custom headers
2400 foreach ($this->CustomHeader as $header) {
2401 $result .= $this->headerLine(
2403 $this->encodeHeader(trim($header[1]))
2406 if (!$this->sign_key_file) {
2407 $result .= $this->headerLine('MIME-Version', '1.0');
2408 $result .= $this->getMailMIME();
2415 * Get the message MIME type headers.
2419 public function getMailMIME()
2422 $ismultipart = true;
2423 switch ($this->message_type) {
2425 $result .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';');
2426 $result .= $this->textLine(' boundary="' . $this->boundary[1] . '"');
2429 case 'inline_attach':
2431 case 'alt_inline_attach':
2432 $result .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_MIXED . ';');
2433 $result .= $this->textLine(' boundary="' . $this->boundary[1] . '"');
2437 $result .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_ALTERNATIVE . ';');
2438 $result .= $this->textLine(' boundary="' . $this->boundary[1] . '"');
2441 // Catches case 'plain': and case '':
2442 $result .= $this->textLine('Content-Type: ' . $this->ContentType . '; charset=' . $this->CharSet);
2443 $ismultipart = false;
2446 // RFC1341 part 5 says 7bit is assumed if not specified
2447 if (static::ENCODING_7BIT != $this->Encoding) {
2448 // RFC 2045 section 6.4 says multipart MIME parts may only use 7bit, 8bit or binary CTE
2450 if (static::ENCODING_8BIT == $this->Encoding) {
2451 $result .= $this->headerLine('Content-Transfer-Encoding', static::ENCODING_8BIT);
2453 // The only remaining alternatives are quoted-printable and base64, which are both 7bit compatible
2455 $result .= $this->headerLine('Content-Transfer-Encoding', $this->Encoding);
2459 if ('mail' != $this->Mailer) {
2460 $result .= static::$LE;
2467 * Returns the whole MIME message.
2468 * Includes complete headers and body.
2469 * Only valid post preSend().
2471 * @see PHPMailer::preSend()
2475 public function getSentMIMEMessage()
2477 return rtrim($this->MIMEHeader . $this->mailHeader, "\n\r") . static::$LE . static::$LE . $this->MIMEBody;
2481 * Create a unique ID to use for boundaries.
2485 protected function generateId()
2487 $len = 32; //32 bytes = 256 bits
2488 if (function_exists('random_bytes')) {
2489 $bytes = random_bytes($len);
2490 } elseif (function_exists('openssl_random_pseudo_bytes')) {
2491 $bytes = openssl_random_pseudo_bytes($len);
2493 //Use a hash to force the length to the same as the other methods
2494 $bytes = hash('sha256', uniqid((string) mt_rand(), true), true);
2497 //We don't care about messing up base64 format here, just want a random string
2498 return str_replace(['=', '+', '/'], '', base64_encode(hash('sha256', $bytes, true)));
2502 * Assemble the message body.
2503 * Returns an empty string on failure.
2507 * @return string The assembled message body
2509 public function createBody()
2512 //Create unique IDs and preset boundaries
2513 $this->uniqueid = $this->generateId();
2514 $this->boundary[1] = 'b1_' . $this->uniqueid;
2515 $this->boundary[2] = 'b2_' . $this->uniqueid;
2516 $this->boundary[3] = 'b3_' . $this->uniqueid;
2518 if ($this->sign_key_file) {
2519 $body .= $this->getMailMIME() . static::$LE;
2522 $this->setWordWrap();
2524 $bodyEncoding = $this->Encoding;
2525 $bodyCharSet = $this->CharSet;
2526 //Can we do a 7-bit downgrade?
2527 if (static::ENCODING_8BIT == $bodyEncoding and !$this->has8bitChars($this->Body)) {
2528 $bodyEncoding = static::ENCODING_7BIT;
2529 //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit
2530 $bodyCharSet = 'us-ascii';
2532 //If lines are too long, and we're not already using an encoding that will shorten them,
2533 //change to quoted-printable transfer encoding for the body part only
2534 if (static::ENCODING_BASE64 != $this->Encoding and static::hasLineLongerThanMax($this->Body)) {
2535 $bodyEncoding = static::ENCODING_QUOTED_PRINTABLE;
2538 $altBodyEncoding = $this->Encoding;
2539 $altBodyCharSet = $this->CharSet;
2540 //Can we do a 7-bit downgrade?
2541 if (static::ENCODING_8BIT == $altBodyEncoding and !$this->has8bitChars($this->AltBody)) {
2542 $altBodyEncoding = static::ENCODING_7BIT;
2543 //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit
2544 $altBodyCharSet = 'us-ascii';
2546 //If lines are too long, and we're not already using an encoding that will shorten them,
2547 //change to quoted-printable transfer encoding for the alt body part only
2548 if (static::ENCODING_BASE64 != $altBodyEncoding and static::hasLineLongerThanMax($this->AltBody)) {
2549 $altBodyEncoding = static::ENCODING_QUOTED_PRINTABLE;
2551 //Use this as a preamble in all multipart message types
2552 $mimepre = 'This is a multi-part message in MIME format.' . static::$LE;
2553 switch ($this->message_type) {
2556 $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
2557 $body .= $this->encodeString($this->Body, $bodyEncoding);
2558 $body .= static::$LE;
2559 $body .= $this->attachAll('inline', $this->boundary[1]);
2563 $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
2564 $body .= $this->encodeString($this->Body, $bodyEncoding);
2565 $body .= static::$LE;
2566 $body .= $this->attachAll('attachment', $this->boundary[1]);
2568 case 'inline_attach':
2570 $body .= $this->textLine('--' . $this->boundary[1]);
2571 $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';');
2572 $body .= $this->textLine(' boundary="' . $this->boundary[2] . '";');
2573 $body .= $this->textLine(' type="' . static::CONTENT_TYPE_TEXT_HTML . '"');
2574 $body .= static::$LE;
2575 $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, '', $bodyEncoding);
2576 $body .= $this->encodeString($this->Body, $bodyEncoding);
2577 $body .= static::$LE;
2578 $body .= $this->attachAll('inline', $this->boundary[2]);
2579 $body .= static::$LE;
2580 $body .= $this->attachAll('attachment', $this->boundary[1]);
2584 $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, static::CONTENT_TYPE_PLAINTEXT, $altBodyEncoding);
2585 $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
2586 $body .= static::$LE;
2587 $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, static::CONTENT_TYPE_TEXT_HTML, $bodyEncoding);
2588 $body .= $this->encodeString($this->Body, $bodyEncoding);
2589 $body .= static::$LE;
2590 if (!empty($this->Ical)) {
2591 $body .= $this->getBoundary($this->boundary[1], '', static::CONTENT_TYPE_TEXT_CALENDAR . '; method=REQUEST', '');
2592 $body .= $this->encodeString($this->Ical, $this->Encoding);
2593 $body .= static::$LE;
2595 $body .= $this->endBoundary($this->boundary[1]);
2599 $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, static::CONTENT_TYPE_PLAINTEXT, $altBodyEncoding);
2600 $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
2601 $body .= static::$LE;
2602 $body .= $this->textLine('--' . $this->boundary[1]);
2603 $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';');
2604 $body .= $this->textLine(' boundary="' . $this->boundary[2] . '";');
2605 $body .= $this->textLine(' type="' . static::CONTENT_TYPE_TEXT_HTML . '"');
2606 $body .= static::$LE;
2607 $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, static::CONTENT_TYPE_TEXT_HTML, $bodyEncoding);
2608 $body .= $this->encodeString($this->Body, $bodyEncoding);
2609 $body .= static::$LE;
2610 $body .= $this->attachAll('inline', $this->boundary[2]);
2611 $body .= static::$LE;
2612 $body .= $this->endBoundary($this->boundary[1]);
2616 $body .= $this->textLine('--' . $this->boundary[1]);
2617 $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_ALTERNATIVE . ';');
2618 $body .= $this->textLine(' boundary="' . $this->boundary[2] . '"');
2619 $body .= static::$LE;
2620 $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, static::CONTENT_TYPE_PLAINTEXT, $altBodyEncoding);
2621 $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
2622 $body .= static::$LE;
2623 $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, static::CONTENT_TYPE_TEXT_HTML, $bodyEncoding);
2624 $body .= $this->encodeString($this->Body, $bodyEncoding);
2625 $body .= static::$LE;
2626 if (!empty($this->Ical)) {
2627 $body .= $this->getBoundary($this->boundary[2], '', static::CONTENT_TYPE_TEXT_CALENDAR . '; method=REQUEST', '');
2628 $body .= $this->encodeString($this->Ical, $this->Encoding);
2630 $body .= $this->endBoundary($this->boundary[2]);
2631 $body .= static::$LE;
2632 $body .= $this->attachAll('attachment', $this->boundary[1]);
2634 case 'alt_inline_attach':
2636 $body .= $this->textLine('--' . $this->boundary[1]);
2637 $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_ALTERNATIVE . ';');
2638 $body .= $this->textLine(' boundary="' . $this->boundary[2] . '"');
2639 $body .= static::$LE;
2640 $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, static::CONTENT_TYPE_PLAINTEXT, $altBodyEncoding);
2641 $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
2642 $body .= static::$LE;
2643 $body .= $this->textLine('--' . $this->boundary[2]);
2644 $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';');
2645 $body .= $this->textLine(' boundary="' . $this->boundary[3] . '";');
2646 $body .= $this->textLine(' type="' . static::CONTENT_TYPE_TEXT_HTML . '"');
2647 $body .= static::$LE;
2648 $body .= $this->getBoundary($this->boundary[3], $bodyCharSet, static::CONTENT_TYPE_TEXT_HTML, $bodyEncoding);
2649 $body .= $this->encodeString($this->Body, $bodyEncoding);
2650 $body .= static::$LE;
2651 $body .= $this->attachAll('inline', $this->boundary[3]);
2652 $body .= static::$LE;
2653 $body .= $this->endBoundary($this->boundary[2]);
2654 $body .= static::$LE;
2655 $body .= $this->attachAll('attachment', $this->boundary[1]);
2658 // Catch case 'plain' and case '', applies to simple `text/plain` and `text/html` body content types
2659 //Reset the `Encoding` property in case we changed it for line length reasons
2660 $this->Encoding = $bodyEncoding;
2661 $body .= $this->encodeString($this->Body, $this->Encoding);
2665 if ($this->isError()) {
2667 if ($this->exceptions) {
2668 throw new Exception($this->lang('empty_message'), self::STOP_CRITICAL);
2670 } elseif ($this->sign_key_file) {
2672 if (!defined('PKCS7_TEXT')) {
2673 throw new Exception($this->lang('extension_missing') . 'openssl');
2675 $file = fopen('php://temp', 'rb+');
2676 $signed = fopen('php://temp', 'rb+');
2677 fwrite($file, $body);
2679 //Workaround for PHP bug https://bugs.php.net/bug.php?id=69197
2680 if (empty($this->sign_extracerts_file)) {
2681 $sign = @openssl_pkcs7_sign(
2684 'file://' . realpath($this->sign_cert_file),
2685 ['file://' . realpath($this->sign_key_file), $this->sign_key_pass],
2689 $sign = @openssl_pkcs7_sign(
2692 'file://' . realpath($this->sign_cert_file),
2693 ['file://' . realpath($this->sign_key_file), $this->sign_key_pass],
2696 $this->sign_extracerts_file
2701 $body = file_get_contents($signed);
2703 //The message returned by openssl contains both headers and body, so need to split them up
2704 $parts = explode("\n\n", $body, 2);
2705 $this->MIMEHeader .= $parts[0] . static::$LE . static::$LE;
2709 throw new Exception($this->lang('signing') . openssl_error_string());
2711 } catch (Exception $exc) {
2713 if ($this->exceptions) {
2723 * Return the start of a message boundary.
2725 * @param string $boundary
2726 * @param string $charSet
2727 * @param string $contentType
2728 * @param string $encoding
2732 protected function getBoundary($boundary, $charSet, $contentType, $encoding)
2735 if ('' == $charSet) {
2736 $charSet = $this->CharSet;
2738 if ('' == $contentType) {
2739 $contentType = $this->ContentType;
2741 if ('' == $encoding) {
2742 $encoding = $this->Encoding;
2744 $result .= $this->textLine('--' . $boundary);
2745 $result .= sprintf('Content-Type: %s; charset=%s', $contentType, $charSet);
2746 $result .= static::$LE;
2747 // RFC1341 part 5 says 7bit is assumed if not specified
2748 if (static::ENCODING_7BIT != $encoding) {
2749 $result .= $this->headerLine('Content-Transfer-Encoding', $encoding);
2751 $result .= static::$LE;
2757 * Return the end of a message boundary.
2759 * @param string $boundary
2763 protected function endBoundary($boundary)
2765 return static::$LE . '--' . $boundary . '--' . static::$LE;
2769 * Set the message type.
2770 * PHPMailer only supports some preset message types, not arbitrary MIME structures.
2772 protected function setMessageType()
2775 if ($this->alternativeExists()) {
2778 if ($this->inlineImageExists()) {
2781 if ($this->attachmentExists()) {
2784 $this->message_type = implode('_', $type);
2785 if ('' == $this->message_type) {
2786 //The 'plain' message_type refers to the message having a single body element, not that it is plain-text
2787 $this->message_type = 'plain';
2792 * Format a header line.
2794 * @param string $name
2795 * @param string|int $value
2799 public function headerLine($name, $value)
2801 return $name . ': ' . $value . static::$LE;
2805 * Return a formatted mail line.
2807 * @param string $value
2811 public function textLine($value)
2813 return $value . static::$LE;
2817 * Add an attachment from a path on the filesystem.
2818 * Never use a user-supplied path to a file!
2819 * Returns false if the file could not be found or read.
2820 * Explicitly *does not* support passing URLs; PHPMailer is not an HTTP client.
2821 * If you need to do that, fetch the resource yourself and pass it in via a local file or string.
2823 * @param string $path Path to the attachment
2824 * @param string $name Overrides the attachment name
2825 * @param string $encoding File encoding (see $Encoding)
2826 * @param string $type File extension (MIME) type
2827 * @param string $disposition Disposition to use
2833 public function addAttachment(
2836 $encoding = self::ENCODING_BASE64,
2838 $disposition = 'attachment'
2841 if (!static::isPermittedPath($path) || !@is_file($path)) {
2842 throw new Exception($this->lang('file_access') . $path, self::STOP_CONTINUE);
2845 // If a MIME type is not specified, try to work it out from the file name
2847 $type = static::filenameToType($path);
2850 $filename = static::mb_pathinfo($path, PATHINFO_BASENAME);
2855 if (!$this->validateEncoding($encoding)) {
2856 throw new Exception($this->lang('encoding') . $encoding);
2859 $this->attachment[] = [
2865 5 => false, // isStringAttachment
2869 } catch (Exception $exc) {
2870 $this->setError($exc->getMessage());
2871 $this->edebug($exc->getMessage());
2872 if ($this->exceptions) {
2883 * Return the array of attachments.
2887 public function getAttachments()
2889 return $this->attachment;
2893 * Attach all file, string, and binary attachments to the message.
2894 * Returns an empty string on failure.
2896 * @param string $disposition_type
2897 * @param string $boundary
2901 protected function attachAll($disposition_type, $boundary)
2903 // Return text of body
2908 // Add all attachments
2909 foreach ($this->attachment as $attachment) {
2910 // Check if it is a valid disposition_filter
2911 if ($attachment[6] == $disposition_type) {
2912 // Check for string attachment
2915 $bString = $attachment[5];
2917 $string = $attachment[0];
2919 $path = $attachment[0];
2922 $inclhash = hash('sha256', serialize($attachment));
2923 if (in_array($inclhash, $incl)) {
2926 $incl[] = $inclhash;
2927 $name = $attachment[2];
2928 $encoding = $attachment[3];
2929 $type = $attachment[4];
2930 $disposition = $attachment[6];
2931 $cid = $attachment[7];
2932 if ('inline' == $disposition and array_key_exists($cid, $cidUniq)) {
2935 $cidUniq[$cid] = true;
2937 $mime[] = sprintf('--%s%s', $boundary, static::$LE);
2938 //Only include a filename property if we have one
2939 if (!empty($name)) {
2941 'Content-Type: %s; name="%s"%s',
2943 $this->encodeHeader($this->secureHeader($name)),
2948 'Content-Type: %s%s',
2953 // RFC1341 part 5 says 7bit is assumed if not specified
2954 if (static::ENCODING_7BIT != $encoding) {
2955 $mime[] = sprintf('Content-Transfer-Encoding: %s%s', $encoding, static::$LE);
2960 'Content-ID: <%s>%s',
2961 $this->encodeHeader($this->secureHeader($cid)),
2966 // If a filename contains any of these chars, it should be quoted,
2967 // but not otherwise: RFC2183 & RFC2045 5.1
2968 // Fixes a warning in IETF's msglint MIME checker
2969 // Allow for bypassing the Content-Disposition header totally
2970 if (!empty($disposition)) {
2971 $encoded_name = $this->encodeHeader($this->secureHeader($name));
2972 if (preg_match('/[ \(\)<>@,;:\\"\/\[\]\?=]/', $encoded_name)) {
2974 'Content-Disposition: %s; filename="%s"%s',
2977 static::$LE . static::$LE
2980 if (!empty($encoded_name)) {
2982 'Content-Disposition: %s; filename=%s%s',
2985 static::$LE . static::$LE
2989 'Content-Disposition: %s%s',
2991 static::$LE . static::$LE
2996 $mime[] = static::$LE;
2999 // Encode as string attachment
3001 $mime[] = $this->encodeString($string, $encoding);
3003 $mime[] = $this->encodeFile($path, $encoding);
3005 if ($this->isError()) {
3008 $mime[] = static::$LE;
3012 $mime[] = sprintf('--%s--%s', $boundary, static::$LE);
3014 return implode('', $mime);
3018 * Encode a file attachment in requested format.
3019 * Returns an empty string on failure.
3021 * @param string $path The full path to the file
3022 * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
3028 protected function encodeFile($path, $encoding = self::ENCODING_BASE64)
3031 if (!static::isPermittedPath($path) || !file_exists($path)) {
3032 throw new Exception($this->lang('file_open') . $path, self::STOP_CONTINUE);
3034 $file_buffer = file_get_contents($path);
3035 if (false === $file_buffer) {
3036 throw new Exception($this->lang('file_open') . $path, self::STOP_CONTINUE);
3038 $file_buffer = $this->encodeString($file_buffer, $encoding);
3040 return $file_buffer;
3041 } catch (Exception $exc) {
3042 $this->setError($exc->getMessage());
3049 * Encode a string in requested format.
3050 * Returns an empty string on failure.
3052 * @param string $str The text to encode
3053 * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
3059 public function encodeString($str, $encoding = self::ENCODING_BASE64)
3062 switch (strtolower($encoding)) {
3063 case static::ENCODING_BASE64:
3064 $encoded = chunk_split(
3065 base64_encode($str),
3066 static::STD_LINE_LENGTH,
3070 case static::ENCODING_7BIT:
3071 case static::ENCODING_8BIT:
3072 $encoded = static::normalizeBreaks($str);
3073 // Make sure it ends with a line break
3074 if (substr($encoded, -(strlen(static::$LE))) != static::$LE) {
3075 $encoded .= static::$LE;
3078 case static::ENCODING_BINARY:
3081 case static::ENCODING_QUOTED_PRINTABLE:
3082 $encoded = $this->encodeQP($str);
3085 $this->setError($this->lang('encoding') . $encoding);
3086 if ($this->exceptions) {
3087 throw new Exception($this->lang('encoding') . $encoding);
3096 * Encode a header value (not including its label) optimally.
3097 * Picks shortest of Q, B, or none. Result includes folding if needed.
3098 * See RFC822 definitions for phrase, comment and text positions.
3100 * @param string $str The header value to encode
3101 * @param string $position What context the string will be used in
3105 public function encodeHeader($str, $position = 'text')
3108 switch (strtolower($position)) {
3110 if (!preg_match('/[\200-\377]/', $str)) {
3111 // Can't use addslashes as we don't know the value of magic_quotes_sybase
3112 $encoded = addcslashes($str, "\0..\37\177\\\"");
3113 if (($str == $encoded) and !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
3117 return "\"$encoded\"";
3119 $matchcount = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
3121 /* @noinspection PhpMissingBreakStatementInspection */
3123 $matchcount = preg_match_all('/[()"]/', $str, $matches);
3127 $matchcount += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
3131 //RFCs specify a maximum line length of 78 chars, however mail() will sometimes
3132 //corrupt messages with headers longer than 65 chars. See #818
3133 $lengthsub = 'mail' == $this->Mailer ? 13 : 0;
3134 $maxlen = static::STD_LINE_LENGTH - $lengthsub;
3135 // Try to select the encoding which should produce the shortest output
3136 if ($matchcount > strlen($str) / 3) {
3137 // More than a third of the content will need encoding, so B encoding will be most efficient
3139 //This calculation is:
3141 // - shorten to avoid mail() corruption
3142 // - Q/B encoding char overhead ("` =?<charset>?[QB]?<content>?=`")
3143 // - charset name length
3144 $maxlen = static::STD_LINE_LENGTH - $lengthsub - 8 - strlen($this->CharSet);
3145 if ($this->hasMultiBytes($str)) {
3146 // Use a custom function which correctly encodes and wraps long
3147 // multibyte strings without breaking lines within a character
3148 $encoded = $this->base64EncodeWrapMB($str, "\n");
3150 $encoded = base64_encode($str);
3151 $maxlen -= $maxlen % 4;
3152 $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
3154 $encoded = preg_replace('/^(.*)$/m', ' =?' . $this->CharSet . "?$encoding?\\1?=", $encoded);
3155 } elseif ($matchcount > 0) {
3156 //1 or more chars need encoding, use Q-encode
3158 //Recalc max line length for Q encoding - see comments on B encode
3159 $maxlen = static::STD_LINE_LENGTH - $lengthsub - 8 - strlen($this->CharSet);
3160 $encoded = $this->encodeQ($str, $position);
3161 $encoded = $this->wrapText($encoded, $maxlen, true);
3162 $encoded = str_replace('=' . static::$LE, "\n", trim($encoded));
3163 $encoded = preg_replace('/^(.*)$/m', ' =?' . $this->CharSet . "?$encoding?\\1?=", $encoded);
3164 } elseif (strlen($str) > $maxlen) {
3165 //No chars need encoding, but line is too long, so fold it
3166 $encoded = trim($this->wrapText($str, $maxlen, false));
3167 if ($str == $encoded) {
3168 //Wrapping nicely didn't work, wrap hard instead
3169 $encoded = trim(chunk_split($str, static::STD_LINE_LENGTH, static::$LE));
3171 $encoded = str_replace(static::$LE, "\n", trim($encoded));
3172 $encoded = preg_replace('/^(.*)$/m', ' \\1', $encoded);
3174 //No reformatting needed
3178 return trim(static::normalizeBreaks($encoded));
3182 * Check if a string contains multi-byte characters.
3184 * @param string $str multi-byte text to wrap encode
3188 public function hasMultiBytes($str)
3190 if (function_exists('mb_strlen')) {
3191 return strlen($str) > mb_strlen($str, $this->CharSet);
3194 // Assume no multibytes (we can't handle without mbstring functions anyway)
3199 * Does a string contain any 8-bit chars (in any charset)?
3201 * @param string $text
3205 public function has8bitChars($text)
3207 return (bool) preg_match('/[\x80-\xFF]/', $text);
3211 * Encode and wrap long multibyte strings for mail headers
3212 * without breaking lines within a character.
3213 * Adapted from a function by paravoid.
3215 * @see http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283
3217 * @param string $str multi-byte text to wrap encode
3218 * @param string $linebreak string to use as linefeed/end-of-line
3222 public function base64EncodeWrapMB($str, $linebreak = null)
3224 $start = '=?' . $this->CharSet . '?B?';
3227 if (null === $linebreak) {
3228 $linebreak = static::$LE;
3231 $mb_length = mb_strlen($str, $this->CharSet);
3232 // Each line must have length <= 75, including $start and $end
3233 $length = 75 - strlen($start) - strlen($end);
3234 // Average multi-byte ratio
3235 $ratio = $mb_length / strlen($str);
3236 // Base64 has a 4:3 ratio
3237 $avgLength = floor($length * $ratio * .75);
3239 for ($i = 0; $i < $mb_length; $i += $offset) {
3242 $offset = $avgLength - $lookBack;
3243 $chunk = mb_substr($str, $i, $offset, $this->CharSet);
3244 $chunk = base64_encode($chunk);
3246 } while (strlen($chunk) > $length);
3247 $encoded .= $chunk . $linebreak;
3250 // Chomp the last linefeed
3251 return substr($encoded, 0, -strlen($linebreak));
3255 * Encode a string in quoted-printable format.
3256 * According to RFC2045 section 6.7.
3258 * @param string $string The text to encode
3262 public function encodeQP($string)
3264 return static::normalizeBreaks(quoted_printable_encode($string));
3268 * Encode a string using Q encoding.
3270 * @see http://tools.ietf.org/html/rfc2047#section-4.2
3272 * @param string $str the text to encode
3273 * @param string $position Where the text is going to be used, see the RFC for what that means
3277 public function encodeQ($str, $position = 'text')
3279 // There should not be any EOL in the string
3281 $encoded = str_replace(["\r", "\n"], '', $str);
3282 switch (strtolower($position)) {
3284 // RFC 2047 section 5.3
3285 $pattern = '^A-Za-z0-9!*+\/ -';
3288 * RFC 2047 section 5.2.
3289 * Build $pattern without including delimiters and []
3291 /* @noinspection PhpMissingBreakStatementInspection */
3294 /* Intentional fall through */
3297 // RFC 2047 section 5.1
3298 // Replace every high ascii, control, =, ? and _ characters
3299 /** @noinspection SuspiciousAssignmentsInspection */
3300 $pattern = '\000-\011\013\014\016-\037\075\077\137\177-\377' . $pattern;
3304 if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) {
3305 // If the string contains an '=', make sure it's the first thing we replace
3306 // so as to avoid double-encoding
3307 $eqkey = array_search('=', $matches[0]);
3308 if (false !== $eqkey) {
3309 unset($matches[0][$eqkey]);
3310 array_unshift($matches[0], '=');
3312 foreach (array_unique($matches[0]) as $char) {
3313 $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded);
3316 // Replace spaces with _ (more readable than =20)
3317 // RFC 2047 section 4.2(2)
3318 return str_replace(' ', '_', $encoded);
3322 * Add a string or binary attachment (non-filesystem).
3323 * This method can be used to attach ascii or binary data,
3324 * such as a BLOB record from a database.
3326 * @param string $string String attachment data