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)
35 * Options: null (default), 1 = High, 3 = Normal, 5 = low.
36 * When null, the header is not set at all.
43 * The character set of the message.
47 public $CharSet = 'iso-8859-1';
50 * The MIME Content-type of the message.
54 public $ContentType = 'text/plain';
57 * The message encoding.
58 * Options: "8bit", "7bit", "binary", "base64", and "quoted-printable".
62 public $Encoding = '8bit';
65 * Holds the most recent mailer error message.
69 public $ErrorInfo = '';
72 * The From email address for the message.
76 public $From = 'root@localhost';
79 * The From name of the message.
83 public $FromName = 'Root User';
86 * The envelope sender of the message.
87 * This will usually be turned into a Return-Path header by the receiver,
88 * and is the address that bounces will be sent to.
89 * If not empty, will be passed via `-f` to sendmail or as the 'MAIL FROM' value over SMTP.
96 * The Subject of the message.
100 public $Subject = '';
103 * An HTML or plain text message body.
104 * If HTML then call isHTML(true).
111 * The plain-text message body.
112 * This body can be read by mail clients that do not have HTML email
113 * capability such as mutt & Eudora.
114 * Clients that can read HTML will view the normal Body.
118 public $AltBody = '';
121 * An iCal message part body.
122 * Only supported in simple alt or alt_inline message types
123 * To generate iCal event structures, use classes like EasyPeasyICS or iCalcreator.
125 * @see http://sprain.ch/blog/downloads/php-class-easypeasyics-create-ical-files-with-php/
126 * @see http://kigkonsult.se/iCalcreator/
133 * The complete compiled MIME message body.
137 protected $MIMEBody = '';
140 * The complete compiled MIME message headers.
144 protected $MIMEHeader = '';
147 * Extra headers that createHeader() doesn't fold in.
151 protected $mailHeader = '';
154 * Word-wrap the message body to this number of chars.
155 * Set to 0 to not wrap. A useful value here is 78, for RFC2822 section 2.1.1 compliance.
157 * @see static::STD_LINE_LENGTH
161 public $WordWrap = 0;
164 * Which method to use to send mail.
165 * Options: "mail", "sendmail", or "smtp".
169 public $Mailer = 'mail';
172 * The path to the sendmail program.
176 public $Sendmail = '/usr/sbin/sendmail';
179 * Whether mail() uses a fully sendmail-compatible MTA.
180 * One which supports sendmail's "-oi -f" options.
184 public $UseSendmailOptions = true;
187 * The email address that a reading confirmation should be sent to, also known as read receipt.
191 public $ConfirmReadingTo = '';
194 * The hostname to use in the Message-ID header and as default HELO string.
195 * If empty, PHPMailer attempts to find one with, in order,
196 * $_SERVER['SERVER_NAME'], gethostname(), php_uname('n'), or the value
197 * 'localhost.localdomain'.
201 public $Hostname = '';
204 * An ID to be used in the Message-ID header.
205 * If empty, a unique id will be generated.
206 * You can set your own, but it must be in the format "<id@domain>",
207 * as defined in RFC5322 section 3.6.4 or it will be ignored.
209 * @see https://tools.ietf.org/html/rfc5322#section-3.6.4
213 public $MessageID = '';
216 * The message Date to be used in the Date header.
217 * If empty, the current date will be added.
221 public $MessageDate = '';
225 * Either a single hostname or multiple semicolon-delimited hostnames.
226 * You can also specify a different port
227 * for each host by using this format: [hostname:port]
228 * (e.g. "smtp1.example.com:25;smtp2.example.com").
229 * You can also specify encryption type, for example:
230 * (e.g. "tls://smtp1.example.com:587;ssl://smtp2.example.com:465").
231 * Hosts will be tried in order.
235 public $Host = 'localhost';
238 * The default SMTP server port.
245 * The SMTP HELO of the message.
246 * Default is $Hostname. If $Hostname is empty, PHPMailer attempts to find
247 * one with the same method described above for $Hostname.
249 * @see PHPMailer::$Hostname
256 * What kind of encryption to use on the SMTP connection.
257 * Options: '', 'ssl' or 'tls'.
261 public $SMTPSecure = '';
264 * Whether to enable TLS encryption automatically if a server supports it,
265 * even if `SMTPSecure` is not set to 'tls'.
266 * Be aware that in PHP >= 5.6 this requires that the server's certificates are valid.
270 public $SMTPAutoTLS = true;
273 * Whether to use SMTP authentication.
274 * Uses the Username and Password properties.
276 * @see PHPMailer::$Username
277 * @see PHPMailer::$Password
281 public $SMTPAuth = false;
284 * Options array passed to stream_context_create when connecting via SMTP.
288 public $SMTPOptions = [];
295 public $Username = '';
302 public $Password = '';
306 * Options are CRAM-MD5, LOGIN, PLAIN, XOAUTH2, attempted in that order if not specified.
310 public $AuthType = '';
313 * An instance of the PHPMailer OAuth class.
320 * The SMTP server timeout in seconds.
321 * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2.
325 public $Timeout = 300;
328 * SMTP class debug output mode.
329 * Debug output level.
333 * * `2` Data and commands
334 * * `3` As 2 plus connection status
335 * * `4` Low-level data output.
337 * @see SMTP::$do_debug
341 public $SMTPDebug = 0;
344 * How to handle debug output.
346 * * `echo` Output plain-text as-is, appropriate for CLI
347 * * `html` Output escaped, line breaks converted to `<br>`, appropriate for browser output
348 * * `error_log` Output to error log as configured in php.ini
349 * By default PHPMailer will use `echo` if run from a `cli` or `cli-server` SAPI, `html` otherwise.
350 * Alternatively, you can provide a callable expecting two params: a message string and the debug level:
353 * $mail->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";};
356 * Alternatively, you can pass in an instance of a PSR-3 compatible logger, though only `debug`
357 * level output is used:
360 * $mail->Debugoutput = new myPsr3Logger;
363 * @see SMTP::$Debugoutput
365 * @var string|callable|\Psr\Log\LoggerInterface
367 public $Debugoutput = 'echo';
370 * Whether to keep SMTP connection open after each message.
371 * If this is set to true then to close the connection
372 * requires an explicit call to smtpClose().
376 public $SMTPKeepAlive = false;
379 * Whether to split multiple to addresses into multiple messages
380 * or send them all in one message.
381 * Only supported in `mail` and `sendmail` transports, not in SMTP.
385 public $SingleTo = false;
388 * Storage for addresses when SingleTo is enabled.
392 protected $SingleToArray = [];
395 * Whether to generate VERP addresses on send.
396 * Only applicable when sending via SMTP.
398 * @see https://en.wikipedia.org/wiki/Variable_envelope_return_path
399 * @see http://www.postfix.org/VERP_README.html Postfix VERP info
403 public $do_verp = false;
406 * Whether to allow sending messages with an empty body.
410 public $AllowEmpty = false;
417 public $DKIM_selector = '';
421 * Usually the email address used as the source of the email.
425 public $DKIM_identity = '';
429 * Used if your key is encrypted.
433 public $DKIM_passphrase = '';
436 * DKIM signing domain name.
438 * @example 'example.com'
442 public $DKIM_domain = '';
445 * DKIM private key file path.
449 public $DKIM_private = '';
452 * DKIM private key string.
454 * If set, takes precedence over `$DKIM_private`.
458 public $DKIM_private_string = '';
461 * Callback Action function name.
463 * The function that handles the result of the send email action.
464 * It is called out by send() for each email sent.
466 * Value can be any php callable: http://www.php.net/is_callable
469 * bool $result result of the send action
470 * array $to email addresses of the recipients
471 * array $cc cc email addresses
472 * array $bcc bcc email addresses
473 * string $subject the subject
474 * string $body the email body
475 * string $from email address of sender
476 * string $extra extra information of possible use
477 * "smtp_transaction_id' => last smtp transaction id
481 public $action_function = '';
484 * What to put in the X-Mailer header.
485 * Options: An empty string for PHPMailer default, whitespace for none, or a string to use.
489 public $XMailer = '';
492 * Which validator to use by default when validating email addresses.
493 * May be a callable to inject your own validator, but there are several built-in validators.
494 * The default validator uses PHP's FILTER_VALIDATE_EMAIL filter_var option.
496 * @see PHPMailer::validateAddress()
498 * @var string|callable
500 public static $validator = 'php';
503 * An instance of the SMTP sender class.
510 * The array of 'to' names and addresses.
517 * The array of 'cc' names and addresses.
524 * The array of 'bcc' names and addresses.
531 * The array of reply-to names and addresses.
535 protected $ReplyTo = [];
538 * An array of all kinds of addresses.
539 * Includes all of $to, $cc, $bcc.
541 * @see PHPMailer::$to
542 * @see PHPMailer::$cc
543 * @see PHPMailer::$bcc
547 protected $all_recipients = [];
550 * An array of names and addresses queued for validation.
551 * In send(), valid and non duplicate entries are moved to $all_recipients
552 * and one of $to, $cc, or $bcc.
553 * This array is used only for addresses with IDN.
555 * @see PHPMailer::$to
556 * @see PHPMailer::$cc
557 * @see PHPMailer::$bcc
558 * @see PHPMailer::$all_recipients
562 protected $RecipientsQueue = [];
565 * An array of reply-to names and addresses queued for validation.
566 * In send(), valid and non duplicate entries are moved to $ReplyTo.
567 * This array is used only for addresses with IDN.
569 * @see PHPMailer::$ReplyTo
573 protected $ReplyToQueue = [];
576 * The array of attachments.
580 protected $attachment = [];
583 * The array of custom headers.
587 protected $CustomHeader = [];
590 * The most recent Message-ID (including angular brackets).
594 protected $lastMessageID = '';
597 * The message's MIME type.
601 protected $message_type = '';
604 * The array of MIME boundary strings.
608 protected $boundary = [];
611 * The array of available languages.
615 protected $language = [];
618 * The number of errors encountered.
622 protected $error_count = 0;
625 * The S/MIME certificate file path.
629 protected $sign_cert_file = '';
632 * The S/MIME key file path.
636 protected $sign_key_file = '';
639 * The optional S/MIME extra certificates ("CA Chain") file path.
643 protected $sign_extracerts_file = '';
646 * The S/MIME password for the key.
647 * Used only if the key is encrypted.
651 protected $sign_key_pass = '';
654 * Whether to throw exceptions for errors.
658 protected $exceptions = false;
661 * Unique ID used for message ID and boundaries.
665 protected $uniqueid = '';
668 * The PHPMailer Version number.
672 const VERSION
= '6.0.5';
675 * Error severity: message only, continue processing.
679 const STOP_MESSAGE
= 0;
682 * Error severity: message, likely ok to continue processing.
686 const STOP_CONTINUE
= 1;
689 * Error severity: message, plus full stop, critical error reached.
693 const STOP_CRITICAL
= 2;
696 * SMTP RFC standard line ending.
700 protected static $LE = "\r\n";
703 * The maximum line length allowed by RFC 2822 section 2.1.1.
707 const MAX_LINE_LENGTH
= 998;
710 * The lower maximum line length allowed by RFC 2822 section 2.1.1.
711 * This length does NOT include the line break
712 * 76 means that lines will be 77 or 78 chars depending on whether
713 * the line break format is LF or CRLF; both are valid.
717 const STD_LINE_LENGTH
= 76;
722 * @param bool $exceptions Should we throw external exceptions?
724 public function __construct($exceptions = null)
726 if (null !== $exceptions) {
727 $this->exceptions
= (bool) $exceptions;
729 //Pick an appropriate debug output format automatically
730 $this->Debugoutput
= (strpos(PHP_SAPI
, 'cli') !== false ?
'echo' : 'html');
736 public function __destruct()
738 //Close any open SMTP connection nicely
743 * Call mail() in a safe_mode-aware fashion.
744 * Also, unless sendmail_path points to sendmail (or something that
745 * claims to be sendmail), don't pass params (not a perfect fix,
748 * @param string $to To
749 * @param string $subject Subject
750 * @param string $body Message Body
751 * @param string $header Additional Header(s)
752 * @param string|null $params Params
756 private function mailPassthru($to, $subject, $body, $header, $params)
758 //Check overloading of mail function to avoid double-encoding
759 if (ini_get('mbstring.func_overload') & 1) {
760 $subject = $this->secureHeader($subject);
762 $subject = $this->encodeHeader($this->secureHeader($subject));
764 //Calling mail() with null params breaks
765 if (!$this->UseSendmailOptions
or null === $params) {
766 $result = @mail
($to, $subject, $body, $header);
768 $result = @mail
($to, $subject, $body, $header, $params);
775 * Output debugging info via user-defined method.
776 * Only generates output if SMTP debug output is enabled (@see SMTP::$do_debug).
778 * @see PHPMailer::$Debugoutput
779 * @see PHPMailer::$SMTPDebug
783 protected function edebug($str)
785 if ($this->SMTPDebug
<= 0) {
788 //Is this a PSR-3 logger?
789 if ($this->Debugoutput
instanceof \Psr\Log\LoggerInterface
) {
790 $this->Debugoutput
->debug($str);
794 //Avoid clash with built-in function names
795 if (!in_array($this->Debugoutput
, ['error_log', 'html', 'echo']) and is_callable($this->Debugoutput
)) {
796 call_user_func($this->Debugoutput
, $str, $this->SMTPDebug
);
800 switch ($this->Debugoutput
) {
802 //Don't output, just log
806 //Cleans up output a bit for a better looking, HTML-safe output
808 preg_replace('/[\r\n]+/', '', $str),
815 //Normalize line breaks
816 $str = preg_replace('/\r\n|\r/ms', "\n", $str);
817 echo gmdate('Y-m-d H:i:s'),
819 //Trim trailing space
821 //Indent for readability, except for trailing break
833 * Sets message type to HTML or plain.
835 * @param bool $isHtml True for HTML mode
837 public function isHTML($isHtml = true)
840 $this->ContentType
= 'text/html';
842 $this->ContentType
= 'text/plain';
847 * Send messages using SMTP.
849 public function isSMTP()
851 $this->Mailer
= 'smtp';
855 * Send messages using PHP's mail() function.
857 public function isMail()
859 $this->Mailer
= 'mail';
863 * Send messages using $Sendmail.
865 public function isSendmail()
867 $ini_sendmail_path = ini_get('sendmail_path');
869 if (false === stripos($ini_sendmail_path, 'sendmail')) {
870 $this->Sendmail
= '/usr/sbin/sendmail';
872 $this->Sendmail
= $ini_sendmail_path;
874 $this->Mailer
= 'sendmail';
878 * Send messages using qmail.
880 public function isQmail()
882 $ini_sendmail_path = ini_get('sendmail_path');
884 if (false === stripos($ini_sendmail_path, 'qmail')) {
885 $this->Sendmail
= '/var/qmail/bin/qmail-inject';
887 $this->Sendmail
= $ini_sendmail_path;
889 $this->Mailer
= 'qmail';
893 * Add a "To" address.
895 * @param string $address The email address to send to
896 * @param string $name
898 * @return bool true on success, false if address already used or invalid in some way
900 public function addAddress($address, $name = '')
902 return $this->addOrEnqueueAnAddress('to', $address, $name);
906 * Add a "CC" address.
908 * @param string $address The email address to send to
909 * @param string $name
911 * @return bool true on success, false if address already used or invalid in some way
913 public function addCC($address, $name = '')
915 return $this->addOrEnqueueAnAddress('cc', $address, $name);
919 * Add a "BCC" address.
921 * @param string $address The email address to send to
922 * @param string $name
924 * @return bool true on success, false if address already used or invalid in some way
926 public function addBCC($address, $name = '')
928 return $this->addOrEnqueueAnAddress('bcc', $address, $name);
932 * Add a "Reply-To" address.
934 * @param string $address The email address to reply to
935 * @param string $name
937 * @return bool true on success, false if address already used or invalid in some way
939 public function addReplyTo($address, $name = '')
941 return $this->addOrEnqueueAnAddress('Reply-To', $address, $name);
945 * Add an address to one of the recipient arrays or to the ReplyTo array. Because PHPMailer
946 * can't validate addresses with an IDN without knowing the PHPMailer::$CharSet (that can still
947 * be modified after calling this function), addition of such addresses is delayed until send().
948 * Addresses that have been added already return false, but do not throw exceptions.
950 * @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo'
951 * @param string $address The email address to send, resp. to reply to
952 * @param string $name
956 * @return bool true on success, false if address already used or invalid in some way
958 protected function addOrEnqueueAnAddress($kind, $address, $name)
960 $address = trim($address);
961 $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
962 $pos = strrpos($address, '@');
963 if (false === $pos) {
964 // At-sign is missing.
965 $error_message = sprintf('%s (%s): %s',
966 $this->lang('invalid_address'),
969 $this->setError($error_message);
970 $this->edebug($error_message);
971 if ($this->exceptions
) {
972 throw new Exception($error_message);
977 $params = [$kind, $address, $name];
978 // Enqueue addresses with IDN until we know the PHPMailer::$CharSet.
979 if ($this->has8bitChars(substr($address, ++
$pos)) and static::idnSupported()) {
980 if ('Reply-To' != $kind) {
981 if (!array_key_exists($address, $this->RecipientsQueue
)) {
982 $this->RecipientsQueue
[$address] = $params;
987 if (!array_key_exists($address, $this->ReplyToQueue
)) {
988 $this->ReplyToQueue
[$address] = $params;
997 // Immediately add standard addresses without IDN.
998 return call_user_func_array([$this, 'addAnAddress'], $params);
1002 * Add an address to one of the recipient arrays or to the ReplyTo array.
1003 * Addresses that have been added already return false, but do not throw exceptions.
1005 * @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo'
1006 * @param string $address The email address to send, resp. to reply to
1007 * @param string $name
1011 * @return bool true on success, false if address already used or invalid in some way
1013 protected function addAnAddress($kind, $address, $name = '')
1015 if (!in_array($kind, ['to', 'cc', 'bcc', 'Reply-To'])) {
1016 $error_message = sprintf('%s: %s',
1017 $this->lang('Invalid recipient kind'),
1019 $this->setError($error_message);
1020 $this->edebug($error_message);
1021 if ($this->exceptions
) {
1022 throw new Exception($error_message);
1027 if (!static::validateAddress($address)) {
1028 $error_message = sprintf('%s (%s): %s',
1029 $this->lang('invalid_address'),
1032 $this->setError($error_message);
1033 $this->edebug($error_message);
1034 if ($this->exceptions
) {
1035 throw new Exception($error_message);
1040 if ('Reply-To' != $kind) {
1041 if (!array_key_exists(strtolower($address), $this->all_recipients
)) {
1042 $this->{$kind}[] = [$address, $name];
1043 $this->all_recipients
[strtolower($address)] = true;
1048 if (!array_key_exists(strtolower($address), $this->ReplyTo
)) {
1049 $this->ReplyTo
[strtolower($address)] = [$address, $name];
1059 * Parse and validate a string containing one or more RFC822-style comma-separated email addresses
1060 * of the form "display name <address>" into an array of name/address pairs.
1061 * Uses the imap_rfc822_parse_adrlist function if the IMAP extension is available.
1062 * Note that quotes in the name part are removed.
1064 * @see http://www.andrew.cmu.edu/user/agreen1/testing/mrbs/web/Mail/RFC822.php A more careful implementation
1066 * @param string $addrstr The address list string
1067 * @param bool $useimap Whether to use the IMAP extension to parse the list
1071 public static function parseAddresses($addrstr, $useimap = true)
1074 if ($useimap and function_exists('imap_rfc822_parse_adrlist')) {
1075 //Use this built-in parser if it's available
1076 $list = imap_rfc822_parse_adrlist($addrstr, '');
1077 foreach ($list as $address) {
1078 if ('.SYNTAX-ERROR.' != $address->host
) {
1079 if (static::validateAddress($address->mailbox
. '@' . $address->host
)) {
1081 'name' => (property_exists($address, 'personal') ?
$address->personal
: ''),
1082 'address' => $address->mailbox
. '@' . $address->host
,
1088 //Use this simpler parser
1089 $list = explode(',', $addrstr);
1090 foreach ($list as $address) {
1091 $address = trim($address);
1092 //Is there a separate name part?
1093 if (strpos($address, '<') === false) {
1094 //No separate name, just use the whole thing
1095 if (static::validateAddress($address)) {
1098 'address' => $address,
1102 list($name, $email) = explode('<', $address);
1103 $email = trim(str_replace('>', '', $email));
1104 if (static::validateAddress($email)) {
1106 'name' => trim(str_replace(['"', "'"], '', $name)),
1107 'address' => $email,
1118 * Set the From and FromName properties.
1120 * @param string $address
1121 * @param string $name
1122 * @param bool $auto Whether to also set the Sender address, defaults to true
1128 public function setFrom($address, $name = '', $auto = true)
1130 $address = trim($address);
1131 $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
1132 // Don't validate now addresses with IDN. Will be done in send().
1133 $pos = strrpos($address, '@');
1134 if (false === $pos or
1135 (!$this->has8bitChars(substr($address, ++
$pos)) or !static::idnSupported()) and
1136 !static::validateAddress($address)) {
1137 $error_message = sprintf('%s (From): %s',
1138 $this->lang('invalid_address'),
1140 $this->setError($error_message);
1141 $this->edebug($error_message);
1142 if ($this->exceptions
) {
1143 throw new Exception($error_message);
1148 $this->From
= $address;
1149 $this->FromName
= $name;
1151 if (empty($this->Sender
)) {
1152 $this->Sender
= $address;
1160 * Return the Message-ID header of the last email.
1161 * Technically this is the value from the last time the headers were created,
1162 * but it's also the message ID of the last sent message except in
1163 * pathological cases.
1167 public function getLastMessageID()
1169 return $this->lastMessageID
;
1173 * Check that a string looks like an email address.
1174 * Validation patterns supported:
1175 * * `auto` Pick best pattern automatically;
1176 * * `pcre8` Use the squiloople.com pattern, requires PCRE > 8.0;
1177 * * `pcre` Use old PCRE implementation;
1178 * * `php` Use PHP built-in FILTER_VALIDATE_EMAIL;
1179 * * `html5` Use the pattern given by the HTML5 spec for 'email' type form input elements.
1180 * * `noregex` Don't use a regex: super fast, really dumb.
1181 * Alternatively you may pass in a callable to inject your own validator, for example:
1184 * PHPMailer::validateAddress('user@example.com', function($address) {
1185 * return (strpos($address, '@') !== false);
1189 * You can also set the PHPMailer::$validator static to a callable, allowing built-in methods to use your validator.
1191 * @param string $address The email address to check
1192 * @param string|callable $patternselect Which pattern to use
1196 public static function validateAddress($address, $patternselect = null)
1198 if (null === $patternselect) {
1199 $patternselect = static::$validator;
1201 if (is_callable($patternselect)) {
1202 return call_user_func($patternselect, $address);
1204 //Reject line breaks in addresses; it's valid RFC5322, but not RFC5321
1205 if (strpos($address, "\n") !== false or strpos($address, "\r") !== false) {
1208 switch ($patternselect) {
1209 case 'pcre': //Kept for BC
1212 * A more complex and more permissive version of the RFC5322 regex on which FILTER_VALIDATE_EMAIL
1214 * In addition to the addresses allowed by filter_var, also permits:
1215 * * dotless domains: `a@b`
1216 * * comments: `1234 @ local(blah) .machine .example`
1217 * * quoted elements: `'"test blah"@example.org'`
1218 * * numeric TLDs: `a@b.123`
1219 * * unbracketed IPv4 literals: `a@192.168.0.1`
1220 * * IPv6 literals: 'first.last@[IPv6:a1::]'
1221 * Not all of these will necessarily work for sending!
1223 * @see http://squiloople.com/2009/12/20/email-address-validation/
1224 * @copyright 2009-2010 Michael Rushton
1225 * Feel free to use and redistribute this code. But please keep this copyright notice.
1227 return (bool) preg_match(
1228 '/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)' .
1229 '((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)' .
1230 '(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)' .
1231 '([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*' .
1232 '(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)' .
1233 '(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}' .
1234 '|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:' .
1235 '|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}' .
1236 '|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD',
1241 * This is the pattern used in the HTML5 spec for validation of 'email' type form input elements.
1243 * @see http://www.whatwg.org/specs/web-apps/current-work/#e-mail-state-(type=email)
1245 return (bool) preg_match(
1246 '/^[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}' .
1247 '[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/sD',
1252 return (bool) filter_var($address, FILTER_VALIDATE_EMAIL
);
1257 * Tells whether IDNs (Internationalized Domain Names) are supported or not. This requires the
1258 * `intl` and `mbstring` PHP extensions.
1260 * @return bool `true` if required functions for IDN support are present
1262 public static function idnSupported()
1264 return function_exists('idn_to_ascii') and function_exists('mb_convert_encoding');
1268 * Converts IDN in given email address to its ASCII form, also known as punycode, if possible.
1269 * Important: Address must be passed in same encoding as currently set in PHPMailer::$CharSet.
1270 * This function silently returns unmodified address if:
1271 * - No conversion is necessary (i.e. domain name is not an IDN, or is already in ASCII form)
1272 * - Conversion to punycode is impossible (e.g. required PHP functions are not available)
1273 * or fails for any reason (e.g. domain contains characters not allowed in an IDN).
1275 * @see PHPMailer::$CharSet
1277 * @param string $address The email address to convert
1279 * @return string The encoded address in ASCII form
1281 public function punyencodeAddress($address)
1283 // Verify we have required functions, CharSet, and at-sign.
1284 $pos = strrpos($address, '@');
1285 if (static::idnSupported() and
1286 !empty($this->CharSet
) and
1289 $domain = substr($address, ++
$pos);
1290 // Verify CharSet string is a valid one, and domain properly encoded in this CharSet.
1291 if ($this->has8bitChars($domain) and @mb_check_encoding
($domain, $this->CharSet
)) {
1292 $domain = mb_convert_encoding($domain, 'UTF-8', $this->CharSet
);
1293 //Ignore IDE complaints about this line - method signature changed in PHP 5.4
1295 $punycode = idn_to_ascii($domain, $errorcode, INTL_IDNA_VARIANT_UTS46
);
1296 if (false !== $punycode) {
1297 return substr($address, 0, $pos) . $punycode;
1306 * Create a message and send it.
1307 * Uses the sending method specified by $Mailer.
1311 * @return bool false on error - See the ErrorInfo property for details of the error
1313 public function send()
1316 if (!$this->preSend()) {
1320 return $this->postSend();
1321 } catch (Exception
$exc) {
1322 $this->mailHeader
= '';
1323 $this->setError($exc->getMessage());
1324 if ($this->exceptions
) {
1333 * Prepare a message for sending.
1339 public function preSend()
1341 if ('smtp' == $this->Mailer
or
1342 ('mail' == $this->Mailer
and stripos(PHP_OS
, 'WIN') === 0)
1344 //SMTP mandates RFC-compliant line endings
1345 //and it's also used with mail() on Windows
1346 static::setLE("\r\n");
1348 //Maintain backward compatibility with legacy Linux command line mailers
1349 static::setLE(PHP_EOL
);
1351 //Check for buggy PHP versions that add a header with an incorrect line break
1352 if (ini_get('mail.add_x_header') == 1
1353 and 'mail' == $this->Mailer
1354 and stripos(PHP_OS
, 'WIN') === 0
1355 and ((version_compare(PHP_VERSION
, '7.0.0', '>=')
1356 and version_compare(PHP_VERSION
, '7.0.17', '<'))
1357 or (version_compare(PHP_VERSION
, '7.1.0', '>=')
1358 and version_compare(PHP_VERSION
, '7.1.3', '<')))
1361 'Your version of PHP is affected by a bug that may result in corrupted messages.' .
1362 ' To fix it, switch to sending using SMTP, disable the mail.add_x_header option in' .
1363 ' your php.ini, switch to MacOS or Linux, or upgrade your PHP to version 7.0.17+ or 7.1.3+.',
1369 $this->error_count
= 0; // Reset errors
1370 $this->mailHeader
= '';
1372 // Dequeue recipient and Reply-To addresses with IDN
1373 foreach (array_merge($this->RecipientsQueue
, $this->ReplyToQueue
) as $params) {
1374 $params[1] = $this->punyencodeAddress($params[1]);
1375 call_user_func_array([$this, 'addAnAddress'], $params);
1377 if (count($this->to
) +
count($this->cc
) +
count($this->bcc
) < 1) {
1378 throw new Exception($this->lang('provide_address'), self
::STOP_CRITICAL
);
1381 // Validate From, Sender, and ConfirmReadingTo addresses
1382 foreach (['From', 'Sender', 'ConfirmReadingTo'] as $address_kind) {
1383 $this->$address_kind = trim($this->$address_kind);
1384 if (empty($this->$address_kind)) {
1387 $this->$address_kind = $this->punyencodeAddress($this->$address_kind);
1388 if (!static::validateAddress($this->$address_kind)) {
1389 $error_message = sprintf('%s (%s): %s',
1390 $this->lang('invalid_address'),
1392 $this->$address_kind);
1393 $this->setError($error_message);
1394 $this->edebug($error_message);
1395 if ($this->exceptions
) {
1396 throw new Exception($error_message);
1403 // Set whether the message is multipart/alternative
1404 if ($this->alternativeExists()) {
1405 $this->ContentType
= 'multipart/alternative';
1408 $this->setMessageType();
1409 // Refuse to send an empty message unless we are specifically allowing it
1410 if (!$this->AllowEmpty
and empty($this->Body
)) {
1411 throw new Exception($this->lang('empty_message'), self
::STOP_CRITICAL
);
1414 //Trim subject consistently
1415 $this->Subject
= trim($this->Subject
);
1416 // Create body before headers in case body makes changes to headers (e.g. altering transfer encoding)
1417 $this->MIMEHeader
= '';
1418 $this->MIMEBody
= $this->createBody();
1419 // createBody may have added some headers, so retain them
1420 $tempheaders = $this->MIMEHeader
;
1421 $this->MIMEHeader
= $this->createHeader();
1422 $this->MIMEHeader
.= $tempheaders;
1424 // To capture the complete message when using mail(), create
1425 // an extra header list which createHeader() doesn't fold in
1426 if ('mail' == $this->Mailer
) {
1427 if (count($this->to
) > 0) {
1428 $this->mailHeader
.= $this->addrAppend('To', $this->to
);
1430 $this->mailHeader
.= $this->headerLine('To', 'undisclosed-recipients:;');
1432 $this->mailHeader
.= $this->headerLine(
1434 $this->encodeHeader($this->secureHeader($this->Subject
))
1438 // Sign with DKIM if enabled
1439 if (!empty($this->DKIM_domain
)
1440 and !empty($this->DKIM_selector
)
1441 and (!empty($this->DKIM_private_string
)
1442 or (!empty($this->DKIM_private
) and file_exists($this->DKIM_private
))
1445 $header_dkim = $this->DKIM_Add(
1446 $this->MIMEHeader
. $this->mailHeader
,
1447 $this->encodeHeader($this->secureHeader($this->Subject
)),
1450 $this->MIMEHeader
= rtrim($this->MIMEHeader
, "\r\n ") . static::$LE .
1451 static::normalizeBreaks($header_dkim) . static::$LE;
1455 } catch (Exception
$exc) {
1456 $this->setError($exc->getMessage());
1457 if ($this->exceptions
) {
1466 * Actually send a message via the selected mechanism.
1472 public function postSend()
1475 // Choose the mailer and send through it
1476 switch ($this->Mailer
) {
1479 return $this->sendmailSend($this->MIMEHeader
, $this->MIMEBody
);
1481 return $this->smtpSend($this->MIMEHeader
, $this->MIMEBody
);
1483 return $this->mailSend($this->MIMEHeader
, $this->MIMEBody
);
1485 $sendMethod = $this->Mailer
. 'Send';
1486 if (method_exists($this, $sendMethod)) {
1487 return $this->$sendMethod($this->MIMEHeader
, $this->MIMEBody
);
1490 return $this->mailSend($this->MIMEHeader
, $this->MIMEBody
);
1492 } catch (Exception
$exc) {
1493 $this->setError($exc->getMessage());
1494 $this->edebug($exc->getMessage());
1495 if ($this->exceptions
) {
1504 * Send mail using the $Sendmail program.
1506 * @see PHPMailer::$Sendmail
1508 * @param string $header The message headers
1509 * @param string $body The message body
1515 protected function sendmailSend($header, $body)
1517 // CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped.
1518 if (!empty($this->Sender
) and self
::isShellSafe($this->Sender
)) {
1519 if ('qmail' == $this->Mailer
) {
1520 $sendmailFmt = '%s -f%s';
1522 $sendmailFmt = '%s -oi -f%s -t';
1525 if ('qmail' == $this->Mailer
) {
1526 $sendmailFmt = '%s';
1528 $sendmailFmt = '%s -oi -t';
1532 $sendmail = sprintf($sendmailFmt, escapeshellcmd($this->Sendmail
), $this->Sender
);
1534 if ($this->SingleTo
) {
1535 foreach ($this->SingleToArray
as $toAddr) {
1536 $mail = @popen
($sendmail, 'w');
1538 throw new Exception($this->lang('execute') . $this->Sendmail
, self
::STOP_CRITICAL
);
1540 fwrite($mail, 'To: ' . $toAddr . "\n");
1541 fwrite($mail, $header);
1542 fwrite($mail, $body);
1543 $result = pclose($mail);
1554 if (0 !== $result) {
1555 throw new Exception($this->lang('execute') . $this->Sendmail
, self
::STOP_CRITICAL
);
1559 $mail = @popen
($sendmail, 'w');
1561 throw new Exception($this->lang('execute') . $this->Sendmail
, self
::STOP_CRITICAL
);
1563 fwrite($mail, $header);
1564 fwrite($mail, $body);
1565 $result = pclose($mail);
1576 if (0 !== $result) {
1577 throw new Exception($this->lang('execute') . $this->Sendmail
, self
::STOP_CRITICAL
);
1585 * Fix CVE-2016-10033 and CVE-2016-10045 by disallowing potentially unsafe shell characters.
1586 * Note that escapeshellarg and escapeshellcmd are inadequate for our purposes, especially on Windows.
1588 * @see https://github.com/PHPMailer/PHPMailer/issues/924 CVE-2016-10045 bug report
1590 * @param string $string The string to be validated
1594 protected static function isShellSafe($string)
1597 if (escapeshellcmd($string) !== $string
1598 or !in_array(escapeshellarg($string), ["'$string'", "\"$string\""])
1603 $length = strlen($string);
1605 for ($i = 0; $i < $length; ++
$i) {
1608 // All other characters have a special meaning in at least one common shell, including = and +.
1609 // Full stop (.) has a special meaning in cmd.exe, but its impact should be negligible here.
1610 // Note that this does permit non-Latin alphanumeric characters based on the current locale.
1611 if (!ctype_alnum($c) && strpos('@_-.', $c) === false) {
1620 * Send mail using the PHP mail() function.
1622 * @see http://www.php.net/manual/en/book.mail.php
1624 * @param string $header The message headers
1625 * @param string $body The message body
1631 protected function mailSend($header, $body)
1634 foreach ($this->to
as $toaddr) {
1635 $toArr[] = $this->addrFormat($toaddr);
1637 $to = implode(', ', $toArr);
1640 //This sets the SMTP envelope sender which gets turned into a return-path header by the receiver
1641 if (!empty($this->Sender
) and static::validateAddress($this->Sender
)) {
1642 //A space after `-f` is optional, but there is a long history of its presence
1643 //causing problems, so we don't use one
1644 //Exim docs: http://www.exim.org/exim-html-current/doc/html/spec_html/ch-the_exim_command_line.html
1645 //Sendmail docs: http://www.sendmail.org/~ca/email/man/sendmail.html
1646 //Qmail docs: http://www.qmail.org/man/man8/qmail-inject.html
1647 //Example problem: https://www.drupal.org/node/1057954
1648 // CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped.
1649 if (self
::isShellSafe($this->Sender
)) {
1650 $params = sprintf('-f%s', $this->Sender
);
1653 if (!empty($this->Sender
) and static::validateAddress($this->Sender
)) {
1654 $old_from = ini_get('sendmail_from');
1655 ini_set('sendmail_from', $this->Sender
);
1658 if ($this->SingleTo
and count($toArr) > 1) {
1659 foreach ($toArr as $toAddr) {
1660 $result = $this->mailPassthru($toAddr, $this->Subject
, $body, $header, $params);
1661 $this->doCallback($result, [$toAddr], $this->cc
, $this->bcc
, $this->Subject
, $body, $this->From
, []);
1664 $result = $this->mailPassthru($to, $this->Subject
, $body, $header, $params);
1665 $this->doCallback($result, $this->to
, $this->cc
, $this->bcc
, $this->Subject
, $body, $this->From
, []);
1667 if (isset($old_from)) {
1668 ini_set('sendmail_from', $old_from);
1671 throw new Exception($this->lang('instantiate'), self
::STOP_CRITICAL
);
1678 * Get an instance to use for SMTP operations.
1679 * Override this function to load your own SMTP implementation,
1680 * or set one with setSMTPInstance.
1684 public function getSMTPInstance()
1686 if (!is_object($this->smtp
)) {
1687 $this->smtp
= new SMTP();
1694 * Provide an instance to use for SMTP operations.
1700 public function setSMTPInstance(SMTP
$smtp)
1702 $this->smtp
= $smtp;
1708 * Send mail via SMTP.
1709 * Returns false if there is a bad MAIL FROM, RCPT, or DATA input.
1711 * @see PHPMailer::setSMTPInstance() to use a different class.
1713 * @uses \PHPMailer\PHPMailer\SMTP
1715 * @param string $header The message headers
1716 * @param string $body The message body
1722 protected function smtpSend($header, $body)
1725 if (!$this->smtpConnect($this->SMTPOptions
)) {
1726 throw new Exception($this->lang('smtp_connect_failed'), self
::STOP_CRITICAL
);
1728 //Sender already validated in preSend()
1729 if ('' == $this->Sender
) {
1730 $smtp_from = $this->From
;
1732 $smtp_from = $this->Sender
;
1734 if (!$this->smtp
->mail($smtp_from)) {
1735 $this->setError($this->lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp
->getError()));
1736 throw new Exception($this->ErrorInfo
, self
::STOP_CRITICAL
);
1740 // Attempt to send to all recipients
1741 foreach ([$this->to
, $this->cc
, $this->bcc
] as $togroup) {
1742 foreach ($togroup as $to) {
1743 if (!$this->smtp
->recipient($to[0])) {
1744 $error = $this->smtp
->getError();
1745 $bad_rcpt[] = ['to' => $to[0], 'error' => $error['detail']];
1751 $callbacks[] = ['issent'=>$isSent, 'to'=>$to[0]];
1755 // Only send the DATA command if we have viable recipients
1756 if ((count($this->all_recipients
) > count($bad_rcpt)) and !$this->smtp
->data($header . $body)) {
1757 throw new Exception($this->lang('data_not_accepted'), self
::STOP_CRITICAL
);
1760 $smtp_transaction_id = $this->smtp
->getLastTransactionID();
1762 if ($this->SMTPKeepAlive
) {
1763 $this->smtp
->reset();
1765 $this->smtp
->quit();
1766 $this->smtp
->close();
1769 foreach ($callbacks as $cb) {
1778 ['smtp_transaction_id' => $smtp_transaction_id]
1782 //Create error message for any bad addresses
1783 if (count($bad_rcpt) > 0) {
1785 foreach ($bad_rcpt as $bad) {
1786 $errstr .= $bad['to'] . ': ' . $bad['error'];
1788 throw new Exception(
1789 $this->lang('recipients_failed') . $errstr,
1798 * Initiate a connection to an SMTP server.
1799 * Returns false if the operation failed.
1801 * @param array $options An array of options compatible with stream_context_create()
1805 * @uses \PHPMailer\PHPMailer\SMTP
1809 public function smtpConnect($options = null)
1811 if (null === $this->smtp
) {
1812 $this->smtp
= $this->getSMTPInstance();
1815 //If no options are provided, use whatever is set in the instance
1816 if (null === $options) {
1817 $options = $this->SMTPOptions
;
1820 // Already connected?
1821 if ($this->smtp
->connected()) {
1825 $this->smtp
->setTimeout($this->Timeout
);
1826 $this->smtp
->setDebugLevel($this->SMTPDebug
);
1827 $this->smtp
->setDebugOutput($this->Debugoutput
);
1828 $this->smtp
->setVerp($this->do_verp
);
1829 $hosts = explode(';', $this->Host
);
1830 $lastexception = null;
1832 foreach ($hosts as $hostentry) {
1835 '/^((ssl|tls):\/\/)*([a-zA-Z0-9\.-]*|\[[a-fA-F0-9:]+\]):?([0-9]*)$/',
1839 static::edebug($this->lang('connect_host') . ' ' . $hostentry);
1840 // Not a valid host entry
1843 // $hostinfo[2]: optional ssl or tls prefix
1844 // $hostinfo[3]: the hostname
1845 // $hostinfo[4]: optional port number
1846 // The host string prefix can temporarily override the current setting for SMTPSecure
1847 // If it's not specified, the default value is used
1849 //Check the host name is a valid name or IP address before trying to use it
1850 if (!static::isValidHost($hostinfo[3])) {
1851 static::edebug($this->lang('connect_host') . ' ' . $hostentry);
1855 $secure = $this->SMTPSecure
;
1856 $tls = ('tls' == $this->SMTPSecure
);
1857 if ('ssl' == $hostinfo[2] or ('' == $hostinfo[2] and 'ssl' == $this->SMTPSecure
)) {
1859 $tls = false; // Can't have SSL and TLS at the same time
1861 } elseif ('tls' == $hostinfo[2]) {
1863 // tls doesn't use a prefix
1866 //Do we need the OpenSSL extension?
1867 $sslext = defined('OPENSSL_ALGO_SHA256');
1868 if ('tls' === $secure or 'ssl' === $secure) {
1869 //Check for an OpenSSL constant rather than using extension_loaded, which is sometimes disabled
1871 throw new Exception($this->lang('extension_missing') . 'openssl', self
::STOP_CRITICAL
);
1874 $host = $hostinfo[3];
1875 $port = $this->Port
;
1876 $tport = (int) $hostinfo[4];
1877 if ($tport > 0 and $tport < 65536) {
1880 if ($this->smtp
->connect($prefix . $host, $port, $this->Timeout
, $options)) {
1883 $hello = $this->Helo
;
1885 $hello = $this->serverHostname();
1887 $this->smtp
->hello($hello);
1888 //Automatically enable TLS encryption if:
1889 // * it's not disabled
1890 // * we have openssl extension
1891 // * we are not already using SSL
1892 // * the server offers STARTTLS
1893 if ($this->SMTPAutoTLS
and $sslext and 'ssl' != $secure and $this->smtp
->getServerExt('STARTTLS')) {
1897 if (!$this->smtp
->startTLS()) {
1898 throw new Exception($this->lang('connect_host'));
1900 // We must resend EHLO after TLS negotiation
1901 $this->smtp
->hello($hello);
1903 if ($this->SMTPAuth
) {
1904 if (!$this->smtp
->authenticate(
1911 throw new Exception($this->lang('authenticate'));
1916 } catch (Exception
$exc) {
1917 $lastexception = $exc;
1918 $this->edebug($exc->getMessage());
1919 // We must have connected, but then failed TLS or Auth, so close connection nicely
1920 $this->smtp
->quit();
1924 // If we get here, all connection attempts have failed, so close connection hard
1925 $this->smtp
->close();
1926 // As we've caught all exceptions, just report whatever the last one was
1927 if ($this->exceptions
and null !== $lastexception) {
1928 throw $lastexception;
1935 * Close the active SMTP session if one exists.
1937 public function smtpClose()
1939 if (null !== $this->smtp
) {
1940 if ($this->smtp
->connected()) {
1941 $this->smtp
->quit();
1942 $this->smtp
->close();
1948 * Set the language for error messages.
1949 * Returns false if it cannot load the language file.
1950 * The default language is English.
1952 * @param string $langcode ISO 639-1 2-character language code (e.g. French is "fr")
1953 * @param string $lang_path Path to the language file directory, with trailing separator (slash)
1957 public function setLanguage($langcode = 'en', $lang_path = '')
1959 // Backwards compatibility for renamed language codes
1960 $renamed_langcodes = [
1969 if (isset($renamed_langcodes[$langcode])) {
1970 $langcode = $renamed_langcodes[$langcode];
1973 // Define full set of translatable strings in English
1975 'authenticate' => 'SMTP Error: Could not authenticate.',
1976 'connect_host' => 'SMTP Error: Could not connect to SMTP host.',
1977 'data_not_accepted' => 'SMTP Error: data not accepted.',
1978 'empty_message' => 'Message body empty',
1979 'encoding' => 'Unknown encoding: ',
1980 'execute' => 'Could not execute: ',
1981 'file_access' => 'Could not access file: ',
1982 'file_open' => 'File Error: Could not open file: ',
1983 'from_failed' => 'The following From address failed: ',
1984 'instantiate' => 'Could not instantiate mail function.',
1985 'invalid_address' => 'Invalid address: ',
1986 'mailer_not_supported' => ' mailer is not supported.',
1987 'provide_address' => 'You must provide at least one recipient email address.',
1988 'recipients_failed' => 'SMTP Error: The following recipients failed: ',
1989 'signing' => 'Signing Error: ',
1990 'smtp_connect_failed' => 'SMTP connect() failed.',
1991 'smtp_error' => 'SMTP server error: ',
1992 'variable_set' => 'Cannot set or reset variable: ',
1993 'extension_missing' => 'Extension missing: ',
1995 if (empty($lang_path)) {
1996 // Calculate an absolute path so it can work if CWD is not here
1997 $lang_path = dirname(__DIR__
) . DIRECTORY_SEPARATOR
. 'language' . DIRECTORY_SEPARATOR
;
1999 //Validate $langcode
2000 if (!preg_match('/^[a-z]{2}(?:_[a-zA-Z]{2})?$/', $langcode)) {
2004 $lang_file = $lang_path . 'phpmailer.lang-' . $langcode . '.php';
2005 // There is no English translation file
2006 if ('en' != $langcode) {
2007 // Make sure language file path is readable
2008 if (!file_exists($lang_file)) {
2011 // Overwrite language-specific strings.
2012 // This way we'll never have missing translation keys.
2013 $foundlang = include $lang_file;
2016 $this->language
= $PHPMAILER_LANG;
2018 return (bool) $foundlang; // Returns false if language not found
2022 * Get the array of strings for the current language.
2026 public function getTranslations()
2028 return $this->language
;
2032 * Create recipient headers.
2034 * @param string $type
2035 * @param array $addr An array of recipients,
2036 * where each recipient is a 2-element indexed array with element 0 containing an address
2037 * and element 1 containing a name, like:
2038 * [['joe@example.com', 'Joe User'], ['zoe@example.com', 'Zoe User']]
2042 public function addrAppend($type, $addr)
2045 foreach ($addr as $address) {
2046 $addresses[] = $this->addrFormat($address);
2049 return $type . ': ' . implode(', ', $addresses) . static::$LE;
2053 * Format an address for use in a message header.
2055 * @param array $addr A 2-element indexed array, element 0 containing an address, element 1 containing a name like
2056 * ['joe@example.com', 'Joe User']
2060 public function addrFormat($addr)
2062 if (empty($addr[1])) { // No name provided
2063 return $this->secureHeader($addr[0]);
2066 return $this->encodeHeader($this->secureHeader($addr[1]), 'phrase') . ' <' . $this->secureHeader(
2072 * Word-wrap message.
2073 * For use with mailers that do not automatically perform wrapping
2074 * and for quoted-printable encoded messages.
2075 * Original written by philippe.
2077 * @param string $message The message to wrap
2078 * @param int $length The line length to wrap to
2079 * @param bool $qp_mode Whether to run in Quoted-Printable mode
2083 public function wrapText($message, $length, $qp_mode = false)
2086 $soft_break = sprintf(' =%s', static::$LE);
2088 $soft_break = static::$LE;
2090 // If utf-8 encoding is used, we will need to make sure we don't
2091 // split multibyte characters when we wrap
2092 $is_utf8 = 'utf-8' == strtolower($this->CharSet
);
2093 $lelen = strlen(static::$LE);
2094 $crlflen = strlen(static::$LE);
2096 $message = static::normalizeBreaks($message);
2097 //Remove a trailing line break
2098 if (substr($message, -$lelen) == static::$LE) {
2099 $message = substr($message, 0, -$lelen);
2102 //Split message into lines
2103 $lines = explode(static::$LE, $message);
2104 //Message will be rebuilt in here
2106 foreach ($lines as $line) {
2107 $words = explode(' ', $line);
2110 foreach ($words as $word) {
2111 if ($qp_mode and (strlen($word) > $length)) {
2112 $space_left = $length - strlen($buf) - $crlflen;
2114 if ($space_left > 20) {
2117 $len = $this->utf8CharBoundary($word, $len);
2118 } elseif ('=' == substr($word, $len - 1, 1)) {
2120 } elseif ('=' == substr($word, $len - 2, 1)) {
2123 $part = substr($word, 0, $len);
2124 $word = substr($word, $len);
2125 $buf .= ' ' . $part;
2126 $message .= $buf . sprintf('=%s', static::$LE);
2128 $message .= $buf . $soft_break;
2132 while (strlen($word) > 0) {
2138 $len = $this->utf8CharBoundary($word, $len);
2139 } elseif ('=' == substr($word, $len - 1, 1)) {
2141 } elseif ('=' == substr($word, $len - 2, 1)) {
2144 $part = substr($word, 0, $len);
2145 $word = substr($word, $len);
2147 if (strlen($word) > 0) {
2148 $message .= $part . sprintf('=%s', static::$LE);
2160 if (strlen($buf) > $length and '' != $buf_o) {
2161 $message .= $buf_o . $soft_break;
2167 $message .= $buf . static::$LE;
2174 * Find the last character boundary prior to $maxLength in a utf-8
2175 * quoted-printable encoded string.
2176 * Original written by Colin Brown.
2178 * @param string $encodedText utf-8 QP text
2179 * @param int $maxLength Find the last character boundary prior to this length
2183 public function utf8CharBoundary($encodedText, $maxLength)
2185 $foundSplitPos = false;
2187 while (!$foundSplitPos) {
2188 $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
2189 $encodedCharPos = strpos($lastChunk, '=');
2190 if (false !== $encodedCharPos) {
2191 // Found start of encoded character byte within $lookBack block.
2192 // Check the encoded byte value (the 2 chars after the '=')
2193 $hex = substr($encodedText, $maxLength - $lookBack +
$encodedCharPos +
1, 2);
2194 $dec = hexdec($hex);
2196 // Single byte character.
2197 // If the encoded char was found at pos 0, it will fit
2198 // otherwise reduce maxLength to start of the encoded char
2199 if ($encodedCharPos > 0) {
2200 $maxLength -= $lookBack - $encodedCharPos;
2202 $foundSplitPos = true;
2203 } elseif ($dec >= 192) {
2204 // First byte of a multi byte character
2205 // Reduce maxLength to split at start of character
2206 $maxLength -= $lookBack - $encodedCharPos;
2207 $foundSplitPos = true;
2208 } elseif ($dec < 192) {
2209 // Middle byte of a multi byte character, look further back
2213 // No encoded character found
2214 $foundSplitPos = true;
2222 * Apply word wrapping to the message body.
2223 * Wraps the message body to the number of chars set in the WordWrap property.
2224 * You should only do this to plain-text bodies as wrapping HTML tags may break them.
2225 * This is called automatically by createBody(), so you don't need to call it yourself.
2227 public function setWordWrap()
2229 if ($this->WordWrap
< 1) {
2233 switch ($this->message_type
) {
2237 case 'alt_inline_attach':
2238 $this->AltBody
= $this->wrapText($this->AltBody
, $this->WordWrap
);
2241 $this->Body
= $this->wrapText($this->Body
, $this->WordWrap
);
2247 * Assemble message headers.
2249 * @return string The assembled headers
2251 public function createHeader()
2255 $result .= $this->headerLine('Date', '' == $this->MessageDate ? self
::rfcDate() : $this->MessageDate
);
2257 // To be created automatically by mail()
2258 if ($this->SingleTo
) {
2259 if ('mail' != $this->Mailer
) {
2260 foreach ($this->to
as $toaddr) {
2261 $this->SingleToArray
[] = $this->addrFormat($toaddr);
2265 if (count($this->to
) > 0) {
2266 if ('mail' != $this->Mailer
) {
2267 $result .= $this->addrAppend('To', $this->to
);
2269 } elseif (count($this->cc
) == 0) {
2270 $result .= $this->headerLine('To', 'undisclosed-recipients:;');
2274 $result .= $this->addrAppend('From', [[trim($this->From
), $this->FromName
]]);
2276 // sendmail and mail() extract Cc from the header before sending
2277 if (count($this->cc
) > 0) {
2278 $result .= $this->addrAppend('Cc', $this->cc
);
2281 // sendmail and mail() extract Bcc from the header before sending
2283 'sendmail' == $this->Mailer
or 'qmail' == $this->Mailer
or 'mail' == $this->Mailer
2285 and count($this->bcc
) > 0
2287 $result .= $this->addrAppend('Bcc', $this->bcc
);
2290 if (count($this->ReplyTo
) > 0) {
2291 $result .= $this->addrAppend('Reply-To', $this->ReplyTo
);
2294 // mail() sets the subject itself
2295 if ('mail' != $this->Mailer
) {
2296 $result .= $this->headerLine('Subject', $this->encodeHeader($this->secureHeader($this->Subject
)));
2299 // Only allow a custom message ID if it conforms to RFC 5322 section 3.6.4
2300 // https://tools.ietf.org/html/rfc5322#section-3.6.4
2301 if ('' != $this->MessageID
and preg_match('/^<.*@.*>$/', $this->MessageID
)) {
2302 $this->lastMessageID
= $this->MessageID
;
2304 $this->lastMessageID
= sprintf('<%s@%s>', $this->uniqueid
, $this->serverHostname());
2306 $result .= $this->headerLine('Message-ID', $this->lastMessageID
);
2307 if (null !== $this->Priority
) {
2308 $result .= $this->headerLine('X-Priority', $this->Priority
);
2310 if ('' == $this->XMailer
) {
2311 $result .= $this->headerLine(
2313 'PHPMailer ' . self
::VERSION
. ' (https://github.com/PHPMailer/PHPMailer)'
2316 $myXmailer = trim($this->XMailer
);
2318 $result .= $this->headerLine('X-Mailer', $myXmailer);
2322 if ('' != $this->ConfirmReadingTo
) {
2323 $result .= $this->headerLine('Disposition-Notification-To', '<' . $this->ConfirmReadingTo
. '>');
2326 // Add custom headers
2327 foreach ($this->CustomHeader
as $header) {
2328 $result .= $this->headerLine(
2330 $this->encodeHeader(trim($header[1]))
2333 if (!$this->sign_key_file
) {
2334 $result .= $this->headerLine('MIME-Version', '1.0');
2335 $result .= $this->getMailMIME();
2342 * Get the message MIME type headers.
2346 public function getMailMIME()
2349 $ismultipart = true;
2350 switch ($this->message_type
) {
2352 $result .= $this->headerLine('Content-Type', 'multipart/related;');
2353 $result .= $this->textLine("\tboundary=\"" . $this->boundary
[1] . '"');
2356 case 'inline_attach':
2358 case 'alt_inline_attach':
2359 $result .= $this->headerLine('Content-Type', 'multipart/mixed;');
2360 $result .= $this->textLine("\tboundary=\"" . $this->boundary
[1] . '"');
2364 $result .= $this->headerLine('Content-Type', 'multipart/alternative;');
2365 $result .= $this->textLine("\tboundary=\"" . $this->boundary
[1] . '"');
2368 // Catches case 'plain': and case '':
2369 $result .= $this->textLine('Content-Type: ' . $this->ContentType
. '; charset=' . $this->CharSet
);
2370 $ismultipart = false;
2373 // RFC1341 part 5 says 7bit is assumed if not specified
2374 if ('7bit' != $this->Encoding
) {
2375 // RFC 2045 section 6.4 says multipart MIME parts may only use 7bit, 8bit or binary CTE
2377 if ('8bit' == $this->Encoding
) {
2378 $result .= $this->headerLine('Content-Transfer-Encoding', '8bit');
2380 // The only remaining alternatives are quoted-printable and base64, which are both 7bit compatible
2382 $result .= $this->headerLine('Content-Transfer-Encoding', $this->Encoding
);
2386 if ('mail' != $this->Mailer
) {
2387 $result .= static::$LE;
2394 * Returns the whole MIME message.
2395 * Includes complete headers and body.
2396 * Only valid post preSend().
2398 * @see PHPMailer::preSend()
2402 public function getSentMIMEMessage()
2404 return rtrim($this->MIMEHeader
. $this->mailHeader
, "\n\r") . static::$LE . static::$LE . $this->MIMEBody
;
2408 * Create a unique ID to use for boundaries.
2412 protected function generateId()
2414 $len = 32; //32 bytes = 256 bits
2415 if (function_exists('random_bytes')) {
2416 $bytes = random_bytes($len);
2417 } elseif (function_exists('openssl_random_pseudo_bytes')) {
2418 $bytes = openssl_random_pseudo_bytes($len);
2420 //Use a hash to force the length to the same as the other methods
2421 $bytes = hash('sha256', uniqid((string) mt_rand(), true), true);
2424 //We don't care about messing up base64 format here, just want a random string
2425 return str_replace(['=', '+', '/'], '', base64_encode(hash('sha256', $bytes, true)));
2429 * Assemble the message body.
2430 * Returns an empty string on failure.
2434 * @return string The assembled message body
2436 public function createBody()
2439 //Create unique IDs and preset boundaries
2440 $this->uniqueid
= $this->generateId();
2441 $this->boundary
[1] = 'b1_' . $this->uniqueid
;
2442 $this->boundary
[2] = 'b2_' . $this->uniqueid
;
2443 $this->boundary
[3] = 'b3_' . $this->uniqueid
;
2445 if ($this->sign_key_file
) {
2446 $body .= $this->getMailMIME() . static::$LE;
2449 $this->setWordWrap();
2451 $bodyEncoding = $this->Encoding
;
2452 $bodyCharSet = $this->CharSet
;
2453 //Can we do a 7-bit downgrade?
2454 if ('8bit' == $bodyEncoding and !$this->has8bitChars($this->Body
)) {
2455 $bodyEncoding = '7bit';
2456 //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit
2457 $bodyCharSet = 'us-ascii';
2459 //If lines are too long, and we're not already using an encoding that will shorten them,
2460 //change to quoted-printable transfer encoding for the body part only
2461 if ('base64' != $this->Encoding
and static::hasLineLongerThanMax($this->Body
)) {
2462 $bodyEncoding = 'quoted-printable';
2465 $altBodyEncoding = $this->Encoding
;
2466 $altBodyCharSet = $this->CharSet
;
2467 //Can we do a 7-bit downgrade?
2468 if ('8bit' == $altBodyEncoding and !$this->has8bitChars($this->AltBody
)) {
2469 $altBodyEncoding = '7bit';
2470 //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit
2471 $altBodyCharSet = 'us-ascii';
2473 //If lines are too long, and we're not already using an encoding that will shorten them,
2474 //change to quoted-printable transfer encoding for the alt body part only
2475 if ('base64' != $altBodyEncoding and static::hasLineLongerThanMax($this->AltBody
)) {
2476 $altBodyEncoding = 'quoted-printable';
2478 //Use this as a preamble in all multipart message types
2479 $mimepre = 'This is a multi-part message in MIME format.' . static::$LE;
2480 switch ($this->message_type
) {
2483 $body .= $this->getBoundary($this->boundary
[1], $bodyCharSet, '', $bodyEncoding);
2484 $body .= $this->encodeString($this->Body
, $bodyEncoding);
2485 $body .= static::$LE;
2486 $body .= $this->attachAll('inline', $this->boundary
[1]);
2490 $body .= $this->getBoundary($this->boundary
[1], $bodyCharSet, '', $bodyEncoding);
2491 $body .= $this->encodeString($this->Body
, $bodyEncoding);
2492 $body .= static::$LE;
2493 $body .= $this->attachAll('attachment', $this->boundary
[1]);
2495 case 'inline_attach':
2497 $body .= $this->textLine('--' . $this->boundary
[1]);
2498 $body .= $this->headerLine('Content-Type', 'multipart/related;');
2499 $body .= $this->textLine("\tboundary=\"" . $this->boundary
[2] . '"');
2500 $body .= static::$LE;
2501 $body .= $this->getBoundary($this->boundary
[2], $bodyCharSet, '', $bodyEncoding);
2502 $body .= $this->encodeString($this->Body
, $bodyEncoding);
2503 $body .= static::$LE;
2504 $body .= $this->attachAll('inline', $this->boundary
[2]);
2505 $body .= static::$LE;
2506 $body .= $this->attachAll('attachment', $this->boundary
[1]);
2510 $body .= $this->getBoundary($this->boundary
[1], $altBodyCharSet, 'text/plain', $altBodyEncoding);
2511 $body .= $this->encodeString($this->AltBody
, $altBodyEncoding);
2512 $body .= static::$LE;
2513 $body .= $this->getBoundary($this->boundary
[1], $bodyCharSet, 'text/html', $bodyEncoding);
2514 $body .= $this->encodeString($this->Body
, $bodyEncoding);
2515 $body .= static::$LE;
2516 if (!empty($this->Ical
)) {
2517 $body .= $this->getBoundary($this->boundary
[1], '', 'text/calendar; method=REQUEST', '');
2518 $body .= $this->encodeString($this->Ical
, $this->Encoding
);
2519 $body .= static::$LE;
2521 $body .= $this->endBoundary($this->boundary
[1]);
2525 $body .= $this->getBoundary($this->boundary
[1], $altBodyCharSet, 'text/plain', $altBodyEncoding);
2526 $body .= $this->encodeString($this->AltBody
, $altBodyEncoding);
2527 $body .= static::$LE;
2528 $body .= $this->textLine('--' . $this->boundary
[1]);
2529 $body .= $this->headerLine('Content-Type', 'multipart/related;');
2530 $body .= $this->textLine("\tboundary=\"" . $this->boundary
[2] . '"');
2531 $body .= static::$LE;
2532 $body .= $this->getBoundary($this->boundary
[2], $bodyCharSet, 'text/html', $bodyEncoding);
2533 $body .= $this->encodeString($this->Body
, $bodyEncoding);
2534 $body .= static::$LE;
2535 $body .= $this->attachAll('inline', $this->boundary
[2]);
2536 $body .= static::$LE;
2537 $body .= $this->endBoundary($this->boundary
[1]);
2541 $body .= $this->textLine('--' . $this->boundary
[1]);
2542 $body .= $this->headerLine('Content-Type', 'multipart/alternative;');
2543 $body .= $this->textLine("\tboundary=\"" . $this->boundary
[2] . '"');
2544 $body .= static::$LE;
2545 $body .= $this->getBoundary($this->boundary
[2], $altBodyCharSet, 'text/plain', $altBodyEncoding);
2546 $body .= $this->encodeString($this->AltBody
, $altBodyEncoding);
2547 $body .= static::$LE;
2548 $body .= $this->getBoundary($this->boundary
[2], $bodyCharSet, 'text/html', $bodyEncoding);
2549 $body .= $this->encodeString($this->Body
, $bodyEncoding);
2550 $body .= static::$LE;
2551 if (!empty($this->Ical
)) {
2552 $body .= $this->getBoundary($this->boundary
[2], '', 'text/calendar; method=REQUEST', '');
2553 $body .= $this->encodeString($this->Ical
, $this->Encoding
);
2555 $body .= $this->endBoundary($this->boundary
[2]);
2556 $body .= static::$LE;
2557 $body .= $this->attachAll('attachment', $this->boundary
[1]);
2559 case 'alt_inline_attach':
2561 $body .= $this->textLine('--' . $this->boundary
[1]);
2562 $body .= $this->headerLine('Content-Type', 'multipart/alternative;');
2563 $body .= $this->textLine("\tboundary=\"" . $this->boundary
[2] . '"');
2564 $body .= static::$LE;
2565 $body .= $this->getBoundary($this->boundary
[2], $altBodyCharSet, 'text/plain', $altBodyEncoding);
2566 $body .= $this->encodeString($this->AltBody
, $altBodyEncoding);
2567 $body .= static::$LE;
2568 $body .= $this->textLine('--' . $this->boundary
[2]);
2569 $body .= $this->headerLine('Content-Type', 'multipart/related;');
2570 $body .= $this->textLine("\tboundary=\"" . $this->boundary
[3] . '"');
2571 $body .= static::$LE;
2572 $body .= $this->getBoundary($this->boundary
[3], $bodyCharSet, 'text/html', $bodyEncoding);
2573 $body .= $this->encodeString($this->Body
, $bodyEncoding);
2574 $body .= static::$LE;
2575 $body .= $this->attachAll('inline', $this->boundary
[3]);
2576 $body .= static::$LE;
2577 $body .= $this->endBoundary($this->boundary
[2]);
2578 $body .= static::$LE;
2579 $body .= $this->attachAll('attachment', $this->boundary
[1]);
2582 // Catch case 'plain' and case '', applies to simple `text/plain` and `text/html` body content types
2583 //Reset the `Encoding` property in case we changed it for line length reasons
2584 $this->Encoding
= $bodyEncoding;
2585 $body .= $this->encodeString($this->Body
, $this->Encoding
);
2589 if ($this->isError()) {
2591 if ($this->exceptions
) {
2592 throw new Exception($this->lang('empty_message'), self
::STOP_CRITICAL
);
2594 } elseif ($this->sign_key_file
) {
2596 if (!defined('PKCS7_TEXT')) {
2597 throw new Exception($this->lang('extension_missing') . 'openssl');
2599 // @TODO would be nice to use php://temp streams here
2600 $file = tempnam(sys_get_temp_dir(), 'mail');
2601 if (false === file_put_contents($file, $body)) {
2602 throw new Exception($this->lang('signing') . ' Could not write temp file');
2604 $signed = tempnam(sys_get_temp_dir(), 'signed');
2605 //Workaround for PHP bug https://bugs.php.net/bug.php?id=69197
2606 if (empty($this->sign_extracerts_file
)) {
2607 $sign = @openssl_pkcs7_sign
(
2610 'file://' . realpath($this->sign_cert_file
),
2611 ['file://' . realpath($this->sign_key_file
), $this->sign_key_pass
],
2615 $sign = @openssl_pkcs7_sign
(
2618 'file://' . realpath($this->sign_cert_file
),
2619 ['file://' . realpath($this->sign_key_file
), $this->sign_key_pass
],
2622 $this->sign_extracerts_file
2627 $body = file_get_contents($signed);
2629 //The message returned by openssl contains both headers and body, so need to split them up
2630 $parts = explode("\n\n", $body, 2);
2631 $this->MIMEHeader
.= $parts[0] . static::$LE . static::$LE;
2635 throw new Exception($this->lang('signing') . openssl_error_string());
2637 } catch (Exception
$exc) {
2639 if ($this->exceptions
) {
2649 * Return the start of a message boundary.
2651 * @param string $boundary
2652 * @param string $charSet
2653 * @param string $contentType
2654 * @param string $encoding
2658 protected function getBoundary($boundary, $charSet, $contentType, $encoding)
2661 if ('' == $charSet) {
2662 $charSet = $this->CharSet
;
2664 if ('' == $contentType) {
2665 $contentType = $this->ContentType
;
2667 if ('' == $encoding) {
2668 $encoding = $this->Encoding
;
2670 $result .= $this->textLine('--' . $boundary);
2671 $result .= sprintf('Content-Type: %s; charset=%s', $contentType, $charSet);
2672 $result .= static::$LE;
2673 // RFC1341 part 5 says 7bit is assumed if not specified
2674 if ('7bit' != $encoding) {
2675 $result .= $this->headerLine('Content-Transfer-Encoding', $encoding);
2677 $result .= static::$LE;
2683 * Return the end of a message boundary.
2685 * @param string $boundary
2689 protected function endBoundary($boundary)
2691 return static::$LE . '--' . $boundary . '--' . static::$LE;
2695 * Set the message type.
2696 * PHPMailer only supports some preset message types, not arbitrary MIME structures.
2698 protected function setMessageType()
2701 if ($this->alternativeExists()) {
2704 if ($this->inlineImageExists()) {
2707 if ($this->attachmentExists()) {
2710 $this->message_type
= implode('_', $type);
2711 if ('' == $this->message_type
) {
2712 //The 'plain' message_type refers to the message having a single body element, not that it is plain-text
2713 $this->message_type
= 'plain';
2718 * Format a header line.
2720 * @param string $name
2721 * @param string|int $value
2725 public function headerLine($name, $value)
2727 return $name . ': ' . $value . static::$LE;
2731 * Return a formatted mail line.
2733 * @param string $value
2737 public function textLine($value)
2739 return $value . static::$LE;
2743 * Add an attachment from a path on the filesystem.
2744 * Never use a user-supplied path to a file!
2745 * Returns false if the file could not be found or read.
2747 * @param string $path Path to the attachment
2748 * @param string $name Overrides the attachment name
2749 * @param string $encoding File encoding (see $Encoding)
2750 * @param string $type File extension (MIME) type
2751 * @param string $disposition Disposition to use
2757 public function addAttachment($path, $name = '', $encoding = 'base64', $type = '', $disposition = 'attachment')
2760 if (!@is_file
($path)) {
2761 throw new Exception($this->lang('file_access') . $path, self
::STOP_CONTINUE
);
2764 // If a MIME type is not specified, try to work it out from the file name
2766 $type = static::filenameToType($path);
2769 $filename = basename($path);
2774 $this->attachment
[] = [
2780 5 => false, // isStringAttachment
2784 } catch (Exception
$exc) {
2785 $this->setError($exc->getMessage());
2786 $this->edebug($exc->getMessage());
2787 if ($this->exceptions
) {
2798 * Return the array of attachments.
2802 public function getAttachments()
2804 return $this->attachment
;
2808 * Attach all file, string, and binary attachments to the message.
2809 * Returns an empty string on failure.
2811 * @param string $disposition_type
2812 * @param string $boundary
2816 protected function attachAll($disposition_type, $boundary)
2818 // Return text of body
2823 // Add all attachments
2824 foreach ($this->attachment
as $attachment) {
2825 // Check if it is a valid disposition_filter
2826 if ($attachment[6] == $disposition_type) {
2827 // Check for string attachment
2830 $bString = $attachment[5];
2832 $string = $attachment[0];
2834 $path = $attachment[0];
2837 $inclhash = hash('sha256', serialize($attachment));
2838 if (in_array($inclhash, $incl)) {
2841 $incl[] = $inclhash;
2842 $name = $attachment[2];
2843 $encoding = $attachment[3];
2844 $type = $attachment[4];
2845 $disposition = $attachment[6];
2846 $cid = $attachment[7];
2847 if ('inline' == $disposition and array_key_exists($cid, $cidUniq)) {
2850 $cidUniq[$cid] = true;
2852 $mime[] = sprintf('--%s%s', $boundary, static::$LE);
2853 //Only include a filename property if we have one
2854 if (!empty($name)) {
2856 'Content-Type: %s; name="%s"%s',
2858 $this->encodeHeader($this->secureHeader($name)),
2863 'Content-Type: %s%s',
2868 // RFC1341 part 5 says 7bit is assumed if not specified
2869 if ('7bit' != $encoding) {
2870 $mime[] = sprintf('Content-Transfer-Encoding: %s%s', $encoding, static::$LE);
2874 $mime[] = sprintf('Content-ID: <%s>%s', $cid, static::$LE);
2877 // If a filename contains any of these chars, it should be quoted,
2878 // but not otherwise: RFC2183 & RFC2045 5.1
2879 // Fixes a warning in IETF's msglint MIME checker
2880 // Allow for bypassing the Content-Disposition header totally
2881 if (!(empty($disposition))) {
2882 $encoded_name = $this->encodeHeader($this->secureHeader($name));
2883 if (preg_match('/[ \(\)<>@,;:\\"\/\[\]\?=]/', $encoded_name)) {
2885 'Content-Disposition: %s; filename="%s"%s',
2888 static::$LE . static::$LE
2891 if (!empty($encoded_name)) {
2893 'Content-Disposition: %s; filename=%s%s',
2896 static::$LE . static::$LE
2900 'Content-Disposition: %s%s',
2902 static::$LE . static::$LE
2907 $mime[] = static::$LE;
2910 // Encode as string attachment
2912 $mime[] = $this->encodeString($string, $encoding);
2914 $mime[] = $this->encodeFile($path, $encoding);
2916 if ($this->isError()) {
2919 $mime[] = static::$LE;
2923 $mime[] = sprintf('--%s--%s', $boundary, static::$LE);
2925 return implode('', $mime);
2929 * Encode a file attachment in requested format.
2930 * Returns an empty string on failure.
2932 * @param string $path The full path to the file
2933 * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
2939 protected function encodeFile($path, $encoding = 'base64')
2942 if (!file_exists($path)) {
2943 throw new Exception($this->lang('file_open') . $path, self
::STOP_CONTINUE
);
2945 $file_buffer = file_get_contents($path);
2946 if (false === $file_buffer) {
2947 throw new Exception($this->lang('file_open') . $path, self
::STOP_CONTINUE
);
2949 $file_buffer = $this->encodeString($file_buffer, $encoding);
2951 return $file_buffer;
2952 } catch (Exception
$exc) {
2953 $this->setError($exc->getMessage());
2960 * Encode a string in requested format.
2961 * Returns an empty string on failure.
2963 * @param string $str The text to encode
2964 * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable
2968 public function encodeString($str, $encoding = 'base64')
2971 switch (strtolower($encoding)) {
2973 $encoded = chunk_split(
2974 base64_encode($str),
2975 static::STD_LINE_LENGTH
,
2981 $encoded = static::normalizeBreaks($str);
2982 // Make sure it ends with a line break
2983 if (substr($encoded, -(strlen(static::$LE))) != static::$LE) {
2984 $encoded .= static::$LE;
2990 case 'quoted-printable':
2991 $encoded = $this->encodeQP($str);
2994 $this->setError($this->lang('encoding') . $encoding);
3002 * Encode a header value (not including its label) optimally.
3003 * Picks shortest of Q, B, or none. Result includes folding if needed.
3004 * See RFC822 definitions for phrase, comment and text positions.
3006 * @param string $str The header value to encode
3007 * @param string $position What context the string will be used in
3011 public function encodeHeader($str, $position = 'text')
3014 switch (strtolower($position)) {
3016 if (!preg_match('/[\200-\377]/', $str)) {
3017 // Can't use addslashes as we don't know the value of magic_quotes_sybase
3018 $encoded = addcslashes($str, "\0..\37\177\\\"");
3019 if (($str == $encoded) and !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
3023 return "\"$encoded\"";
3025 $matchcount = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
3027 /* @noinspection PhpMissingBreakStatementInspection */
3029 $matchcount = preg_match_all('/[()"]/', $str, $matches);
3033 $matchcount +
= preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
3037 //RFCs specify a maximum line length of 78 chars, however mail() will sometimes
3038 //corrupt messages with headers longer than 65 chars. See #818
3039 $lengthsub = 'mail' == $this->Mailer ?
13 : 0;
3040 $maxlen = static::STD_LINE_LENGTH
- $lengthsub;
3041 // Try to select the encoding which should produce the shortest output
3042 if ($matchcount > strlen($str) / 3) {
3043 // More than a third of the content will need encoding, so B encoding will be most efficient
3045 //This calculation is:
3047 // - shorten to avoid mail() corruption
3048 // - Q/B encoding char overhead ("` =?<charset>?[QB]?<content>?=`")
3049 // - charset name length
3050 $maxlen = static::STD_LINE_LENGTH
- $lengthsub - 8 - strlen($this->CharSet
);
3051 if ($this->hasMultiBytes($str)) {
3052 // Use a custom function which correctly encodes and wraps long
3053 // multibyte strings without breaking lines within a character
3054 $encoded = $this->base64EncodeWrapMB($str, "\n");
3056 $encoded = base64_encode($str);
3057 $maxlen -= $maxlen %
4;
3058 $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
3060 $encoded = preg_replace('/^(.*)$/m', ' =?' . $this->CharSet
. "?$encoding?\\1?=", $encoded);
3061 } elseif ($matchcount > 0) {
3062 //1 or more chars need encoding, use Q-encode
3064 //Recalc max line length for Q encoding - see comments on B encode
3065 $maxlen = static::STD_LINE_LENGTH
- $lengthsub - 8 - strlen($this->CharSet
);
3066 $encoded = $this->encodeQ($str, $position);
3067 $encoded = $this->wrapText($encoded, $maxlen, true);
3068 $encoded = str_replace('=' . static::$LE, "\n", trim($encoded));
3069 $encoded = preg_replace('/^(.*)$/m', ' =?' . $this->CharSet
. "?$encoding?\\1?=", $encoded);
3070 } elseif (strlen($str) > $maxlen) {
3071 //No chars need encoding, but line is too long, so fold it
3072 $encoded = trim($this->wrapText($str, $maxlen, false));
3073 if ($str == $encoded) {
3074 //Wrapping nicely didn't work, wrap hard instead
3075 $encoded = trim(chunk_split($str, static::STD_LINE_LENGTH
, static::$LE));
3077 $encoded = str_replace(static::$LE, "\n", trim($encoded));
3078 $encoded = preg_replace('/^(.*)$/m', ' \\1', $encoded);
3080 //No reformatting needed
3084 return trim(static::normalizeBreaks($encoded));
3088 * Check if a string contains multi-byte characters.
3090 * @param string $str multi-byte text to wrap encode
3094 public function hasMultiBytes($str)
3096 if (function_exists('mb_strlen')) {
3097 return strlen($str) > mb_strlen($str, $this->CharSet
);
3100 // Assume no multibytes (we can't handle without mbstring functions anyway)
3105 * Does a string contain any 8-bit chars (in any charset)?
3107 * @param string $text
3111 public function has8bitChars($text)
3113 return (bool) preg_match('/[\x80-\xFF]/', $text);
3117 * Encode and wrap long multibyte strings for mail headers
3118 * without breaking lines within a character.
3119 * Adapted from a function by paravoid.
3121 * @see http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283
3123 * @param string $str multi-byte text to wrap encode
3124 * @param string $linebreak string to use as linefeed/end-of-line
3128 public function base64EncodeWrapMB($str, $linebreak = null)
3130 $start = '=?' . $this->CharSet
. '?B?';
3133 if (null === $linebreak) {
3134 $linebreak = static::$LE;
3137 $mb_length = mb_strlen($str, $this->CharSet
);
3138 // Each line must have length <= 75, including $start and $end
3139 $length = 75 - strlen($start) - strlen($end);
3140 // Average multi-byte ratio
3141 $ratio = $mb_length / strlen($str);
3142 // Base64 has a 4:3 ratio
3143 $avgLength = floor($length * $ratio * .75);
3145 for ($i = 0; $i < $mb_length; $i +
= $offset) {
3148 $offset = $avgLength - $lookBack;
3149 $chunk = mb_substr($str, $i, $offset, $this->CharSet
);
3150 $chunk = base64_encode($chunk);
3152 } while (strlen($chunk) > $length);
3153 $encoded .= $chunk . $linebreak;
3156 // Chomp the last linefeed
3157 return substr($encoded, 0, -strlen($linebreak));
3161 * Encode a string in quoted-printable format.
3162 * According to RFC2045 section 6.7.
3164 * @param string $string The text to encode
3168 public function encodeQP($string)
3170 return static::normalizeBreaks(quoted_printable_encode($string));
3174 * Encode a string using Q encoding.
3176 * @see http://tools.ietf.org/html/rfc2047#section-4.2
3178 * @param string $str the text to encode
3179 * @param string $position Where the text is going to be used, see the RFC for what that means
3183 public function encodeQ($str, $position = 'text')
3185 // There should not be any EOL in the string
3187 $encoded = str_replace(["\r", "\n"], '', $str);
3188 switch (strtolower($position)) {
3190 // RFC 2047 section 5.3
3191 $pattern = '^A-Za-z0-9!*+\/ -';
3194 * RFC 2047 section 5.2.
3195 * Build $pattern without including delimiters and []
3197 /* @noinspection PhpMissingBreakStatementInspection */
3200 /* Intentional fall through */
3203 // RFC 2047 section 5.1
3204 // Replace every high ascii, control, =, ? and _ characters
3205 /** @noinspection SuspiciousAssignmentsInspection */
3206 $pattern = '\000-\011\013\014\016-\037\075\077\137\177-\377' . $pattern;
3210 if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) {
3211 // If the string contains an '=', make sure it's the first thing we replace
3212 // so as to avoid double-encoding
3213 $eqkey = array_search('=', $matches[0]);
3214 if (false !== $eqkey) {
3215 unset($matches[0][$eqkey]);
3216 array_unshift($matches[0], '=');
3218 foreach (array_unique($matches[0]) as $char) {
3219 $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded);
3222 // Replace spaces with _ (more readable than =20)
3223 // RFC 2047 section 4.2(2)
3224 return str_replace(' ', '_', $encoded);
3228 * Add a string or binary attachment (non-filesystem).
3229 * This method can be used to attach ascii or binary data,
3230 * such as a BLOB record from a database.
3232 * @param string $string String attachment data
3233 * @param string $filename Name of the attachment
3234 * @param string $encoding File encoding (see $Encoding)
3235 * @param string $type File extension (MIME) type
3236 * @param string $disposition Disposition to use
3238 public function addStringAttachment(
3241 $encoding = 'base64',
3243 $disposition = 'attachment'
3245 // If a MIME type is not specified, try to work it out from the file name
3247 $type = static::filenameToType($filename);
3249 // Append to $attachment array
3250 $this->attachment
[] = [
3253 2 => basename($filename),
3256 5 => true, // isStringAttachment
3263 * Add an embedded (inline) attachment from a file.
3264 * This can include images, sounds, and just about any other document type.
3265 * These differ from 'regular' attachments in that they are intended to be
3266 * displayed inline with the message, not just attached for download.
3267 * This is used in HTML messages that embed the images
3268 * the HTML refers to using the $cid value.
3269 * Never use a user-supplied path to a file!
3271 * @param string $path Path to the attachment
3272 * @param string $cid Content ID of the attachment; Use this to reference
3273 * the content when using an embedded image in HTML
3274 * @param string $name Overrides the attachment name
3275 * @param string $encoding File encoding (see $Encoding)
3276 * @param string $type File MIME type
3277 * @param string $disposition Disposition to use
3279 * @return bool True on successfully adding an attachment
3281 public function addEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = '', $disposition = 'inline')
3283 if (!@is_file
($path)) {
3284 $this->setError($this->lang('file_access') . $path);
3289 // If a MIME type is not specified, try to work it out from the file name
3291 $type = static::filenameToType($path);
3294 $filename = basename($path);
3299 // Append to $attachment array
3300 $this->attachment
[] = [
3306 5 => false, // isStringAttachment
3315 * Add an embedded stringified attachment.
3316 * This can include images, sounds, and just about any other document type.
3317 * If your filename doesn't contain an extension, be sure to set the $type to an appropriate MIME type.
3319 * @param string $string The attachment binary data
3320 * @param string $cid Content ID of the attachment; Use this to reference
3321 * the content when using an embedded image in HTML
3322 * @param string $name A filename for the attachment. If this contains an extension,
3323 * PHPMailer will attempt to set a MIME type for the attachment.
3324 * For example 'file.jpg' would get an 'image/jpeg' MIME type.
3325 * @param string $encoding File encoding (see $Encoding), defaults to 'base64'
3326 * @param string $type MIME type - will be used in preference to any automatically derived type
3327 * @param string $disposition Disposition to use
3329 * @return bool True on successfully adding an attachment
3331 public function addStringEmbeddedImage(
3335 $encoding = 'base64',
3337 $disposition = 'inline'
3339 // If a MIME type is not specified, try to work it out from the name
3340 if ('' == $type and !empty($name)) {
3341 $type = static::filenameToType($name);
3344 // Append to $attachment array
3345 $this->attachment
[] = [
3351 5 => true, // isStringAttachment
3360 * Check if an embedded attachment is present with this cid.
3362 * @param string $cid
3366 protected function cidExists($cid)
3368 foreach ($this->attachment
as $attachment) {
3369 if ('inline' == $attachment[6] and $cid == $attachment[7]) {
3378 * Check if an inline attachment is present.
3382 public function inlineImageExists()
3384 foreach ($this->attachment
as $attachment) {
3385 if ('inline' == $attachment[6]) {
3394 * Check if an attachment (non-inline) is present.
3398 public function attachmentExists()
3400 foreach ($this->attachment
as $attachment) {
3401 if ('attachment' == $attachment[6]) {
3410 * Check if this message has an alternative body set.
3414 public function alternativeExists()
3416 return !empty($this->AltBody
);
3420 * Clear queued addresses of given kind.
3422 * @param string $kind 'to', 'cc', or 'bcc'
3424 public function clearQueuedAddresses($kind)
3426 $this->RecipientsQueue
= array_filter(
3427 $this->RecipientsQueue
,
3428 function ($params) use ($kind) {
3429 return $params[0] != $kind;
3435 * Clear all To recipients.
3437 public function clearAddresses()
3439 foreach ($this->to
as $to) {
3440 unset($this->all_recipients
[strtolower($to[0])]);
3443 $this->clearQueuedAddresses('to');
3447 * Clear all CC recipients.
3449 public function clearCCs()
3451 foreach ($this->cc
as $cc) {
3452 unset($this->all_recipients
[strtolower($cc[0])]);
3455 $this->clearQueuedAddresses('cc');
3459 * Clear all BCC recipients.
3461 public function clearBCCs()
3463 foreach ($this->bcc
as $bcc) {
3464 unset($this->all_recipients
[strtolower($bcc[0])]);
3467 $this->clearQueuedAddresses('bcc');
3471 * Clear all ReplyTo recipients.
3473 public function clearReplyTos()
3475 $this->ReplyTo
= [];
3476 $this->ReplyToQueue
= [];
3480 * Clear all recipient types.
3482 public function clearAllRecipients()
3487 $this->all_recipients
= [];
3488 $this->RecipientsQueue
= [];
3492 * Clear all filesystem, string, and binary attachments.
3494 public function clearAttachments()
3496 $this->attachment
= [];
3500 * Clear all custom headers.
3502 public function clearCustomHeaders()
3504 $this->CustomHeader
= [];
3508 * Add an error message to the error container.
3510 * @param string $msg
3512 protected function setError($msg)
3514 ++
$this->error_count
;
3515 if ('smtp' == $this->Mailer
and null !== $this->smtp
) {
3516 $lasterror = $this->smtp
->getError();
3517 if (!empty($lasterror['error'])) {
3518 $msg .= $this->lang('smtp_error') . $lasterror['error'];
3519 if (!empty($lasterror['detail'])) {
3520 $msg .= ' Detail: ' . $lasterror['detail'];
3522 if (!empty($lasterror['smtp_code'])) {
3523 $msg .= ' SMTP code: ' . $lasterror['smtp_code'];
3525 if (!empty($lasterror['smtp_code_ex'])) {
3526 $msg .= ' Additional SMTP info: ' . $lasterror['smtp_code_ex'];
3530 $this->ErrorInfo
= $msg;
3534 * Return an RFC 822 formatted date.
3538 public static function rfcDate()
3540 // Set the time zone to whatever the default is to avoid 500 errors
3541 // Will default to UTC if it's not set properly in php.ini
3542 date_default_timezone_set(@date_default_timezone_get
());
3544 return date('D, j M Y H:i:s O');
3548 * Get the server hostname.
3549 * Returns 'localhost.localdomain' if unknown.
3553 protected function serverHostname()
3556 if (!empty($this->Hostname
)) {
3557 $result = $this->Hostname
;
3558 } elseif (isset($_SERVER) and array_key_exists('SERVER_NAME', $_SERVER)) {
3559 $result = $_SERVER['SERVER_NAME'];
3560 } elseif (function_exists('gethostname') and gethostname() !== false) {
3561 $result = gethostname();
3562 } elseif (php_uname('n') !== false) {
3563 $result = php_uname('n');
3565 if (!static::isValidHost($result)) {
3566 return 'localhost.localdomain';
3573 * Validate whether a string contains a valid value to use as a hostname or IP address.
3574 * IPv6 addresses must include [], e.g. `[::1]`, not just `::1`.
3576 * @param string $host The host name or IP address to check
3580 public static function isValidHost($host)
3582 //Simple syntax limits
3584 or !is_string($host)
3585 or strlen($host) > 256
3589 //Looks like a bracketed IPv6 address
3590 if (trim($host, '[]') != $host) {
3591 return (bool) filter_var(trim($host, '[]'), FILTER_VALIDATE_IP
, FILTER_FLAG_IPV6
);
3593 //If removing all the dots results in a numeric string, it must be an IPv4 address.
3594 //Need to check this first because otherwise things like `999.0.0.0` are considered valid host names
3595 if (is_numeric(str_replace('.', '', $host))) {
3596 //Is it a valid IPv4 address?
3597 return (bool) filter_var($host, FILTER_VALIDATE_IP
, FILTER_FLAG_IPV4
);
3599 if (filter_var('http://' . $host, FILTER_VALIDATE_URL
, FILTER_FLAG_HOST_REQUIRED
)) {
3600 //Is it a syntactically valid hostname?
3608 * Get an error message in the current language.
3610 * @param string $key
3614 protected function lang($key)
3616 if (count($this->language
) < 1) {
3617 $this->setLanguage('en'); // set the default language
3620 if (array_key_exists($key, $this->language
)) {
3621 if ('smtp_connect_failed' == $key) {
3622 //Include a link to troubleshooting docs on SMTP connection failure
3623 //this is by far the biggest cause of support questions
3624 //but it's usually not PHPMailer's fault.
3625 return $this->language
[$key] . ' https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting';
3628 return $this->language
[$key];
3631 //Return the key as a fallback
3636 * Check if an error occurred.
3638 * @return bool True if an error did occur
3640 public function isError()
3642 return $this->error_count
> 0;
3646 * Add a custom header.
3647 * $name value can be overloaded to contain
3648 * both header name and value (name:value).
3650 * @param string $name Custom header name
3651 * @param string|null $value Header value
3653 public function addCustomHeader($name, $value = null)
3655 if (null === $value) {
3656 // Value passed in as name:value
3657 $this->CustomHeader
[] = explode(':', $name, 2);
3659 $this->CustomHeader
[] = [$name, $value];
3664 * Returns all custom headers.
3668 public function getCustomHeaders()
3670 return $this->CustomHeader
;
3674 * Create a message body from an HTML string.
3675 * Automatically inlines images and creates a plain-text version by converting the HTML,
3676 * overwriting any existing values in Body and AltBody.
3677 * Do not source $message content from user input!
3678 * $basedir is prepended when handling relative URLs, e.g. <img src="/images/a.png"> and must not be empty
3679 * will look for an image file in $basedir/images/a.png and convert it to inline.
3680 * If you don't provide a $basedir, relative paths will be left untouched (and thus probably break in email)
3681 * Converts data-uri images into embedded attachments.
3682 * If you don't want to apply these transformations to your HTML, just set Body and AltBody directly.
3684 * @param string $message HTML message string
3685 * @param string $basedir Absolute path to a base directory to prepend to relative paths to images
3686 * @param bool|callable $advanced Whether to use the internal HTML to text converter
3687 * or your own custom converter @see PHPMailer::html2text()
3689 * @return string $message The transformed message Body
3691 public function msgHTML($message, $basedir = '', $advanced = false)
3693 preg_match_all('/(src|background)=["\'](.*)["\']/Ui', $message, $images);
3694 if (array_key_exists(2, $images)) {
3695 if (strlen($basedir) > 1 && '/' != substr($basedir, -1)) {
3696 // Ensure $basedir has a trailing /
3699 foreach ($images[2] as $imgindex => $url) {
3700 // Convert data URIs into embedded images
3701 //e.g. "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="
3702 if (preg_match('#^data:(image/(?:jpe?g|gif|png));?(base64)?,(.+)#', $url, $match)) {
3703 if (count($match) == 4 and 'base64' == $match[2]) {
3704 $data = base64_decode($match[3]);
3705 } elseif ('' == $match[2]) {
3706 $data = rawurldecode($match[3]);
3708 //Not recognised so leave it alone
3711 //Hash the decoded data, not the URL so that the same data-URI image used in multiple places
3712 //will only be embedded once, even if it used a different encoding
3713 $cid = hash('sha256', $data) . '@phpmailer.0'; // RFC2392 S 2
3715 if (!$this->cidExists($cid)) {
3716 $this->addStringEmbeddedImage($data, $cid, 'embed' . $imgindex, 'base64', $match[1]);
3718 $message = str_replace(
3719 $images[0][$imgindex],
3720 $images[1][$imgindex] . '="cid:' . $cid . '"',
3725 if (// Only process relative URLs if a basedir is provided (i.e. no absolute local paths)
3727 // Ignore URLs containing parent dir traversal (..)
3728 and (strpos($url, '..') === false)
3729 // Do not change urls that are already inline images
3730 and 0 !== strpos($url, 'cid:')
3731 // Do not change absolute URLs, including anonymous protocol
3732 and !preg_match('#^[a-z][a-z0-9+.-]*:?//#i', $url)
3734 $filename = basename($url);
3735 $directory = dirname($url);
3736 if ('.' == $directory) {
3739 $cid = hash('sha256', $url) . '@phpmailer.0'; // RFC2392 S 2
3740 if (strlen($basedir) > 1 and '/' != substr($basedir, -1)) {
3743 if (strlen($directory) > 1 and '/' != substr($directory, -1)) {
3746 if ($this->addEmbeddedImage(
3747 $basedir . $directory . $filename,
3751 static::_mime_types((string) static::mb_pathinfo($filename, PATHINFO_EXTENSION
))
3754 $message = preg_replace(
3755 '/' . $images[1][$imgindex] . '=["\']' . preg_quote($url, '/') . '["\']/Ui',
3756 $images[1][$imgindex] . '="cid:' . $cid . '"',
3763 $this->isHTML(true);
3764 // Convert all message body line breaks to LE, makes quoted-printable encoding work much better
3765 $this->Body
= static::normalizeBreaks($message);
3766 $this->AltBody
= static::normalizeBreaks($this->html2text($message, $advanced));
3767 if (!$this->alternativeExists()) {
3768 $this->AltBody
= 'This is an HTML-only message. To view it, activate HTML in your email application.'
3776 * Convert an HTML string into plain text.
3777 * This is used by msgHTML().
3778 * Note - older versions of this function used a bundled advanced converter
3779 * which was removed for license reasons in #232.
3783 * // Use default conversion
3784 * $plain = $mail->html2text($html);
3785 * // Use your own custom converter
3786 * $plain = $mail->html2text($html, function($html) {
3787 * $converter = new MyHtml2text($html);
3788 * return $converter->get_text();
3792 * @param string $html The HTML text to convert
3793 * @param bool|callable $advanced Any boolean value to use the internal converter,
3794 * or provide your own callable for custom conversion
3798 public function html2text($html, $advanced = false)
3800 if (is_callable($advanced)) {
3801 return call_user_func($advanced, $html);
3804 return html_entity_decode(
3805 trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/si', '', $html))),
3812 * Get the MIME type for a file extension.
3814 * @param string $ext File extension
3816 * @return string MIME type of file
3818 public static function _mime_types($ext = '')
3821 'xl' => 'application/excel',
3822 'js' => 'application/javascript',
3823 'hqx' => 'application/mac-binhex40',
3824 'cpt' => 'application/mac-compactpro',
3825 'bin' => 'application/macbinary',
3826 'doc' => 'application/msword',
3827 'word' => 'application/msword',
3828 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
3829 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
3830 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
3831 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
3832 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
3833 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
3834 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
3835 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
3836 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
3837 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
3838 'class' => 'application/octet-stream',
3839 'dll' => 'application/octet-stream',
3840 'dms' => 'application/octet-stream',
3841 'exe' => 'application/octet-stream',
3842 'lha' => 'application/octet-stream',
3843 'lzh' => 'application/octet-stream',
3844 'psd' => 'application/octet-stream',
3845 'sea' => 'application/octet-stream',
3846 'so' => 'application/octet-stream',
3847 'oda' => 'application/oda',
3848 'pdf' => 'application/pdf',
3849 'ai' => 'application/postscript',
3850 'eps' => 'application/postscript',
3851 'ps' => 'application/postscript',
3852 'smi' => 'application/smil',
3853 'smil' => 'application/smil',
3854 'mif' => 'application/vnd.mif',
3855 'xls' => 'application/vnd.ms-excel',
3856 'ppt' => 'application/vnd.ms-powerpoint',
3857 'wbxml' => 'application/vnd.wap.wbxml',
3858 'wmlc' => 'application/vnd.wap.wmlc',
3859 'dcr' => 'application/x-director',
3860 'dir' => 'application/x-director',
3861 'dxr' => 'application/x-director',
3862 'dvi' => 'application/x-dvi',
3863 'gtar' => 'application/x-gtar',
3864 'php3' => 'application/x-httpd-php',
3865 'php4' => 'application/x-httpd-php',
3866 'php' => 'application/x-httpd-php',
3867 'phtml' => 'application/x-httpd-php',
3868 'phps' => 'application/x-httpd-php-source',
3869 'swf' => 'application/x-shockwave-flash',
3870 'sit' => 'application/x-stuffit',
3871 'tar' => 'application/x-tar',
3872 'tgz' => 'application/x-tar',
3873 'xht' => 'application/xhtml+xml',
3874 'xhtml' => 'application/xhtml+xml',
3875 'zip' => 'application/zip',
3876 'mid' => 'audio/midi',
3877 'midi' => 'audio/midi',
3878 'mp2' => 'audio/mpeg',
3879 'mp3' => 'audio/mpeg',
3880 'm4a' => 'audio/mp4',
3881 'mpga' => 'audio/mpeg',
3882 'aif' => 'audio/x-aiff',
3883 'aifc' => 'audio/x-aiff',
3884 'aiff' => 'audio/x-aiff',
3885 'ram' => 'audio/x-pn-realaudio',
3886 'rm' => 'audio/x-pn-realaudio',
3887 'rpm' => 'audio/x-pn-realaudio-plugin',
3888 'ra' => 'audio/x-realaudio',
3889 'wav' => 'audio/x-wav',
3890 'mka' => 'audio/x-matroska',
3891 'bmp' => 'image/bmp',
3892 'gif' => 'image/gif',
3893 'jpeg' => 'image/jpeg',
3894 'jpe' => 'image/jpeg',
3895 'jpg' => 'image/jpeg',
3896 'png' => 'image/png',
3897 'tiff' => 'image/tiff',
3898 'tif' => 'image/tiff',
3899 'webp' => 'image/webp',
3900 'heif' => 'image/heif',
3901 'heifs' => 'image/heif-sequence',
3902 'heic' => 'image/heic',
3903 'heics' => 'image/heic-sequence',
3904 'eml' => 'message/rfc822',
3905 'css' => 'text/css',
3906 'html' => 'text/html',
3907 'htm' => 'text/html',
3908 'shtml' => 'text/html',
3909 'log' => 'text/plain',
3910 'text' => 'text/plain',
3911 'txt' => 'text/plain',
3912 'rtx' => 'text/richtext',
3913 'rtf' => 'text/rtf',
3914 'vcf' => 'text/vcard',
3915 'vcard' => 'text/vcard',
3916 'ics' => 'text/calendar',
3917 'xml' => 'text/xml',
3918 'xsl' => 'text/xml',
3919 'wmv' => 'video/x-ms-wmv',
3920 'mpeg' => 'video/mpeg',
3921 'mpe' => 'video/mpeg',
3922 'mpg' => 'video/mpeg',
3923 'mp4' => 'video/mp4',
3924 'm4v' => 'video/mp4',
3925 'mov' => 'video/quicktime',
3926 'qt' => 'video/quicktime',
3927 'rv' => 'video/vnd.rn-realvideo',
3928 'avi' => 'video/x-msvideo',
3929 'movie' => 'video/x-sgi-movie',
3930 'webm' => 'video/webm',
3931 'mkv' => 'video/x-matroska',
3933 $ext = strtolower($ext);
3934 if (array_key_exists($ext, $mimes)) {
3935 return $mimes[$ext];
3938 return 'application/octet-stream';
3942 * Map a file name to a MIME type.
3943 * Defaults to 'application/octet-stream', i.e.. arbitrary binary data.
3945 * @param string $filename A file name or full path, does not need to exist as a file
3949 public static function filenameToType($filename)
3951 // In case the path is a URL, strip any query string before getting extension
3952 $qpos = strpos($filename, '?');
3953 if (false !== $qpos) {
3954 $filename = substr($filename, 0, $qpos);
3956 $ext = static::mb_pathinfo($filename, PATHINFO_EXTENSION
);
3958 return static::_mime_types($ext);
3962 * Multi-byte-safe pathinfo replacement.
3963 * Drop-in replacement for pathinfo(), but multibyte- and cross-platform-safe.
3965 * @see http://www.php.net/manual/en/function.pathinfo.php#107461
3967 * @param string $path A filename or path, does not need to exist as a file
3968 * @param int|string $options Either a PATHINFO_* constant,
3969 * or a string name to return only the specified piece
3971 * @return string|array
3973 public static function mb_pathinfo($path, $options = null)
3975 $ret = ['dirname' => '', 'basename' => '', 'extension' => '', 'filename' => ''];
3977 if (preg_match('#^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^\.\\\\/]+?)|))[\\\\/\.]*$#im', $path, $pathinfo)) {
3978 if (array_key_exists(1, $pathinfo)) {
3979 $ret['dirname'] = $pathinfo[1];
3981 if (array_key_exists(2, $pathinfo)) {
3982 $ret['basename'] = $pathinfo[2];
3984 if (array_key_exists(5, $pathinfo)) {
3985 $ret['extension'] = $pathinfo[5];
3987 if (array_key_exists(3, $pathinfo)) {
3988 $ret['filename'] = $pathinfo[3];
3992 case PATHINFO_DIRNAME
:
3994 return $ret['dirname'];
3995 case PATHINFO_BASENAME
:
3997 return $ret['basename'];
3998 case PATHINFO_EXTENSION
:
4000 return $ret['extension'];
4001 case PATHINFO_FILENAME
:
4003 return $ret['filename'];
4010 * Set or reset instance properties.
4011 * You should avoid this function - it's more verbose, less efficient, more error-prone and
4012 * harder to debug than setting properties directly.
4014 * `$mail->set('SMTPSecure', 'tls');`
4016 * `$mail->SMTPSecure = 'tls';`.
4018 * @param string $name The property name to set
4019 * @param mixed $value The value to set the property to
4023 public function set($name, $value = '')
4025 if (property_exists($this, $name)) {
4026 $this->$name = $value;
4030 $this->setError($this->lang('variable_set') . $name);
4036 * Strip newlines to prevent header injection.
4038 * @param string $str
4042 public function secureHeader($str)
4044 return trim(str_replace(["\r", "\n"], '', $str));
4048 * Normalize line breaks in a string.
4049 * Converts UNIX LF, Mac CR and Windows CRLF line breaks into a single line break format.
4050 * Defaults to CRLF (for message bodies) and preserves consecutive breaks.
4052 * @param string $text
4053 * @param string $breaktype What kind of line break to use; defaults to static::$LE
4057 public static function normalizeBreaks($text, $breaktype = null)
4059 if (null === $breaktype) {
4060 $breaktype = static::$LE;
4063 $text = str_replace(["\r\n", "\r"], "\n", $text);
4064 // Now convert LE as needed
4065 if ("\n" !== $breaktype) {
4066 $text = str_replace("\n", $breaktype, $text);
4073 * Return the current line break format string.
4077 public static function getLE()
4083 * Set the line break format string, e.g. "\r\n".
4087 protected static function setLE($le)
4093 * Set the public and private key files and password for S/MIME signing.
4095 * @param string $cert_filename
4096 * @param string $key_filename
4097 * @param string $key_pass Password for private key
4098 * @param string $extracerts_filename Optional path to chain certificate
4100 public function sign($cert_filename, $key_filename, $key_pass, $extracerts_filename = '')
4102 $this->sign_cert_file
= $cert_filename;
4103 $this->sign_key_file
= $key_filename;
4104 $this->sign_key_pass
= $key_pass;
4105 $this->sign_extracerts_file
= $extracerts_filename;
4109 * Quoted-Printable-encode a DKIM header.
4111 * @param string $txt
4115 public function DKIM_QP($txt)
4118 $len = strlen($txt);
4119 for ($i = 0; $i < $len; ++
$i) {
4120 $ord = ord($txt[$i]);
4121 if (((0x21 <= $ord) and ($ord <= 0x3A)) or $ord == 0x3C or ((0x3E <= $ord) and ($ord <= 0x7E))) {
4124 $line .= '=' . sprintf('%02X', $ord);
4132 * Generate a DKIM signature.
4134 * @param string $signHeader
4138 * @return string The DKIM signature value
4140 public function DKIM_Sign($signHeader)
4142 if (!defined('PKCS7_TEXT')) {
4143 if ($this->exceptions
) {
4144 throw new Exception($this->lang('extension_missing') . 'openssl');
4149 $privKeyStr = !empty($this->DKIM_private_string
) ?
4150 $this->DKIM_private_string
:
4151 file_get_contents($this->DKIM_private
);
4152 if ('' != $this->DKIM_passphrase
) {
4153 $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase
);
4155 $privKey = openssl_pkey_get_private($privKeyStr);
4157 if (openssl_sign($signHeader, $signature, $privKey, 'sha256WithRSAEncryption')) {
4158 openssl_pkey_free($privKey);
4160 return base64_encode($signature);
4162 openssl_pkey_free($privKey);
4168 * Generate a DKIM canonicalization header.
4169 * Uses the 'relaxed' algorithm from RFC6376 section 3.4.2.
4170 * Canonicalized headers should *always* use CRLF, regardless of mailer setting.
4172 * @see https://tools.ietf.org/html/rfc6376#section-3.4.2
4174 * @param string $signHeader Header
4178 public function DKIM_HeaderC($signHeader)
4180 //Unfold all header continuation lines
4181 //Also collapses folded whitespace.
4182 //Note PCRE \s is too broad a definition of whitespace; RFC5322 defines it as `[ \t]`
4183 //@see https://tools.ietf.org/html/rfc5322#section-2.2
4184 //That means this may break if you do something daft like put vertical tabs in your headers.
4185 $signHeader = preg_replace('/\r\n[ \t]+/', ' ', $signHeader);
4186 $lines = explode("\r\n", $signHeader);
4187 foreach ($lines as $key => $line) {
4188 //If the header is missing a :, skip it as it's invalid
4189 //This is likely to happen because the explode() above will also split
4190 //on the trailing LE, leaving an empty line
4191 if (strpos($line, ':') === false) {
4194 list($heading, $value) = explode(':', $line, 2);
4195 //Lower-case header name
4196 $heading = strtolower($heading);
4197 //Collapse white space within the value
4198 $value = preg_replace('/[ \t]{2,}/', ' ', $value);
4199 //RFC6376 is slightly unclear here - it says to delete space at the *end* of each value
4200 //But then says to delete space before and after the colon.
4201 //Net result is the same as trimming both ends of the value.
4202 //by elimination, the same applies to the field name
4203 $lines[$key] = trim($heading, " \t") . ':' . trim($value, " \t");
4206 return implode("\r\n", $lines);
4210 * Generate a DKIM canonicalization body.
4211 * Uses the 'simple' algorithm from RFC6376 section 3.4.3.
4212 * Canonicalized bodies should *always* use CRLF, regardless of mailer setting.
4214 * @see https://tools.ietf.org/html/rfc6376#section-3.4.3
4216 * @param string $body Message Body
4220 public function DKIM_BodyC($body)
4225 // Normalize line endings to CRLF
4226 $body = static::normalizeBreaks($body, "\r\n");
4228 //Reduce multiple trailing line breaks to a single one
4229 return rtrim($body, "\r\n") . "\r\n";
4233 * Create the DKIM header and body in a new message header.
4235 * @param string $headers_line Header lines
4236 * @param string $subject Subject
4237 * @param string $body Body
4241 public function DKIM_Add($headers_line, $subject, $body)
4243 $DKIMsignatureType = 'rsa-sha256'; // Signature & hash algorithms
4244 $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body
4245 $DKIMquery = 'dns/txt'; // Query method
4246 $DKIMtime = time(); // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone)
4247 $subject_header = "Subject: $subject";
4248 $headers = explode(static::$LE, $headers_line);
4253 foreach ($headers as $header) {
4254 if (strpos($header, 'From:') === 0) {
4255 $from_header = $header;
4256 $current = 'from_header';
4257 } elseif (strpos($header, 'To:') === 0) {
4258 $to_header = $header;
4259 $current = 'to_header';
4260 } elseif (strpos($header, 'Date:') === 0) {
4261 $date_header = $header;
4262 $current = 'date_header';
4264 if (!empty($
$current) and strpos($header, ' =?') === 0) {
4265 $
$current .= $header;
4271 $from = str_replace('|', '=7C', $this->DKIM_QP($from_header));
4272 $to = str_replace('|', '=7C', $this->DKIM_QP($to_header));
4273 $date = str_replace('|', '=7C', $this->DKIM_QP($date_header));
4274 $subject = str_replace(
4277 $this->DKIM_QP($subject_header)
4278 ); // Copied header fields (dkim-quoted-printable)
4279 $body = $this->DKIM_BodyC($body);
4280 $DKIMlen = strlen($body); // Length of body
4281 $DKIMb64 = base64_encode(pack('H*', hash('sha256', $body))); // Base64 of packed binary SHA-256 hash of body
4282 if ('' == $this->DKIM_identity
) {
4285 $ident = ' i=' . $this->DKIM_identity
. ';';
4287 $dkimhdrs = 'DKIM-Signature: v=1; a=' .
4288 $DKIMsignatureType . '; q=' .
4289 $DKIMquery . '; l=' .
4291 $this->DKIM_selector
.
4293 "\tt=" . $DKIMtime . '; c=' . $DKIMcanonicalization . ";\r\n" .
4294 "\th=From:To:Date:Subject;\r\n" .
4295 "\td=" . $this->DKIM_domain
. ';' . $ident . "\r\n" .
4299 "\t|$subject;\r\n" .
4300 "\tbh=" . $DKIMb64 . ";\r\n" .
4302 $toSign = $this->DKIM_HeaderC(
4303 $from_header . "\r\n" .
4304 $to_header . "\r\n" .
4305 $date_header . "\r\n" .
4306 $subject_header . "\r\n" .
4309 $signed = $this->DKIM_Sign($toSign);
4311 return static::normalizeBreaks($dkimhdrs . $signed) . static::$LE;
4315 * Detect if a string contains a line longer than the maximum line length
4316 * allowed by RFC 2822 section 2.1.1.
4318 * @param string $str
4322 public static function hasLineLongerThanMax($str)
4324 return (bool) preg_match('/^(.{' . (self
::MAX_LINE_LENGTH +
strlen(static::$LE)) . ',})/m', $str);
4328 * Allows for public read access to 'to' property.
4329 * Before the send() call, queued addresses (i.e. with IDN) are not yet included.
4333 public function getToAddresses()
4339 * Allows for public read access to 'cc' property.
4340 * Before the send() call, queued addresses (i.e. with IDN) are not yet included.
4344 public function getCcAddresses()
4350 * Allows for public read access to 'bcc' property.
4351 * Before the send() call, queued addresses (i.e. with IDN) are not yet included.
4355 public function getBccAddresses()
4361 * Allows for public read access to 'ReplyTo' property.
4362 * Before the send() call, queued addresses (i.e. with IDN) are not yet included.
4366 public function getReplyToAddresses()
4368 return $this->ReplyTo
;
4372 * Allows for public read access to 'all_recipients' property.
4373 * Before the send() call, queued addresses (i.e. with IDN) are not yet included.
4377 public function getAllRecipientAddresses()
4379 return $this->all_recipients
;
4383 * Perform a callback.
4385 * @param bool $isSent
4389 * @param string $subject
4390 * @param string $body
4391 * @param string $from
4392 * @param array $extra
4394 protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body, $from, $extra)
4396 if (!empty($this->action_function
) and is_callable($this->action_function
)) {
4397 call_user_func($this->action_function
, $isSent, $to, $cc, $bcc, $subject, $body, $from, $extra);
4402 * Get the OAuth instance.
4406 public function getOAuth()
4408 return $this->oauth
;
4412 * Set an OAuth instance.
4414 * @param OAuth $oauth
4416 public function setOAuth(OAuth
$oauth)
4418 $this->oauth
= $oauth;