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.
40 public $Priority = null;
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.
317 protected $oauth = null;
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.
507 protected $smtp = null;
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.1';
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.
714 const STD_LINE_LENGTH = 78;
719 * @param bool $exceptions Should we throw external exceptions?
721 public function __construct($exceptions = null)
723 if (null !== $exceptions) {
724 $this->exceptions = (bool) $exceptions;
726 //Pick an appropriate debug output format automatically
727 $this->Debugoutput = (strpos(PHP_SAPI, 'cli') !== false ? 'echo' : 'html');
733 public function __destruct()
735 //Close any open SMTP connection nicely
740 * Call mail() in a safe_mode-aware fashion.
741 * Also, unless sendmail_path points to sendmail (or something that
742 * claims to be sendmail), don't pass params (not a perfect fix,
745 * @param string $to To
746 * @param string $subject Subject
747 * @param string $body Message Body
748 * @param string $header Additional Header(s)
749 * @param string|null $params Params
753 private function mailPassthru($to, $subject, $body, $header, $params)
755 //Check overloading of mail function to avoid double-encoding
756 if (ini_get('mbstring.func_overload') & 1) {
757 $subject = $this->secureHeader($subject);
759 $subject = $this->encodeHeader($this->secureHeader($subject));
761 //Calling mail() with null params breaks
762 if (!$this->UseSendmailOptions or null === $params) {
763 $result = @mail($to, $subject, $body, $header);
765 $result = @mail($to, $subject, $body, $header, $params);
772 * Output debugging info via user-defined method.
773 * Only generates output if SMTP debug output is enabled (@see SMTP::$do_debug).
775 * @see PHPMailer::$Debugoutput
776 * @see PHPMailer::$SMTPDebug
780 protected function edebug($str)
782 if ($this->SMTPDebug <= 0) {
785 //Is this a PSR-3 logger?
786 if (is_a($this->Debugoutput, 'Psr\Log\LoggerInterface')) {
787 $this->Debugoutput->debug($str);
791 //Avoid clash with built-in function names
792 if (!in_array($this->Debugoutput, ['error_log', 'html', 'echo']) and is_callable($this->Debugoutput)) {
793 call_user_func($this->Debugoutput, $str, $this->SMTPDebug);
797 switch ($this->Debugoutput) {
799 //Don't output, just log
803 //Cleans up output a bit for a better looking, HTML-safe output
805 preg_replace('/[\r\n]+/', '', $str),
812 //Normalize line breaks
813 $str = preg_replace('/\r\n|\r/ms', "\n", $str);
814 echo gmdate('Y-m-d H:i:s'),
816 //Trim trailing space
818 //Indent for readability, except for trailing break
830 * Sets message type to HTML or plain.
832 * @param bool $isHtml True for HTML mode
834 public function isHTML($isHtml = true)
837 $this->ContentType = 'text/html';
839 $this->ContentType = 'text/plain';
844 * Send messages using SMTP.
846 public function isSMTP()
848 $this->Mailer = 'smtp';
852 * Send messages using PHP's mail() function.
854 public function isMail()
856 $this->Mailer = 'mail';
860 * Send messages using $Sendmail.
862 public function isSendmail()
864 $ini_sendmail_path = ini_get('sendmail_path');
866 if (!stristr($ini_sendmail_path, 'sendmail')) {
867 $this->Sendmail = '/usr/sbin/sendmail';
869 $this->Sendmail = $ini_sendmail_path;
871 $this->Mailer = 'sendmail';
875 * Send messages using qmail.
877 public function isQmail()
879 $ini_sendmail_path = ini_get('sendmail_path');
881 if (!stristr($ini_sendmail_path, 'qmail')) {
882 $this->Sendmail = '/var/qmail/bin/qmail-inject';
884 $this->Sendmail = $ini_sendmail_path;
886 $this->Mailer = 'qmail';
890 * Add a "To" address.
892 * @param string $address The email address to send to
893 * @param string $name
895 * @return bool true on success, false if address already used or invalid in some way
897 public function addAddress($address, $name = '')
899 return $this->addOrEnqueueAnAddress('to', $address, $name);
903 * Add a "CC" address.
905 * @param string $address The email address to send to
906 * @param string $name
908 * @return bool true on success, false if address already used or invalid in some way
910 public function addCC($address, $name = '')
912 return $this->addOrEnqueueAnAddress('cc', $address, $name);
916 * Add a "BCC" address.
918 * @param string $address The email address to send to
919 * @param string $name
921 * @return bool true on success, false if address already used or invalid in some way
923 public function addBCC($address, $name = '')
925 return $this->addOrEnqueueAnAddress('bcc', $address, $name);
929 * Add a "Reply-To" address.
931 * @param string $address The email address to reply to
932 * @param string $name
934 * @return bool true on success, false if address already used or invalid in some way
936 public function addReplyTo($address, $name = '')
938 return $this->addOrEnqueueAnAddress('Reply-To', $address, $name);
942 * Add an address to one of the recipient arrays or to the ReplyTo array. Because PHPMailer
943 * can't validate addresses with an IDN without knowing the PHPMailer::$CharSet (that can still
944 * be modified after calling this function), addition of such addresses is delayed until send().
945 * Addresses that have been added already return false, but do not throw exceptions.
947 * @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo'
948 * @param string $address The email address to send, resp. to reply to
949 * @param string $name
953 * @return bool true on success, false if address already used or invalid in some way
955 protected function addOrEnqueueAnAddress($kind, $address, $name)
957 $address = trim($address);
958 $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
959 $pos = strrpos($address, '@');
960 if (false === $pos) {
961 // At-sign is missing.
962 $error_message = $this->lang('invalid_address') . " (addAnAddress $kind): $address";
963 $this->setError($error_message);
964 $this->edebug($error_message);
965 if ($this->exceptions) {
966 throw new Exception($error_message);
971 $params = [$kind, $address, $name];
972 // Enqueue addresses with IDN until we know the PHPMailer::$CharSet.
973 if ($this->has8bitChars(substr($address, ++$pos)) and $this->idnSupported()) {
974 if ('Reply-To' != $kind) {
975 if (!array_key_exists($address, $this->RecipientsQueue)) {
976 $this->RecipientsQueue[$address] = $params;
981 if (!array_key_exists($address, $this->ReplyToQueue)) {
982 $this->ReplyToQueue[$address] = $params;
991 // Immediately add standard addresses without IDN.
992 return call_user_func_array([$this, 'addAnAddress'], $params);
996 * Add an address to one of the recipient arrays or to the ReplyTo array.
997 * Addresses that have been added already return false, but do not throw exceptions.
999 * @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo'
1000 * @param string $address The email address to send, resp. to reply to
1001 * @param string $name
1005 * @return bool true on success, false if address already used or invalid in some way
1007 protected function addAnAddress($kind, $address, $name = '')
1009 if (!in_array($kind, ['to', 'cc', 'bcc', 'Reply-To'])) {
1010 $error_message = $this->lang('Invalid recipient kind: ') . $kind;
1011 $this->setError($error_message);
1012 $this->edebug($error_message);
1013 if ($this->exceptions) {
1014 throw new Exception($error_message);
1019 if (!static::validateAddress($address)) {
1020 $error_message = $this->lang('invalid_address') . " (addAnAddress $kind): $address";
1021 $this->setError($error_message);
1022 $this->edebug($error_message);
1023 if ($this->exceptions) {
1024 throw new Exception($error_message);
1029 if ('Reply-To' != $kind) {
1030 if (!array_key_exists(strtolower($address), $this->all_recipients)) {
1031 array_push($this->$kind, [$address, $name]);
1032 $this->all_recipients[strtolower($address)] = true;
1037 if (!array_key_exists(strtolower($address), $this->ReplyTo)) {
1038 $this->ReplyTo[strtolower($address)] = [$address, $name];
1048 * Parse and validate a string containing one or more RFC822-style comma-separated email addresses
1049 * of the form "display name <address>" into an array of name/address pairs.
1050 * Uses the imap_rfc822_parse_adrlist function if the IMAP extension is available.
1051 * Note that quotes in the name part are removed.
1053 * @see http://www.andrew.cmu.edu/user/agreen1/testing/mrbs/web/Mail/RFC822.php A more careful implementation
1055 * @param string $addrstr The address list string
1056 * @param bool $useimap Whether to use the IMAP extension to parse the list
1060 public static function parseAddresses($addrstr, $useimap = true)
1063 if ($useimap and function_exists('imap_rfc822_parse_adrlist')) {
1064 //Use this built-in parser if it's available
1065 $list = imap_rfc822_parse_adrlist($addrstr, '');
1066 foreach ($list as $address) {
1067 if ('.SYNTAX-ERROR.' != $address->host) {
1068 if (static::validateAddress($address->mailbox . '@' . $address->host)) {
1070 'name' => (property_exists($address, 'personal') ? $address->personal : ''),
1071 'address' => $address->mailbox . '@' . $address->host,
1077 //Use this simpler parser
1078 $list = explode(',', $addrstr);
1079 foreach ($list as $address) {
1080 $address = trim($address);
1081 //Is there a separate name part?
1082 if (strpos($address, '<') === false) {
1083 //No separate name, just use the whole thing
1084 if (static::validateAddress($address)) {
1087 'address' => $address,
1091 list($name, $email) = explode('<', $address);
1092 $email = trim(str_replace('>', '', $email));
1093 if (static::validateAddress($email)) {
1095 'name' => trim(str_replace(['"', "'"], '', $name)),
1096 'address' => $email,
1107 * Set the From and FromName properties.
1109 * @param string $address
1110 * @param string $name
1111 * @param bool $auto Whether to also set the Sender address, defaults to true
1117 public function setFrom($address, $name = '', $auto = true)
1119 $address = trim($address);
1120 $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
1121 // Don't validate now addresses with IDN. Will be done in send().
1122 $pos = strrpos($address, '@');
1123 if (false === $pos or
1124 (!$this->has8bitChars(substr($address, ++$pos)) or !$this->idnSupported()) and
1125 !static::validateAddress($address)) {
1126 $error_message = $this->lang('invalid_address') . " (setFrom) $address";
1127 $this->setError($error_message);
1128 $this->edebug($error_message);
1129 if ($this->exceptions) {
1130 throw new Exception($error_message);
1135 $this->From = $address;
1136 $this->FromName = $name;
1138 if (empty($this->Sender)) {
1139 $this->Sender = $address;
1147 * Return the Message-ID header of the last email.
1148 * Technically this is the value from the last time the headers were created,
1149 * but it's also the message ID of the last sent message except in
1150 * pathological cases.
1154 public function getLastMessageID()
1156 return $this->lastMessageID;
1160 * Check that a string looks like an email address.
1161 * Validation patterns supported:
1162 * * `auto` Pick best pattern automatically;
1163 * * `pcre8` Use the squiloople.com pattern, requires PCRE > 8.0;
1164 * * `pcre` Use old PCRE implementation;
1165 * * `php` Use PHP built-in FILTER_VALIDATE_EMAIL;
1166 * * `html5` Use the pattern given by the HTML5 spec for 'email' type form input elements.
1167 * * `noregex` Don't use a regex: super fast, really dumb.
1168 * Alternatively you may pass in a callable to inject your own validator, for example:
1171 * PHPMailer::validateAddress('user@example.com', function($address) {
1172 * return (strpos($address, '@') !== false);
1176 * You can also set the PHPMailer::$validator static to a callable, allowing built-in methods to use your validator.
1178 * @param string $address The email address to check
1179 * @param string|callable $patternselect Which pattern to use
1183 public static function validateAddress($address, $patternselect = null)
1185 if (null === $patternselect) {
1186 $patternselect = static::$validator;
1188 if (is_callable($patternselect)) {
1189 return call_user_func($patternselect, $address);
1191 //Reject line breaks in addresses; it's valid RFC5322, but not RFC5321
1192 if (strpos($address, "\n") !== false or strpos($address, "\r") !== false) {
1195 switch ($patternselect) {
1196 case 'pcre': //Kept for BC
1199 * A more complex and more permissive version of the RFC5322 regex on which FILTER_VALIDATE_EMAIL
1201 * In addition to the addresses allowed by filter_var, also permits:
1202 * * dotless domains: `a@b`
1203 * * comments: `1234 @ local(blah) .machine .example`
1204 * * quoted elements: `'"test blah"@example.org'`
1205 * * numeric TLDs: `a@b.123`
1206 * * unbracketed IPv4 literals: `a@192.168.0.1`
1207 * * IPv6 literals: 'first.last@[IPv6:a1::]'
1208 * Not all of these will necessarily work for sending!
1210 * @see http://squiloople.com/2009/12/20/email-address-validation/
1211 * @copyright 2009-2010 Michael Rushton
1212 * Feel free to use and redistribute this code. But please keep this copyright notice.
1214 return (bool) preg_match(
1215 '/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)' .
1216 '((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)' .
1217 '(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)' .
1218 '([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*' .
1219 '(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)' .
1220 '(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}' .
1221 '|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:' .
1222 '|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}' .
1223 '|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD',
1228 * This is the pattern used in the HTML5 spec for validation of 'email' type form input elements.
1230 * @see http://www.whatwg.org/specs/web-apps/current-work/#e-mail-state-(type=email)
1232 return (bool) preg_match(
1233 '/^[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}' .
1234 '[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/sD',
1239 return (bool) filter_var($address, FILTER_VALIDATE_EMAIL);
1244 * Tells whether IDNs (Internationalized Domain Names) are supported or not. This requires the
1245 * `intl` and `mbstring` PHP extensions.
1247 * @return bool `true` if required functions for IDN support are present
1249 public function idnSupported()
1251 return function_exists('idn_to_ascii') and function_exists('mb_convert_encoding');
1255 * Converts IDN in given email address to its ASCII form, also known as punycode, if possible.
1256 * Important: Address must be passed in same encoding as currently set in PHPMailer::$CharSet.
1257 * This function silently returns unmodified address if:
1258 * - No conversion is necessary (i.e. domain name is not an IDN, or is already in ASCII form)
1259 * - Conversion to punycode is impossible (e.g. required PHP functions are not available)
1260 * or fails for any reason (e.g. domain contains characters not allowed in an IDN).
1262 * @see PHPMailer::$CharSet
1264 * @param string $address The email address to convert
1266 * @return string The encoded address in ASCII form
1268 public function punyencodeAddress($address)
1270 // Verify we have required functions, CharSet, and at-sign.
1271 $pos = strrpos($address, '@');
1272 if ($this->idnSupported() and
1273 !empty($this->CharSet) and
1276 $domain = substr($address, ++$pos);
1277 // Verify CharSet string is a valid one, and domain properly encoded in this CharSet.
1278 if ($this->has8bitChars($domain) and @mb_check_encoding($domain, $this->CharSet)) {
1279 $domain = mb_convert_encoding($domain, 'UTF-8', $this->CharSet);
1280 //Ignore IDE complaints about this line - method signature changed in PHP 5.4
1282 $punycode = idn_to_ascii($domain, $errorcode, INTL_IDNA_VARIANT_UTS46);
1283 if (false !== $punycode) {
1284 return substr($address, 0, $pos) . $punycode;
1293 * Create a message and send it.
1294 * Uses the sending method specified by $Mailer.
1298 * @return bool false on error - See the ErrorInfo property for details of the error
1300 public function send()
1303 if (!$this->preSend()) {
1307 return $this->postSend();
1308 } catch (Exception $exc) {
1309 $this->mailHeader = '';
1310 $this->setError($exc->getMessage());
1311 if ($this->exceptions) {
1320 * Prepare a message for sending.
1326 public function preSend()
1328 if ('smtp' == $this->Mailer or
1329 ('mail' == $this->Mailer and stripos(PHP_OS, 'WIN') === 0)
1331 //SMTP mandates RFC-compliant line endings
1332 //and it's also used with mail() on Windows
1333 static::setLE("\r\n");
1335 //Maintain backward compatibility with legacy Linux command line mailers
1336 static::setLE(PHP_EOL);
1338 //Check for buggy PHP versions that add a header with an incorrect line break
1339 if (ini_get('mail.add_x_header') == 1
1340 and 'mail' == $this->Mailer
1341 and stripos(PHP_OS, 'WIN') === 0
1342 and ((version_compare(PHP_VERSION, '7.0.0', '>=')
1343 and version_compare(PHP_VERSION, '7.0.17', '<'))
1344 or (version_compare(PHP_VERSION, '7.1.0', '>=')
1345 and version_compare(PHP_VERSION, '7.1.3', '<')))
1348 'Your version of PHP is affected by a bug that may result in corrupted messages.' .
1349 ' To fix it, switch to sending using SMTP, disable the mail.add_x_header option in' .
1350 ' your php.ini, switch to MacOS or Linux, or upgrade your PHP to version 7.0.17+ or 7.1.3+.',
1356 $this->error_count = 0; // Reset errors
1357 $this->mailHeader = '';
1359 // Dequeue recipient and Reply-To addresses with IDN
1360 foreach (array_merge($this->RecipientsQueue, $this->ReplyToQueue) as $params) {
1361 $params[1] = $this->punyencodeAddress($params[1]);
1362 call_user_func_array([$this, 'addAnAddress'], $params);
1364 if (count($this->to) + count($this->cc) + count($this->bcc) < 1) {
1365 throw new Exception($this->lang('provide_address'), self::STOP_CRITICAL);
1368 // Validate From, Sender, and ConfirmReadingTo addresses
1369 foreach (['From', 'Sender', 'ConfirmReadingTo'] as $address_kind) {
1370 $this->$address_kind = trim($this->$address_kind);
1371 if (empty($this->$address_kind)) {
1374 $this->$address_kind = $this->punyencodeAddress($this->$address_kind);
1375 if (!static::validateAddress($this->$address_kind)) {
1376 $error_message = $this->lang('invalid_address') . ' (punyEncode) ' . $this->$address_kind;
1377 $this->setError($error_message);
1378 $this->edebug($error_message);
1379 if ($this->exceptions) {
1380 throw new Exception($error_message);
1387 // Set whether the message is multipart/alternative
1388 if ($this->alternativeExists()) {
1389 $this->ContentType = 'multipart/alternative';
1392 $this->setMessageType();
1393 // Refuse to send an empty message unless we are specifically allowing it
1394 if (!$this->AllowEmpty and empty($this->Body)) {
1395 throw new Exception($this->lang('empty_message'), self::STOP_CRITICAL);
1398 //Trim subject consistently
1399 $this->Subject = trim($this->Subject);
1400 // Create body before headers in case body makes changes to headers (e.g. altering transfer encoding)
1401 $this->MIMEHeader = '';
1402 $this->MIMEBody = $this->createBody();
1403 // createBody may have added some headers, so retain them
1404 $tempheaders = $this->MIMEHeader;
1405 $this->MIMEHeader = $this->createHeader();
1406 $this->MIMEHeader .= $tempheaders;
1408 // To capture the complete message when using mail(), create
1409 // an extra header list which createHeader() doesn't fold in
1410 if ('mail' == $this->Mailer) {
1411 if (count($this->to) > 0) {
1412 $this->mailHeader .= $this->addrAppend('To', $this->to);
1414 $this->mailHeader .= $this->headerLine('To', 'undisclosed-recipients:;');
1416 $this->mailHeader .= $this->headerLine(
1418 $this->encodeHeader($this->secureHeader($this->Subject))
1422 // Sign with DKIM if enabled
1423 if (!empty($this->DKIM_domain)
1424 and !empty($this->DKIM_selector)
1425 and (!empty($this->DKIM_private_string)
1426 or (!empty($this->DKIM_private) and file_exists($this->DKIM_private))
1429 $header_dkim = $this->DKIM_Add(
1430 $this->MIMEHeader . $this->mailHeader,
1431 $this->encodeHeader($this->secureHeader($this->Subject)),
1434 $this->MIMEHeader = rtrim($this->MIMEHeader, "\r\n ") . static::$LE .
1435 static::normalizeBreaks($header_dkim) . static::$LE;
1439 } catch (Exception $exc) {
1440 $this->setError($exc->getMessage());
1441 if ($this->exceptions) {
1450 * Actually send a message via the selected mechanism.
1456 public function postSend()
1459 // Choose the mailer and send through it
1460 switch ($this->Mailer) {
1463 return $this->sendmailSend($this->MIMEHeader, $this->MIMEBody);
1465 return $this->smtpSend($this->MIMEHeader, $this->MIMEBody);
1467 return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
1469 $sendMethod = $this->Mailer . 'Send';
1470 if (method_exists($this, $sendMethod)) {
1471 return $this->$sendMethod($this->MIMEHeader, $this->MIMEBody);
1474 return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
1476 } catch (Exception $exc) {
1477 $this->setError($exc->getMessage());
1478 $this->edebug($exc->getMessage());
1479 if ($this->exceptions) {
1488 * Send mail using the $Sendmail program.
1490 * @see PHPMailer::$Sendmail
1492 * @param string $header The message headers
1493 * @param string $body The message body
1499 protected function sendmailSend($header, $body)
1501 // CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped.
1502 if (!empty($this->Sender) and self::isShellSafe($this->Sender)) {
1503 if ('qmail' == $this->Mailer) {
1504 $sendmailFmt = '%s -f%s';
1506 $sendmailFmt = '%s -oi -f%s -t';
1509 if ('qmail' == $this->Mailer) {
1510 $sendmailFmt = '%s';
1512 $sendmailFmt = '%s -oi -t';
1516 $sendmail = sprintf($sendmailFmt, escapeshellcmd($this->Sendmail), $this->Sender);
1518 if ($this->SingleTo) {
1519 foreach ($this->SingleToArray as $toAddr) {
1520 $mail = @popen($sendmail, 'w');
1522 throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1524 fwrite($mail, 'To: ' . $toAddr . "\n");
1525 fwrite($mail, $header);
1526 fwrite($mail, $body);
1527 $result = pclose($mail);
1538 if (0 !== $result) {
1539 throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1543 $mail = @popen($sendmail, 'w');
1545 throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1547 fwrite($mail, $header);
1548 fwrite($mail, $body);
1549 $result = pclose($mail);
1560 if (0 !== $result) {
1561 throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1569 * Fix CVE-2016-10033 and CVE-2016-10045 by disallowing potentially unsafe shell characters.
1570 * Note that escapeshellarg and escapeshellcmd are inadequate for our purposes, especially on Windows.
1572 * @see https://github.com/PHPMailer/PHPMailer/issues/924 CVE-2016-10045 bug report
1574 * @param string $string The string to be validated
1578 protected static function isShellSafe($string)
1581 if (escapeshellcmd($string) !== $string
1582 or !in_array(escapeshellarg($string), ["'$string'", "\"$string\""])
1587 $length = strlen($string);
1589 for ($i = 0; $i < $length; ++$i) {
1592 // All other characters have a special meaning in at least one common shell, including = and +.
1593 // Full stop (.) has a special meaning in cmd.exe, but its impact should be negligible here.
1594 // Note that this does permit non-Latin alphanumeric characters based on the current locale.
1595 if (!ctype_alnum($c) && strpos('@_-.', $c) === false) {
1604 * Send mail using the PHP mail() function.
1606 * @see http://www.php.net/manual/en/book.mail.php
1608 * @param string $header The message headers
1609 * @param string $body The message body
1615 protected function mailSend($header, $body)
1618 foreach ($this->to as $toaddr) {
1619 $toArr[] = $this->addrFormat($toaddr);
1621 $to = implode(', ', $toArr);
1624 //This sets the SMTP envelope sender which gets turned into a return-path header by the receiver
1625 if (!empty($this->Sender) and static::validateAddress($this->Sender)) {
1626 //A space after `-f` is optional, but there is a long history of its presence
1627 //causing problems, so we don't use one
1628 //Exim docs: http://www.exim.org/exim-html-current/doc/html/spec_html/ch-the_exim_command_line.html
1629 //Sendmail docs: http://www.sendmail.org/~ca/email/man/sendmail.html
1630 //Qmail docs: http://www.qmail.org/man/man8/qmail-inject.html
1631 //Example problem: https://www.drupal.org/node/1057954
1632 // CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped.
1633 if (self::isShellSafe($this->Sender)) {
1634 $params = sprintf('-f%s', $this->Sender);
1637 if (!empty($this->Sender) and static::validateAddress($this->Sender)) {
1638 $old_from = ini_get('sendmail_from');
1639 ini_set('sendmail_from', $this->Sender);
1642 if ($this->SingleTo and count($toArr) > 1) {
1643 foreach ($toArr as $toAddr) {
1644 $result = $this->mailPassthru($toAddr, $this->Subject, $body, $header, $params);
1645 $this->doCallback($result, [$toAddr], $this->cc, $this->bcc, $this->Subject, $body, $this->From, []);
1648 $result = $this->mailPassthru($to, $this->Subject, $body, $header, $params);
1649 $this->doCallback($result, $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From, []);
1651 if (isset($old_from)) {
1652 ini_set('sendmail_from', $old_from);
1655 throw new Exception($this->lang('instantiate'), self::STOP_CRITICAL);
1662 * Get an instance to use for SMTP operations.
1663 * Override this function to load your own SMTP implementation,
1664 * or set one with setSMTPInstance.
1668 public function getSMTPInstance()
1670 if (!is_object($this->smtp)) {
1671 $this->smtp = new SMTP();
1678 * Provide an instance to use for SMTP operations.
1684 public function setSMTPInstance(SMTP $smtp)
1686 $this->smtp = $smtp;
1692 * Send mail via SMTP.
1693 * Returns false if there is a bad MAIL FROM, RCPT, or DATA input.
1695 * @see PHPMailer::setSMTPInstance() to use a different class.
1697 * @uses \PHPMailer\PHPMailer\SMTP
1699 * @param string $header The message headers
1700 * @param string $body The message body
1706 protected function smtpSend($header, $body)
1709 if (!$this->smtpConnect($this->SMTPOptions)) {
1710 throw new Exception($this->lang('smtp_connect_failed'), self::STOP_CRITICAL);
1712 //Sender already validated in preSend()
1713 if ('' == $this->Sender) {
1714 $smtp_from = $this->From;
1716 $smtp_from = $this->Sender;
1718 if (!$this->smtp->mail($smtp_from)) {
1719 $this->setError($this->lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp->getError()));
1720 throw new Exception($this->ErrorInfo, self::STOP_CRITICAL);
1724 // Attempt to send to all recipients
1725 foreach ([$this->to, $this->cc, $this->bcc] as $togroup) {
1726 foreach ($togroup as $to) {
1727 if (!$this->smtp->recipient($to[0])) {
1728 $error = $this->smtp->getError();
1729 $bad_rcpt[] = ['to' => $to[0], 'error' => $error['detail']];
1735 $callbacks[] = ['issent'=>$isSent, 'to'=>$to[0]];
1739 // Only send the DATA command if we have viable recipients
1740 if ((count($this->all_recipients) > count($bad_rcpt)) and !$this->smtp->data($header . $body)) {
1741 throw new Exception($this->lang('data_not_accepted'), self::STOP_CRITICAL);
1744 $smtp_transaction_id = $this->smtp->getLastTransactionID();
1746 if ($this->SMTPKeepAlive) {
1747 $this->smtp->reset();
1749 $this->smtp->quit();
1750 $this->smtp->close();
1753 foreach ($callbacks as $cb) {
1762 ['smtp_transaction_id' => $smtp_transaction_id]
1766 //Create error message for any bad addresses
1767 if (count($bad_rcpt) > 0) {
1769 foreach ($bad_rcpt as $bad) {
1770 $errstr .= $bad['to'] . ': ' . $bad['error'];
1772 throw new Exception(
1773 $this->lang('recipients_failed') . $errstr,
1782 * Initiate a connection to an SMTP server.
1783 * Returns false if the operation failed.
1785 * @param array $options An array of options compatible with stream_context_create()
1789 * @uses \PHPMailer\PHPMailer\SMTP
1793 public function smtpConnect($options = null)
1795 if (null === $this->smtp) {
1796 $this->smtp = $this->getSMTPInstance();
1799 //If no options are provided, use whatever is set in the instance
1800 if (null === $options) {
1801 $options = $this->SMTPOptions;
1804 // Already connected?
1805 if ($this->smtp->connected()) {
1809 $this->smtp->setTimeout($this->Timeout);
1810 $this->smtp->setDebugLevel($this->SMTPDebug);
1811 $this->smtp->setDebugOutput($this->Debugoutput);
1812 $this->smtp->setVerp($this->do_verp);
1813 $hosts = explode(';', $this->Host);
1814 $lastexception = null;
1816 foreach ($hosts as $hostentry) {
1819 '/^((ssl|tls):\/\/)*([a-zA-Z0-9\.-]*|\[[a-fA-F0-9:]+\]):?([0-9]*)$/',
1823 static::edebug($this->lang('connect_host') . ' ' . $hostentry);
1824 // Not a valid host entry
1827 // $hostinfo[2]: optional ssl or tls prefix
1828 // $hostinfo[3]: the hostname
1829 // $hostinfo[4]: optional port number
1830 // The host string prefix can temporarily override the current setting for SMTPSecure
1831 // If it's not specified, the default value is used
1833 //Check the host name is a valid name or IP address before trying to use it
1834 if (!static::isValidHost($hostinfo[3])) {
1835 static::edebug($this->lang('connect_host') . ' ' . $hostentry);
1839 $secure = $this->SMTPSecure;
1840 $tls = ('tls' == $this->SMTPSecure);
1841 if ('ssl' == $hostinfo[2] or ('' == $hostinfo[2] and 'ssl' == $this->SMTPSecure)) {
1843 $tls = false; // Can't have SSL and TLS at the same time
1845 } elseif ('tls' == $hostinfo[2]) {
1847 // tls doesn't use a prefix
1850 //Do we need the OpenSSL extension?
1851 $sslext = defined('OPENSSL_ALGO_SHA256');
1852 if ('tls' === $secure or 'ssl' === $secure) {
1853 //Check for an OpenSSL constant rather than using extension_loaded, which is sometimes disabled
1855 throw new Exception($this->lang('extension_missing') . 'openssl', self::STOP_CRITICAL);
1858 $host = $hostinfo[3];
1859 $port = $this->Port;
1860 $tport = (int) $hostinfo[4];
1861 if ($tport > 0 and $tport < 65536) {
1864 if ($this->smtp->connect($prefix . $host, $port, $this->Timeout, $options)) {
1867 $hello = $this->Helo;
1869 $hello = $this->serverHostname();
1871 $this->smtp->hello($hello);
1872 //Automatically enable TLS encryption if:
1873 // * it's not disabled
1874 // * we have openssl extension
1875 // * we are not already using SSL
1876 // * the server offers STARTTLS
1877 if ($this->SMTPAutoTLS and $sslext and $secure != 'ssl' and $this->smtp->getServerExt('STARTTLS')) {
1881 if (!$this->smtp->startTLS()) {
1882 throw new Exception($this->lang('connect_host'));
1884 // We must resend EHLO after TLS negotiation
1885 $this->smtp->hello($hello);
1887 if ($this->SMTPAuth) {
1888 if (!$this->smtp->authenticate(
1895 throw new Exception($this->lang('authenticate'));
1900 } catch (Exception $exc) {
1901 $lastexception = $exc;
1902 $this->edebug($exc->getMessage());
1903 // We must have connected, but then failed TLS or Auth, so close connection nicely
1904 $this->smtp->quit();
1908 // If we get here, all connection attempts have failed, so close connection hard
1909 $this->smtp->close();
1910 // As we've caught all exceptions, just report whatever the last one was
1911 if ($this->exceptions and null !== $lastexception) {
1912 throw $lastexception;
1919 * Close the active SMTP session if one exists.
1921 public function smtpClose()
1923 if (null !== $this->smtp) {
1924 if ($this->smtp->connected()) {
1925 $this->smtp->quit();
1926 $this->smtp->close();
1932 * Set the language for error messages.
1933 * Returns false if it cannot load the language file.
1934 * The default language is English.
1936 * @param string $langcode ISO 639-1 2-character language code (e.g. French is "fr")
1937 * @param string $lang_path Path to the language file directory, with trailing separator (slash)
1941 public function setLanguage($langcode = 'en', $lang_path = '')
1943 // Backwards compatibility for renamed language codes
1944 $renamed_langcodes = [
1953 if (isset($renamed_langcodes[$langcode])) {
1954 $langcode = $renamed_langcodes[$langcode];
1957 // Define full set of translatable strings in English
1959 'authenticate' => 'SMTP Error: Could not authenticate.',
1960 'connect_host' => 'SMTP Error: Could not connect to SMTP host.',
1961 'data_not_accepted' => 'SMTP Error: data not accepted.',
1962 'empty_message' => 'Message body empty',
1963 'encoding' => 'Unknown encoding: ',
1964 'execute' => 'Could not execute: ',
1965 'file_access' => 'Could not access file: ',
1966 'file_open' => 'File Error: Could not open file: ',
1967 'from_failed' => 'The following From address failed: ',
1968 'instantiate' => 'Could not instantiate mail function.',
1969 'invalid_address' => 'Invalid address: ',
1970 'mailer_not_supported' => ' mailer is not supported.',
1971 'provide_address' => 'You must provide at least one recipient email address.',
1972 'recipients_failed' => 'SMTP Error: The following recipients failed: ',
1973 'signing' => 'Signing Error: ',
1974 'smtp_connect_failed' => 'SMTP connect() failed.',
1975 'smtp_error' => 'SMTP server error: ',
1976 'variable_set' => 'Cannot set or reset variable: ',
1977 'extension_missing' => 'Extension missing: ',
1979 if (empty($lang_path)) {
1980 // Calculate an absolute path so it can work if CWD is not here
1981 $lang_path = __DIR__ . DIRECTORY_SEPARATOR . 'language' . DIRECTORY_SEPARATOR;
1983 //Validate $langcode
1984 if (!preg_match('/^[a-z]{2}(?:_[a-zA-Z]{2})?$/', $langcode)) {
1988 $lang_file = $lang_path . 'phpmailer.lang-' . $langcode . '.php';
1989 // There is no English translation file
1990 if ('en' != $langcode) {
1991 // Make sure language file path is readable
1992 if (!file_exists($lang_file)) {
1995 // Overwrite language-specific strings.
1996 // This way we'll never have missing translation keys.
1997 $foundlang = include $lang_file;
2000 $this->language = $PHPMAILER_LANG;
2002 return (bool) $foundlang; // Returns false if language not found
2006 * Get the array of strings for the current language.
2010 public function getTranslations()
2012 return $this->language;
2016 * Create recipient headers.
2018 * @param string $type
2019 * @param array $addr An array of recipients,
2020 * where each recipient is a 2-element indexed array with element 0 containing an address
2021 * and element 1 containing a name, like:
2022 * [['joe@example.com', 'Joe User'], ['zoe@example.com', 'Zoe User']]
2026 public function addrAppend($type, $addr)
2029 foreach ($addr as $address) {
2030 $addresses[] = $this->addrFormat($address);
2033 return $type . ': ' . implode(', ', $addresses) . static::$LE;
2037 * Format an address for use in a message header.
2039 * @param array $addr A 2-element indexed array, element 0 containing an address, element 1 containing a name like
2040 * ['joe@example.com', 'Joe User']
2044 public function addrFormat($addr)
2046 if (empty($addr[1])) { // No name provided
2047 return $this->secureHeader($addr[0]);
2050 return $this->encodeHeader($this->secureHeader($addr[1]), 'phrase') . ' <' . $this->secureHeader(
2056 * Word-wrap message.
2057 * For use with mailers that do not automatically perform wrapping
2058 * and for quoted-printable encoded messages.
2059 * Original written by philippe.
2061 * @param string $message The message to wrap
2062 * @param int $length The line length to wrap to
2063 * @param bool $qp_mode Whether to run in Quoted-Printable mode
2067 public function wrapText($message, $length, $qp_mode = false)
2070 $soft_break = sprintf(' =%s', static::$LE);
2072 $soft_break = static::$LE;
2074 // If utf-8 encoding is used, we will need to make sure we don't
2075 // split multibyte characters when we wrap
2076 $is_utf8 = (strtolower($this->CharSet) == 'utf-8');
2077 $lelen = strlen(static::$LE);
2078 $crlflen = strlen(static::$LE);
2080 $message = static::normalizeBreaks($message);
2081 //Remove a trailing line break
2082 if (substr($message, -$lelen) == static::$LE) {
2083 $message = substr($message, 0, -$lelen);
2086 //Split message into lines
2087 $lines = explode(static::$LE, $message);
2088 //Message will be rebuilt in here
2090 foreach ($lines as $line) {
2091 $words = explode(' ', $line);
2094 foreach ($words as $word) {
2095 if ($qp_mode and (strlen($word) > $length)) {
2096 $space_left = $length - strlen($buf) - $crlflen;
2098 if ($space_left > 20) {
2101 $len = $this->utf8CharBoundary($word, $len);
2102 } elseif (substr($word, $len - 1, 1) == '=') {
2104 } elseif (substr($word, $len - 2, 1) == '=') {
2107 $part = substr($word, 0, $len);
2108 $word = substr($word, $len);
2109 $buf .= ' ' . $part;
2110 $message .= $buf . sprintf('=%s', static::$LE);
2112 $message .= $buf . $soft_break;
2116 while (strlen($word) > 0) {
2122 $len = $this->utf8CharBoundary($word, $len);
2123 } elseif (substr($word, $len - 1, 1) == '=') {
2125 } elseif (substr($word, $len - 2, 1) == '=') {
2128 $part = substr($word, 0, $len);
2129 $word = substr($word, $len);
2131 if (strlen($word) > 0) {
2132 $message .= $part . sprintf('=%s', static::$LE);
2144 if (strlen($buf) > $length and $buf_o != '') {
2145 $message .= $buf_o . $soft_break;
2151 $message .= $buf . static::$LE;
2158 * Find the last character boundary prior to $maxLength in a utf-8
2159 * quoted-printable encoded string.
2160 * Original written by Colin Brown.
2162 * @param string $encodedText utf-8 QP text
2163 * @param int $maxLength Find the last character boundary prior to this length
2167 public function utf8CharBoundary($encodedText, $maxLength)
2169 $foundSplitPos = false;
2171 while (!$foundSplitPos) {
2172 $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
2173 $encodedCharPos = strpos($lastChunk, '=');
2174 if (false !== $encodedCharPos) {
2175 // Found start of encoded character byte within $lookBack block.
2176 // Check the encoded byte value (the 2 chars after the '=')
2177 $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
2178 $dec = hexdec($hex);
2180 // Single byte character.
2181 // If the encoded char was found at pos 0, it will fit
2182 // otherwise reduce maxLength to start of the encoded char
2183 if ($encodedCharPos > 0) {
2184 $maxLength -= $lookBack - $encodedCharPos;
2186 $foundSplitPos = true;
2187 } elseif ($dec >= 192) {
2188 // First byte of a multi byte character
2189 // Reduce maxLength to split at start of character
2190 $maxLength -= $lookBack - $encodedCharPos;
2191 $foundSplitPos = true;
2192 } elseif ($dec < 192) {
2193 // Middle byte of a multi byte character, look further back
2197 // No encoded character found
2198 $foundSplitPos = true;
2206 * Apply word wrapping to the message body.
2207 * Wraps the message body to the number of chars set in the WordWrap property.
2208 * You should only do this to plain-text bodies as wrapping HTML tags may break them.
2209 * This is called automatically by createBody(), so you don't need to call it yourself.
2211 public function setWordWrap()
2213 if ($this->WordWrap < 1) {
2217 switch ($this->message_type) {
2221 case 'alt_inline_attach':
2222 $this->AltBody = $this->wrapText($this->AltBody, $this->WordWrap);
2225 $this->Body = $this->wrapText($this->Body, $this->WordWrap);
2231 * Assemble message headers.
2233 * @return string The assembled headers
2235 public function createHeader()
2239 $result .= $this->headerLine('Date', '' == $this->MessageDate ? self::rfcDate() : $this->MessageDate);
2241 // To be created automatically by mail()
2242 if ($this->SingleTo) {
2243 if ('mail' != $this->Mailer) {
2244 foreach ($this->to as $toaddr) {
2245 $this->SingleToArray[] = $this->addrFormat($toaddr);
2249 if (count($this->to) > 0) {
2250 if ('mail' != $this->Mailer) {
2251 $result .= $this->addrAppend('To', $this->to);
2253 } elseif (count($this->cc) == 0) {
2254 $result .= $this->headerLine('To', 'undisclosed-recipients:;');
2258 $result .= $this->addrAppend('From', [[trim($this->From), $this->FromName]]);
2260 // sendmail and mail() extract Cc from the header before sending
2261 if (count($this->cc) > 0) {
2262 $result .= $this->addrAppend('Cc', $this->cc);
2265 // sendmail and mail() extract Bcc from the header before sending
2267 'sendmail' == $this->Mailer or 'qmail' == $this->Mailer or 'mail' == $this->Mailer
2269 and count($this->bcc) > 0
2271 $result .= $this->addrAppend('Bcc', $this->bcc);
2274 if (count($this->ReplyTo) > 0) {
2275 $result .= $this->addrAppend('Reply-To', $this->ReplyTo);
2278 // mail() sets the subject itself
2279 if ('mail' != $this->Mailer) {
2280 $result .= $this->headerLine('Subject', $this->encodeHeader($this->secureHeader($this->Subject)));
2283 // Only allow a custom message ID if it conforms to RFC 5322 section 3.6.4
2284 // https://tools.ietf.org/html/rfc5322#section-3.6.4
2285 if ('' != $this->MessageID and preg_match('/^<.*@.*>$/', $this->MessageID)) {
2286 $this->lastMessageID = $this->MessageID;
2288 $this->lastMessageID = sprintf('<%s@%s>', $this->uniqueid, $this->serverHostname());
2290 $result .= $this->headerLine('Message-ID', $this->lastMessageID);
2291 if (null !== $this->Priority) {
2292 $result .= $this->headerLine('X-Priority', $this->Priority);
2294 if ('' == $this->XMailer) {
2295 $result .= $this->headerLine(
2297 'PHPMailer ' . self::VERSION . ' (https://github.com/PHPMailer/PHPMailer)'
2300 $myXmailer = trim($this->XMailer);
2302 $result .= $this->headerLine('X-Mailer', $myXmailer);
2306 if ('' != $this->ConfirmReadingTo) {
2307 $result .= $this->headerLine('Disposition-Notification-To', '<' . $this->ConfirmReadingTo . '>');
2310 // Add custom headers
2311 foreach ($this->CustomHeader as $header) {
2312 $result .= $this->headerLine(
2314 $this->encodeHeader(trim($header[1]))
2317 if (!$this->sign_key_file) {
2318 $result .= $this->headerLine('MIME-Version', '1.0');
2319 $result .= $this->getMailMIME();
2326 * Get the message MIME type headers.
2330 public function getMailMIME()
2333 $ismultipart = true;
2334 switch ($this->message_type) {
2336 $result .= $this->headerLine('Content-Type', 'multipart/related;');
2337 $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
2340 case 'inline_attach':
2342 case 'alt_inline_attach':
2343 $result .= $this->headerLine('Content-Type', 'multipart/mixed;');
2344 $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
2348 $result .= $this->headerLine('Content-Type', 'multipart/alternative;');
2349 $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
2352 // Catches case 'plain': and case '':
2353 $result .= $this->textLine('Content-Type: ' . $this->ContentType . '; charset=' . $this->CharSet);
2354 $ismultipart = false;
2357 // RFC1341 part 5 says 7bit is assumed if not specified
2358 if ('7bit' != $this->Encoding) {
2359 // RFC 2045 section 6.4 says multipart MIME parts may only use 7bit, 8bit or binary CTE
2361 if ('8bit' == $this->Encoding) {
2362 $result .= $this->headerLine('Content-Transfer-Encoding', '8bit');
2364 // The only remaining alternatives are quoted-printable and base64, which are both 7bit compatible
2366 $result .= $this->headerLine('Content-Transfer-Encoding', $this->Encoding);
2370 if ('mail' != $this->Mailer) {
2371 $result .= static::$LE;
2378 * Returns the whole MIME message.
2379 * Includes complete headers and body.
2380 * Only valid post preSend().
2382 * @see PHPMailer::preSend()
2386 public function getSentMIMEMessage()
2388 return rtrim($this->MIMEHeader . $this->mailHeader, "\n\r") . static::$LE . static::$LE . $this->MIMEBody;
2392 * Create a unique ID to use for boundaries.
2396 protected function generateId()
2398 $len = 32; //32 bytes = 256 bits
2399 if (function_exists('random_bytes')) {
2400 $bytes = random_bytes($len);
2401 } elseif (function_exists('openssl_random_pseudo_bytes')) {
2402 $bytes = openssl_random_pseudo_bytes($len);
2404 //Use a hash to force the length to the same as the other methods
2405 $bytes = hash('sha256', uniqid((string) mt_rand(), true), true);
2408 //We don't care about messing up base64 format here, just want a random string
2409 return str_replace(['=', '+', '/'], '', base64_encode(hash('sha256', $bytes, true)));
2413 * Assemble the message body.
2414 * Returns an empty string on failure.
2418 * @return string The assembled message body
2420 public function createBody()
2423 //Create unique IDs and preset boundaries
2424 $this->uniqueid = $this->generateId();
2425 $this->boundary[1] = 'b1_' . $this->uniqueid;
2426 $this->boundary[2] = 'b2_' . $this->uniqueid;
2427 $this->boundary[3] = 'b3_' . $this->uniqueid;
2429 if ($this->sign_key_file) {
2430 $body .= $this->getMailMIME() . static::$LE;
2433 $this->setWordWrap();
2435 $bodyEncoding = $this->Encoding;
2436 $bodyCharSet = $this->CharSet;
2437 //Can we do a 7-bit downgrade?
2438 if ('8bit' == $bodyEncoding and !$this->has8bitChars($this->Body)) {
2439 $bodyEncoding = '7bit';
2440 //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit
2441 $bodyCharSet = 'us-ascii';
2443 //If lines are too long, and we're not already using an encoding that will shorten them,
2444 //change to quoted-printable transfer encoding for the body part only
2445 if ('base64' != $this->Encoding and static::hasLineLongerThanMax($this->Body)) {
2446 $bodyEncoding = 'quoted-printable';
2449 $altBodyEncoding = $this->Encoding;
2450 $altBodyCharSet = $this->CharSet;
2451 //Can we do a 7-bit downgrade?
2452 if ('8bit' == $altBodyEncoding and !$this->has8bitChars($this->AltBody)) {
2453 $altBodyEncoding = '7bit';
2454 //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit
2455 $altBodyCharSet = 'us-ascii';
2457 //If lines are too long, and we're not already using an encoding that will shorten them,
2458 //change to quoted-printable transfer encoding for the alt body part only
2459 if ('base64' != $altBodyEncoding and static::hasLineLongerThanMax($this->AltBody)) {
2460 $altBodyEncoding = 'quoted-printable';
2462 //Use this as a preamble in all multipart message types
2463 $mimepre = 'This is a multi-part message in MIME format.' . static::$LE;
2464 switch ($this->message_type) {
2467 $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
2468 $body .= $this->encodeString($this->Body, $bodyEncoding);
2469 $body .= static::$LE;
2470 $body .= $this->attachAll('inline', $this->boundary[1]);
2474 $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
2475 $body .= $this->encodeString($this->Body, $bodyEncoding);
2476 $body .= static::$LE;
2477 $body .= $this->attachAll('attachment', $this->boundary[1]);
2479 case 'inline_attach':
2481 $body .= $this->textLine('--' . $this->boundary[1]);
2482 $body .= $this->headerLine('Content-Type', 'multipart/related;');
2483 $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
2484 $body .= static::$LE;
2485 $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, '', $bodyEncoding);
2486 $body .= $this->encodeString($this->Body, $bodyEncoding);
2487 $body .= static::$LE;
2488 $body .= $this->attachAll('inline', $this->boundary[2]);
2489 $body .= static::$LE;
2490 $body .= $this->attachAll('attachment', $this->boundary[1]);
2494 $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, 'text/plain', $altBodyEncoding);
2495 $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
2496 $body .= static::$LE;
2497 $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, 'text/html', $bodyEncoding);
2498 $body .= $this->encodeString($this->Body, $bodyEncoding);
2499 $body .= static::$LE;
2500 if (!empty($this->Ical)) {
2501 $body .= $this->getBoundary($this->boundary[1], '', 'text/calendar; method=REQUEST', '');
2502 $body .= $this->encodeString($this->Ical, $this->Encoding);
2503 $body .= static::$LE;
2505 $body .= $this->endBoundary($this->boundary[1]);
2509 $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, 'text/plain', $altBodyEncoding);
2510 $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
2511 $body .= static::$LE;
2512 $body .= $this->textLine('--' . $this->boundary[1]);
2513 $body .= $this->headerLine('Content-Type', 'multipart/related;');
2514 $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
2515 $body .= static::$LE;
2516 $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, 'text/html', $bodyEncoding);
2517 $body .= $this->encodeString($this->Body, $bodyEncoding);
2518 $body .= static::$LE;
2519 $body .= $this->attachAll('inline', $this->boundary[2]);
2520 $body .= static::$LE;
2521 $body .= $this->endBoundary($this->boundary[1]);
2525 $body .= $this->textLine('--' . $this->boundary[1]);
2526 $body .= $this->headerLine('Content-Type', 'multipart/alternative;');
2527 $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
2528 $body .= static::$LE;
2529 $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, 'text/plain', $altBodyEncoding);
2530 $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
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 if (!empty($this->Ical)) {
2536 $body .= $this->getBoundary($this->boundary[2], '', 'text/calendar; method=REQUEST', '');
2537 $body .= $this->encodeString($this->Ical, $this->Encoding);
2539 $body .= $this->endBoundary($this->boundary[2]);
2540 $body .= static::$LE;
2541 $body .= $this->attachAll('attachment', $this->boundary[1]);
2543 case 'alt_inline_attach':
2545 $body .= $this->textLine('--' . $this->boundary[1]);
2546 $body .= $this->headerLine('Content-Type', 'multipart/alternative;');
2547 $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
2548 $body .= static::$LE;
2549 $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, 'text/plain', $altBodyEncoding);
2550 $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
2551 $body .= static::$LE;
2552 $body .= $this->textLine('--' . $this->boundary[2]);
2553 $body .= $this->headerLine('Content-Type', 'multipart/related;');
2554 $body .= $this->textLine("\tboundary=\"" . $this->boundary[3] . '"');
2555 $body .= static::$LE;
2556 $body .= $this->getBoundary($this->boundary[3], $bodyCharSet, 'text/html', $bodyEncoding);
2557 $body .= $this->encodeString($this->Body, $bodyEncoding);
2558 $body .= static::$LE;
2559 $body .= $this->attachAll('inline', $this->boundary[3]);
2560 $body .= static::$LE;
2561 $body .= $this->endBoundary($this->boundary[2]);
2562 $body .= static::$LE;
2563 $body .= $this->attachAll('attachment', $this->boundary[1]);
2566 // Catch case 'plain' and case '', applies to simple `text/plain` and `text/html` body content types
2567 //Reset the `Encoding` property in case we changed it for line length reasons
2568 $this->Encoding = $bodyEncoding;
2569 $body .= $this->encodeString($this->Body, $this->Encoding);
2573 if ($this->isError()) {
2575 if ($this->exceptions) {
2576 throw new Exception($this->lang('empty_message'), self::STOP_CRITICAL);
2578 } elseif ($this->sign_key_file) {
2580 if (!defined('PKCS7_TEXT')) {
2581 throw new Exception($this->lang('extension_missing') . 'openssl');
2583 // @TODO would be nice to use php://temp streams here
2584 $file = tempnam(sys_get_temp_dir(), 'mail');
2585 if (false === file_put_contents($file, $body)) {
2586 throw new Exception($this->lang('signing') . ' Could not write temp file');
2588 $signed = tempnam(sys_get_temp_dir(), 'signed');
2589 //Workaround for PHP bug https://bugs.php.net/bug.php?id=69197
2590 if (empty($this->sign_extracerts_file)) {
2591 $sign = @openssl_pkcs7_sign(
2594 'file://' . realpath($this->sign_cert_file),
2595 ['file://' . realpath($this->sign_key_file), $this->sign_key_pass],
2599 $sign = @openssl_pkcs7_sign(
2602 'file://' . realpath($this->sign_cert_file),
2603 ['file://' . realpath($this->sign_key_file), $this->sign_key_pass],
2606 $this->sign_extracerts_file
2611 $body = file_get_contents($signed);
2613 //The message returned by openssl contains both headers and body, so need to split them up
2614 $parts = explode("\n\n", $body, 2);
2615 $this->MIMEHeader .= $parts[0] . static::$LE . static::$LE;
2619 throw new Exception($this->lang('signing') . openssl_error_string());
2621 } catch (Exception $exc) {
2623 if ($this->exceptions) {
2633 * Return the start of a message boundary.
2635 * @param string $boundary
2636 * @param string $charSet
2637 * @param string $contentType
2638 * @param string $encoding
2642 protected function getBoundary($boundary, $charSet, $contentType, $encoding)
2645 if ('' == $charSet) {
2646 $charSet = $this->CharSet;
2648 if ('' == $contentType) {
2649 $contentType = $this->ContentType;
2651 if ('' == $encoding) {
2652 $encoding = $this->Encoding;
2654 $result .= $this->textLine('--' . $boundary);
2655 $result .= sprintf('Content-Type: %s; charset=%s', $contentType, $charSet);
2656 $result .= static::$LE;
2657 // RFC1341 part 5 says 7bit is assumed if not specified
2658 if ('7bit' != $encoding) {
2659 $result .= $this->headerLine('Content-Transfer-Encoding', $encoding);
2661 $result .= static::$LE;
2667 * Return the end of a message boundary.
2669 * @param string $boundary
2673 protected function endBoundary($boundary)
2675 return static::$LE . '--' . $boundary . '--' . static::$LE;
2679 * Set the message type.
2680 * PHPMailer only supports some preset message types, not arbitrary MIME structures.
2682 protected function setMessageType()
2685 if ($this->alternativeExists()) {
2688 if ($this->inlineImageExists()) {
2691 if ($this->attachmentExists()) {
2694 $this->message_type = implode('_', $type);
2695 if ('' == $this->message_type) {
2696 //The 'plain' message_type refers to the message having a single body element, not that it is plain-text
2697 $this->message_type = 'plain';
2702 * Format a header line.
2704 * @param string $name
2705 * @param string|int $value
2709 public function headerLine($name, $value)
2711 return $name . ': ' . $value . static::$LE;
2715 * Return a formatted mail line.
2717 * @param string $value
2721 public function textLine($value)
2723 return $value . static::$LE;
2727 * Add an attachment from a path on the filesystem.
2728 * Never use a user-supplied path to a file!
2729 * Returns false if the file could not be found or read.
2731 * @param string $path Path to the attachment
2732 * @param string $name Overrides the attachment name
2733 * @param string $encoding File encoding (see $Encoding)
2734 * @param string $type File extension (MIME) type
2735 * @param string $disposition Disposition to use
2741 public function addAttachment($path, $name = '', $encoding = 'base64', $type = '', $disposition = 'attachment')
2744 if (!@is_file($path)) {
2745 throw new Exception($this->lang('file_access') . $path, self::STOP_CONTINUE);
2748 // If a MIME type is not specified, try to work it out from the file name
2750 $type = static::filenameToType($path);
2753 $filename = basename($path);
2758 $this->attachment[] = [
2764 5 => false, // isStringAttachment
2768 } catch (Exception $exc) {
2769 $this->setError($exc->getMessage());
2770 $this->edebug($exc->getMessage());
2771 if ($this->exceptions) {
2782 * Return the array of attachments.
2786 public function getAttachments()
2788 return $this->attachment;
2792 * Attach all file, string, and binary attachments to the message.
2793 * Returns an empty string on failure.
2795 * @param string $disposition_type
2796 * @param string $boundary
2800 protected function attachAll($disposition_type, $boundary)
2802 // Return text of body
2807 // Add all attachments
2808 foreach ($this->attachment as $attachment) {
2809 // Check if it is a valid disposition_filter
2810 if ($attachment[6] == $disposition_type) {
2811 // Check for string attachment
2814 $bString = $attachment[5];
2816 $string = $attachment[0];
2818 $path = $attachment[0];
2821 $inclhash = hash('sha256', serialize($attachment));
2822 if (in_array($inclhash, $incl)) {
2825 $incl[] = $inclhash;
2826 $name = $attachment[2];
2827 $encoding = $attachment[3];
2828 $type = $attachment[4];
2829 $disposition = $attachment[6];
2830 $cid = $attachment[7];
2831 if ('inline' == $disposition and array_key_exists($cid, $cidUniq)) {
2834 $cidUniq[$cid] = true;
2836 $mime[] = sprintf('--%s%s', $boundary, static::$LE);
2837 //Only include a filename property if we have one
2838 if (!empty($name)) {
2840 'Content-Type: %s; name="%s"%s',
2842 $this->encodeHeader($this->secureHeader($name)),
2847 'Content-Type: %s%s',
2852 // RFC1341 part 5 says 7bit is assumed if not specified
2853 if ('7bit' != $encoding) {
2854 $mime[] = sprintf('Content-Transfer-Encoding: %s%s', $encoding, static::$LE);
2858 $mime[] = sprintf('Content-ID: <%s>%s', $cid, static::$LE);
2861 // If a filename contains any of these chars, it should be quoted,
2862 // but not otherwise: RFC2183 & RFC2045 5.1
2863 // Fixes a warning in IETF's msglint MIME checker
2864 // Allow for bypassing the Content-Disposition header totally
2865 if (!(empty($disposition))) {
2866 $encoded_name = $this->encodeHeader($this->secureHeader($name));
2867 if (preg_match('/[ \(\)<>@,;:\\"\/\[\]\?=]/', $encoded_name)) {
2869 'Content-Disposition: %s; filename="%s"%s',
2872 static::$LE . static::$LE
2875 if (!empty($encoded_name)) {
2877 'Content-Disposition: %s; filename=%s%s',
2880 static::$LE . static::$LE
2884 'Content-Disposition: %s%s',
2886 static::$LE . static::$LE
2891 $mime[] = static::$LE;
2894 // Encode as string attachment
2896 $mime[] = $this->encodeString($string, $encoding);
2898 $mime[] = $this->encodeFile($path, $encoding);
2900 if ($this->isError()) {
2903 $mime[] = static::$LE;
2907 $mime[] = sprintf('--%s--%s', $boundary, static::$LE);
2909 return implode('', $mime);
2913 * Encode a file attachment in requested format.
2914 * Returns an empty string on failure.
2916 * @param string $path The full path to the file
2917 * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
2923 protected function encodeFile($path, $encoding = 'base64')
2926 if (!file_exists($path)) {
2927 throw new Exception($this->lang('file_open') . $path, self::STOP_CONTINUE);
2929 $file_buffer = file_get_contents($path);
2930 if (false === $file_buffer) {
2931 throw new Exception($this->lang('file_open') . $path, self::STOP_CONTINUE);
2933 $file_buffer = $this->encodeString($file_buffer, $encoding);
2935 return $file_buffer;
2936 } catch (Exception $exc) {
2937 $this->setError($exc->getMessage());
2944 * Encode a string in requested format.
2945 * Returns an empty string on failure.
2947 * @param string $str The text to encode
2948 * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable
2952 public function encodeString($str, $encoding = 'base64')
2955 switch (strtolower($encoding)) {
2957 $encoded = chunk_split(
2958 base64_encode($str),
2959 static::STD_LINE_LENGTH - strlen(static::$LE),
2965 $encoded = static::normalizeBreaks($str);
2966 // Make sure it ends with a line break
2967 if (substr($encoded, -(strlen(static::$LE))) != static::$LE) {
2968 $encoded .= static::$LE;
2974 case 'quoted-printable':
2975 $encoded = $this->encodeQP($str);
2978 $this->setError($this->lang('encoding') . $encoding);
2986 * Encode a header value (not including its label) optimally.
2987 * Picks shortest of Q, B, or none. Result includes folding if needed.
2988 * See RFC822 definitions for phrase, comment and text positions.
2990 * @param string $str The header value to encode
2991 * @param string $position What context the string will be used in
2995 public function encodeHeader($str, $position = 'text')
2998 switch (strtolower($position)) {
3000 if (!preg_match('/[\200-\377]/', $str)) {
3001 // Can't use addslashes as we don't know the value of magic_quotes_sybase
3002 $encoded = addcslashes($str, "\0..\37\177\\\"");
3003 if (($str == $encoded) and !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
3007 return "\"$encoded\"";
3009 $matchcount = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
3011 /* @noinspection PhpMissingBreakStatementInspection */
3013 $matchcount = preg_match_all('/[()"]/', $str, $matches);
3017 $matchcount += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
3021 //RFCs specify a maximum line length of 78 chars, however mail() will sometimes
3022 //corrupt messages with headers longer than 65 chars. See #818
3023 $lengthsub = 'mail' == $this->Mailer ? 13 : 0;
3024 $maxlen = static::STD_LINE_LENGTH - $lengthsub;
3025 // Try to select the encoding which should produce the shortest output
3026 if ($matchcount > strlen($str) / 3) {
3027 // More than a third of the content will need encoding, so B encoding will be most efficient
3029 //This calculation is:
3031 // - shorten to avoid mail() corruption
3032 // - Q/B encoding char overhead ("` =?<charset>?[QB]?<content>?=`")
3033 // - charset name length
3034 $maxlen = static::STD_LINE_LENGTH - $lengthsub - 8 - strlen($this->CharSet);
3035 if ($this->hasMultiBytes($str)) {
3036 // Use a custom function which correctly encodes and wraps long
3037 // multibyte strings without breaking lines within a character
3038 $encoded = $this->base64EncodeWrapMB($str, "\n");
3040 $encoded = base64_encode($str);
3041 $maxlen -= $maxlen % 4;
3042 $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
3044 $encoded = preg_replace('/^(.*)$/m', ' =?' . $this->CharSet . "?$encoding?\\1?=", $encoded);
3045 } elseif ($matchcount > 0) {
3046 //1 or more chars need encoding, use Q-encode
3048 //Recalc max line length for Q encoding - see comments on B encode
3049 $maxlen = static::STD_LINE_LENGTH - $lengthsub - 8 - strlen($this->CharSet);
3050 $encoded = $this->encodeQ($str, $position);
3051 $encoded = $this->wrapText($encoded, $maxlen, true);
3052 $encoded = str_replace('=' . static::$LE, "\n", trim($encoded));
3053 $encoded = preg_replace('/^(.*)$/m', ' =?' . $this->CharSet . "?$encoding?\\1?=", $encoded);
3054 } elseif (strlen($str) > $maxlen) {
3055 //No chars need encoding, but line is too long, so fold it
3056 $encoded = trim($this->wrapText($str, $maxlen, false));
3057 if ($str == $encoded) {
3058 //Wrapping nicely didn't work, wrap hard instead
3059 $encoded = trim(chunk_split($str, static::STD_LINE_LENGTH, static::$LE));
3061 $encoded = str_replace(static::$LE, "\n", trim($encoded));
3062 $encoded = preg_replace('/^(.*)$/m', ' \\1', $encoded);
3064 //No reformatting needed
3068 return trim(static::normalizeBreaks($encoded));
3072 * Check if a string contains multi-byte characters.
3074 * @param string $str multi-byte text to wrap encode
3078 public function hasMultiBytes($str)
3080 if (function_exists('mb_strlen')) {
3081 return strlen($str) > mb_strlen($str, $this->CharSet);
3084 // Assume no multibytes (we can't handle without mbstring functions anyway)
3089 * Does a string contain any 8-bit chars (in any charset)?
3091 * @param string $text
3095 public function has8bitChars($text)
3097 return (bool) preg_match('/[\x80-\xFF]/', $text);
3101 * Encode and wrap long multibyte strings for mail headers
3102 * without breaking lines within a character.
3103 * Adapted from a function by paravoid.
3105 * @see http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283
3107 * @param string $str multi-byte text to wrap encode
3108 * @param string $linebreak string to use as linefeed/end-of-line
3112 public function base64EncodeWrapMB($str, $linebreak = null)
3114 $start = '=?' . $this->CharSet . '?B?';
3117 if (null === $linebreak) {
3118 $linebreak = static::$LE;
3121 $mb_length = mb_strlen($str, $this->CharSet);
3122 // Each line must have length <= 75, including $start and $end
3123 $length = 75 - strlen($start) - strlen($end);
3124 // Average multi-byte ratio
3125 $ratio = $mb_length / strlen($str);
3126 // Base64 has a 4:3 ratio
3127 $avgLength = floor($length * $ratio * .75);
3129 for ($i = 0; $i < $mb_length; $i += $offset) {
3132 $offset = $avgLength - $lookBack;
3133 $chunk = mb_substr($str, $i, $offset, $this->CharSet);
3134 $chunk = base64_encode($chunk);
3136 } while (strlen($chunk) > $length);
3137 $encoded .= $chunk . $linebreak;
3140 // Chomp the last linefeed
3141 return substr($encoded, 0, -strlen($linebreak));
3145 * Encode a string in quoted-printable format.
3146 * According to RFC2045 section 6.7.
3148 * @param string $string The text to encode
3152 public function encodeQP($string)
3154 return static::normalizeBreaks(quoted_printable_encode($string));
3158 * Encode a string using Q encoding.
3160 * @see http://tools.ietf.org/html/rfc2047#section-4.2
3162 * @param string $str the text to encode
3163 * @param string $position Where the text is going to be used, see the RFC for what that means
3167 public function encodeQ($str, $position = 'text')
3169 // There should not be any EOL in the string
3171 $encoded = str_replace(["\r", "\n"], '', $str);
3172 switch (strtolower($position)) {
3174 // RFC 2047 section 5.3
3175 $pattern = '^A-Za-z0-9!*+\/ -';
3178 * RFC 2047 section 5.2.
3179 * Build $pattern without including delimiters and []
3181 /* @noinspection PhpMissingBreakStatementInspection */
3184 /* Intentional fall through */
3187 // RFC 2047 section 5.1
3188 // Replace every high ascii, control, =, ? and _ characters
3189 $pattern = '\000-\011\013\014\016-\037\075\077\137\177-\377' . $pattern;
3193 if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) {
3194 // If the string contains an '=', make sure it's the first thing we replace
3195 // so as to avoid double-encoding
3196 $eqkey = array_search('=', $matches[0]);
3197 if (false !== $eqkey) {
3198 unset($matches[0][$eqkey]);
3199 array_unshift($matches[0], '=');
3201 foreach (array_unique($matches[0]) as $char) {
3202 $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded);
3205 // Replace spaces with _ (more readable than =20)
3206 // RFC 2047 section 4.2(2)
3207 return str_replace(' ', '_', $encoded);
3211 * Add a string or binary attachment (non-filesystem).
3212 * This method can be used to attach ascii or binary data,
3213 * such as a BLOB record from a database.
3215 * @param string $string String attachment data
3216 * @param string $filename Name of the attachment
3217 * @param string $encoding File encoding (see $Encoding)
3218 * @param string $type File extension (MIME) type
3219 * @param string $disposition Disposition to use
3221 public function addStringAttachment(
3224 $encoding = 'base64',
3226 $disposition = 'attachment'
3228 // If a MIME type is not specified, try to work it out from the file name
3230 $type = static::filenameToType($filename);
3232 // Append to $attachment array
3233 $this->attachment[] = [
3236 2 => basename($filename),
3239 5 => true, // isStringAttachment
3246 * Add an embedded (inline) attachment from a file.
3247 * This can include images, sounds, and just about any other document type.
3248 * These differ from 'regular' attachments in that they are intended to be
3249 * displayed inline with the message, not just attached for download.
3250 * This is used in HTML messages that embed the images
3251 * the HTML refers to using the $cid value.
3252 * Never use a user-supplied path to a file!
3254 * @param string $path Path to the attachment
3255 * @param string $cid Content ID of the attachment; Use this to reference
3256 * the content when using an embedded image in HTML
3257 * @param string $name Overrides the attachment name
3258 * @param string $encoding File encoding (see $Encoding)
3259 * @param string $type File MIME type
3260 * @param string $disposition Disposition to use
3262 * @return bool True on successfully adding an attachment
3264 public function addEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = '', $disposition = 'inline')
3266 if (!@is_file($path)) {
3267 $this->setError($this->lang('file_access') . $path);
3272 // If a MIME type is not specified, try to work it out from the file name
3274 $type = static::filenameToType($path);
3277 $filename = basename($path);
3282 // Append to $attachment array
3283 $this->attachment[] = [
3289 5 => false, // isStringAttachment
3298 * Add an embedded stringified attachment.
3299 * This can include images, sounds, and just about any other document type.
3300 * Be sure to set the $type to an image type for images:
3301 * JPEG images use 'image/jpeg', GIF uses 'image/gif', PNG uses 'image/png'.
3303 * @param string $string The attachment binary data
3304 * @param string $cid Content ID of the attachment; Use this to reference
3305 * the content when using an embedded image in HTML
3306 * @param string $name
3307 * @param string $encoding File encoding (see $Encoding)
3308 * @param string $type MIME type
3309 * @param string $disposition Disposition to use
3311 * @return bool True on successfully adding an attachment
3313 public function addStringEmbeddedImage(
3317 $encoding = 'base64',
3319 $disposition = 'inline'
3321 // If a MIME type is not specified, try to work it out from the name
3322 if ('' == $type and !empty($name)) {
3323 $type = static::filenameToType($name);