![PHPMailer](https://raw.github.com/PHPMailer/PHPMailer/master/examples/images/phpmailer.png)
-# PHPMailer - A full-featured email creation and transfer class for PHP
+# PHPMailer – A full-featured email creation and transfer class for PHP
-Build status: [![Build Status](https://travis-ci.org/PHPMailer/PHPMailer.svg)](https://travis-ci.org/PHPMailer/PHPMailer)
-[![Scrutinizer Quality Score](https://scrutinizer-ci.com/g/PHPMailer/PHPMailer/badges/quality-score.png?s=3758e21d279becdf847a557a56a3ed16dfec9d5d)](https://scrutinizer-ci.com/g/PHPMailer/PHPMailer/)
-[![Code Coverage](https://scrutinizer-ci.com/g/PHPMailer/PHPMailer/badges/coverage.png?s=3fe6ca5fe8cd2cdf96285756e42932f7ca256962)](https://scrutinizer-ci.com/g/PHPMailer/PHPMailer/)
+[![Test status](https://github.com/PHPMailer/PHPMailer/workflows/Tests/badge.svg)](https://github.com/PHPMailer/PHPMailer/actions) [![Latest Stable Version](https://poser.pugx.org/phpmailer/phpmailer/v/stable.svg)](https://packagist.org/packages/phpmailer/phpmailer) [![Total Downloads](https://poser.pugx.org/phpmailer/phpmailer/downloads)](https://packagist.org/packages/phpmailer/phpmailer) [![License](https://poser.pugx.org/phpmailer/phpmailer/license.svg)](https://packagist.org/packages/phpmailer/phpmailer) [![API Docs](https://github.com/phpmailer/phpmailer/workflows/Docs/badge.svg)](https://phpmailer.github.io/PHPMailer/)
-[![Latest Stable Version](https://poser.pugx.org/phpmailer/phpmailer/v/stable.svg)](https://packagist.org/packages/phpmailer/phpmailer) [![Total Downloads](https://poser.pugx.org/phpmailer/phpmailer/downloads)](https://packagist.org/packages/phpmailer/phpmailer) [![Latest Unstable Version](https://poser.pugx.org/phpmailer/phpmailer/v/unstable.svg)](https://packagist.org/packages/phpmailer/phpmailer) [![License](https://poser.pugx.org/phpmailer/phpmailer/license.svg)](https://packagist.org/packages/phpmailer/phpmailer) [![API Docs](https://github.com/phpmailer/phpmailer/workflows/Docs/badge.svg)](http://phpmailer.github.io/PHPMailer/)
-
-## Class Features
+## Features
- Probably the world's most popular code for sending email from PHP!
- Used by many open-source projects: WordPress, Drupal, 1CRM, SugarCRM, Yii, Joomla! and many more
-- Integrated SMTP support - send without a local mail server
+- Integrated SMTP support – send without a local mail server
- Send emails with multiple To, CC, BCC and Reply-to addresses
- Multipart/alternative emails for mail clients that do not read HTML email
- Add attachments, including inline
- Support for UTF-8 content and 8bit, base64, binary, and quoted-printable encodings
-- SMTP authentication with LOGIN, PLAIN, CRAM-MD5, and XOAUTH2 mechanisms over SSL and SMTP+STARTTLS transports
+- SMTP authentication with LOGIN, PLAIN, CRAM-MD5, and XOAUTH2 mechanisms over SMTPS and SMTP+STARTTLS transports
- Validates email addresses automatically
-- Protect against header injection attacks
+- Protects against header injection attacks
- Error messages in over 50 languages!
- DKIM and S/MIME signing support
-- Compatible with PHP 5.5 and later
+- Compatible with PHP 5.5 and later, including PHP 8.0
- Namespaced to prevent name clashes
- Much more!
## Why you might need it
-Many PHP developers need to send email from their code. The only PHP function that supports this is [`mail()`](https://www.php.net/manual/en/function.mail.php). However, it does not provide any assistance for making use of popular features such as encryption, authentication, HTML messages, and attachments.
+Many PHP developers need to send email from their code. The only PHP function that supports this directly is [`mail()`](https://www.php.net/manual/en/function.mail.php). However, it does not provide any assistance for making use of popular features such as encryption, authentication, HTML messages, and attachments.
+
+Formatting email correctly is surprisingly difficult. There are myriad overlapping (and conflicting) standards, requiring tight adherence to horribly complicated formatting and encoding rules – the vast majority of code that you'll find online that uses the `mail()` function directly is just plain wrong, if not unsafe!
-Formatting email correctly is surprisingly difficult. There are myriad overlapping RFCs, requiring tight adherence to horribly complicated formatting and encoding rules – the vast majority of code that you'll find online that uses the `mail()` function directly is just plain wrong!
-*Please* don't be tempted to do it yourself – if you don't use PHPMailer, there are many other excellent libraries that you should look at before rolling your own. Try [SwiftMailer](https://swiftmailer.symfony.com/), [Zend/Mail](https://zendframework.github.io/zend-mail/), [ZetaComponents](https://github.com/zetacomponents/Mail) etc.
+The PHP `mail()` function usually sends via a local mail server, typically fronted by a `sendmail` binary on Linux, BSD, and macOS platforms, however, Windows usually doesn't include a local mail server; PHPMailer's integrated SMTP client allows email sending on all platforms without needing a local mail server. Be aware though, that the `mail()` function should be avoided when possible; it's both faster and [safer](https://exploitbox.io/paper/Pwning-PHP-Mail-Function-For-Fun-And-RCE.html) to use SMTP to localhost.
-The PHP `mail()` function usually sends via a local mail server, typically fronted by a `sendmail` binary on Linux, BSD, and macOS platforms, however, Windows usually doesn't include a local mail server; PHPMailer's integrated SMTP implementation allows email sending on Windows platforms without a local mail server.
+*Please* don't be tempted to do it yourself – if you don't use PHPMailer, there are many other excellent libraries that
+you should look at before rolling your own. Try [SwiftMailer](https://swiftmailer.symfony.com/)
+, [Laminas/Mail](https://docs.laminas.dev/laminas-mail/), [ZetaComponents](https://github.com/zetacomponents/Mail) etc.
## License
-This software is distributed under the [LGPL 2.1](http://www.gnu.org/licenses/lgpl-2.1.html) license, along with the [GPL Cooperation Commitment](https://gplcc.github.io/gplcc/). Please read LICENSE for information on the software availability and distribution.
+This software is distributed under the [LGPL 2.1](http://www.gnu.org/licenses/lgpl-2.1.html) license, along with the [GPL Cooperation Commitment](https://gplcc.github.io/gplcc/). Please read [LICENSE](https://github.com/PHPMailer/PHPMailer/blob/master/LICENSE) for information on the software availability and distribution.
## Installation & loading
PHPMailer is available on [Packagist](https://packagist.org/packages/phpmailer/phpmailer) (using semantic versioning), and installation via [Composer](https://getcomposer.org) is the recommended way to install PHPMailer. Just add this line to your `composer.json` file:
```json
-"phpmailer/phpmailer": "~6.1"
+"phpmailer/phpmailer": "^6.2"
```
or run
If you want to use the Gmail XOAUTH2 authentication class, you will also need to add a dependency on the `league/oauth2-client` package in your `composer.json`.
-Alternatively, if you're not using Composer, copy the contents of the PHPMailer folder into one of the `include_path` directories specified in your PHP configuration and load each class file manually:
+Alternatively, if you're not using Composer, you
+can [download PHPMailer as a zip file](https://github.com/PHPMailer/PHPMailer/archive/master.zip), (note that docs and examples are not included in the zip file), then copy the contents of the PHPMailer folder into one of the `include_path` directories specified in your PHP configuration and load each class file manually:
```php
<?php
require 'path/to/PHPMailer/src/SMTP.php';
```
-If you're not using the `SMTP` class explicitly (you're probably not), you don't need a `use` line for the SMTP class.
-
-If you don't speak git or just want a tarball, click the 'zip' button on the right of the project page in GitHub, though note that docs and examples are not included in the tarball.
+If you're not using the `SMTP` class explicitly (you're probably not), you don't need a `use` line for the SMTP class. Even if you're not using exceptions, you do still need to load the `Exception` class as it is used internally.
## Legacy versions
-PHPMailer 5.2 (which is compatible with PHP 5.0 - 7.0) is no longer being supported, even for security updates. You will find the latest version of 5.2 in the [5.2-stable branch](https://github.com/PHPMailer/PHPMailer/tree/5.2-stable). If you're using PHP 5.5 or later (which you should be), switch to the 6.x releases.
+PHPMailer 5.2 (which is compatible with PHP 5.0 — 7.0) is no longer supported, even for security updates. You will find the latest version of 5.2 in the [5.2-stable branch](https://github.com/PHPMailer/PHPMailer/tree/5.2-stable). If you're using PHP 5.5 or later (which you should be), switch to the 6.x releases.
### Upgrading from 5.2
The biggest changes are that source files are now in the `src/` folder, and PHPMailer now declares the namespace `PHPMailer\PHPMailer`. This has several important effects – [read the upgrade guide](https://github.com/PHPMailer/PHPMailer/tree/master/UPGRADING.md) for more details.
### Minimal installation
-While installing the entire package manually or with Composer is simple, convenient, and reliable, you may want to include only vital files in your project. At the very least you will need [src/PHPMailer.php](https://github.com/PHPMailer/PHPMailer/tree/master/src/PHPMailer.php). If you're using SMTP, you'll need [src/SMTP.php](https://github.com/PHPMailer/PHPMailer/tree/master/src/SMTP.php), and if you're using POP-before SMTP, you'll need [src/POP3.php](https://github.com/PHPMailer/PHPMailer/tree/master/src/POP3.php). You can skip the [language](https://github.com/PHPMailer/PHPMailer/tree/master/language/) folder if you're not showing errors to users and can make do with English-only errors. If you're using XOAUTH2 you will need [src/OAuth.php](https://github.com/PHPMailer/PHPMailer/tree/master/src/OAuth.php) as well as the Composer dependencies for the services you wish to authenticate with. Really, it's much easier to use Composer!
+While installing the entire package manually or with Composer is simple, convenient, and reliable, you may want to include only vital files in your project. At the very least you will need [src/PHPMailer.php](https://github.com/PHPMailer/PHPMailer/tree/master/src/PHPMailer.php). If you're using SMTP, you'll need [src/SMTP.php](https://github.com/PHPMailer/PHPMailer/tree/master/src/SMTP.php), and if you're using POP-before SMTP (*very* unlikely!), you'll need [src/POP3.php](https://github.com/PHPMailer/PHPMailer/tree/master/src/POP3.php). You can skip the [language](https://github.com/PHPMailer/PHPMailer/tree/master/language/) folder if you're not showing errors to users and can make do with English-only errors. If you're using XOAUTH2 you will need [src/OAuth.php](https://github.com/PHPMailer/PHPMailer/tree/master/src/OAuth.php) as well as the Composer dependencies for the services you wish to authenticate with. Really, it's much easier to use Composer!
## A Simple Example
```php
<?php
-// Import PHPMailer classes into the global namespace
-// These must be at the top of your script, not inside a function
+//Import PHPMailer classes into the global namespace
+//These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
-// Load Composer's autoloader
+//Load Composer's autoloader
require 'vendor/autoload.php';
-// Instantiation and passing `true` enables exceptions
+//Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);
try {
//Server settings
- $mail->SMTPDebug = SMTP::DEBUG_SERVER; // Enable verbose debug output
- $mail->isSMTP(); // Send using SMTP
- $mail->Host = 'smtp1.example.com'; // Set the SMTP server to send through
- $mail->SMTPAuth = true; // Enable SMTP authentication
- $mail->Username = 'user@example.com'; // SMTP username
- $mail->Password = 'secret'; // SMTP password
- $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` also accepted
- $mail->Port = 587; // TCP port to connect to
+ $mail->SMTPDebug = SMTP::DEBUG_SERVER; //Enable verbose debug output
+ $mail->isSMTP(); //Send using SMTP
+ $mail->Host = 'smtp.example.com'; //Set the SMTP server to send through
+ $mail->SMTPAuth = true; //Enable SMTP authentication
+ $mail->Username = 'user@example.com'; //SMTP username
+ $mail->Password = 'secret'; //SMTP password
+ $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; //Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
+ $mail->Port = 587; //TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
//Recipients
$mail->setFrom('from@example.com', 'Mailer');
- $mail->addAddress('joe@example.net', 'Joe User'); // Add a recipient
- $mail->addAddress('ellen@example.com'); // Name is optional
+ $mail->addAddress('joe@example.net', 'Joe User'); //Add a recipient
+ $mail->addAddress('ellen@example.com'); //Name is optional
$mail->addReplyTo('info@example.com', 'Information');
$mail->addCC('cc@example.com');
$mail->addBCC('bcc@example.com');
- // Attachments
- $mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
- $mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
+ //Attachments
+ $mail->addAttachment('/var/tmp/file.tar.gz'); //Add attachments
+ $mail->addAttachment('/tmp/image.jpg', 'new.jpg'); //Optional name
- // Content
- $mail->isHTML(true); // Set email format to HTML
+ //Content
+ $mail->isHTML(true); //Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
}
```
-You'll find plenty more to play with in the [examples](https://github.com/PHPMailer/PHPMailer/tree/master/examples) folder.
+You'll find plenty to play with in the [examples](https://github.com/PHPMailer/PHPMailer/tree/master/examples) folder, which covers many common scenarios including sending through gmail, building contact forms, sending to mailing lists, and more.
If you are re-using the instance (e.g. when sending to a mailing list), you may need to clear the recipient list to avoid sending duplicate messages. See [the mailing list example](https://github.com/PHPMailer/PHPMailer/blob/master/examples/mailing_list.phps) for further guidance.
PHPMailer defaults to English, but in the [language](https://github.com/PHPMailer/PHPMailer/tree/master/language/) folder you'll find many translations for PHPMailer error messages that you may encounter. Their filenames contain [ISO 639-1](http://en.wikipedia.org/wiki/ISO_639-1) language code for the translations, for example `fr` for French. To specify a language, you need to tell PHPMailer which one to use, like this:
```php
-// To load the French version
+//To load the French version
$mail->setLanguage('fr', '/optional/path/to/language/directory/');
```
-We welcome corrections and new languages - if you're looking for corrections to do, run the [PHPMailerLangTest.php](https://github.com/PHPMailer/PHPMailer/tree/master/test/PHPMailerLangTest.php) script in the tests folder and it will show any missing translations.
+We welcome corrections and new languages – if you're looking for corrections, run the [PHPMailerLangTest.php](https://github.com/PHPMailer/PHPMailer/tree/master/test/PHPMailerLangTest.php) script in the tests folder and it will show any missing translations.
## Documentation
-Start reading at the [GitHub wiki](https://github.com/PHPMailer/PHPMailer/wiki). If you're having trouble, this should be the first place you look as it's the most frequently updated.
+Start reading at the [GitHub wiki](https://github.com/PHPMailer/PHPMailer/wiki). If you're having trouble, head for [the troubleshooting guide](https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting) as it's frequently updated.
Examples of how to use PHPMailer for common scenarios can be found in the [examples](https://github.com/PHPMailer/PHPMailer/tree/master/examples) folder. If you're looking for a good starting point, we recommend you start with [the Gmail example](https://github.com/PHPMailer/PHPMailer/tree/master/examples/gmail.phps).
-Note that in order to reduce PHPMailer's deployed code footprint, the examples are no longer included if you load PHPMailer via Composer or via [GitHub's zip file download](https://github.com/PHPMailer/PHPMailer/archive/master.zip), so you'll need to either clone the git repository or use the above links to get to the examples directly.
+To reduce PHPMailer's deployed code footprint, examples are not included if you load PHPMailer via Composer or via [GitHub's zip file download](https://github.com/PHPMailer/PHPMailer/archive/master.zip), so you'll need to either clone the git repository or use the above links to get to the examples directly.
-Complete generated API documentation is [available online](http://phpmailer.github.io/PHPMailer/).
+Complete generated API documentation is [available online](https://phpmailer.github.io/PHPMailer/).
-You can generate complete API-level documentation by running `phpdoc` in the top-level folder, and documentation will appear in the `docs` folder, though you'll need to have [PHPDocumentor](http://www.phpdoc.org) installed. You may find [the unit tests](https://github.com/PHPMailer/PHPMailer/tree/master/test/phpmailerTest.php) a good source of how to do various operations such as encryption.
+You can generate complete API-level documentation by running `phpdoc` in the top-level folder, and documentation will appear in the `docs` folder, though you'll need to have [PHPDocumentor](http://www.phpdoc.org) installed. You may find [the unit tests](https://github.com/PHPMailer/PHPMailer/blob/master/test/PHPMailerTest.php) a good reference for how to do various operations such as encryption.
If the documentation doesn't cover what you need, search the [many questions on Stack Overflow](http://stackoverflow.com/questions/tagged/phpmailer), and before you ask a question about "SMTP Error: Could not connect to SMTP host.", [read the troubleshooting guide](https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting).
## Tests
-There is a PHPUnit test script in the [test](https://github.com/PHPMailer/PHPMailer/tree/master/test/) folder. PHPMailer uses PHPUnit 4.8 - we would use 5.x but we need to run on PHP 5.5.
+[PHPMailer tests](https://github.com/PHPMailer/PHPMailer/tree/master/test/) use PHPUnit 9, with [a polyfill](https://github.com/Yoast/PHPUnit-Polyfills) to let 9-style tests run on older PHPUnit and PHP versions.
-Build status: [![Build Status](https://travis-ci.org/PHPMailer/PHPMailer.svg)](https://travis-ci.org/PHPMailer/PHPMailer)
+[![Test status](https://github.com/PHPMailer/PHPMailer/workflows/Tests/badge.svg)](https://github.com/PHPMailer/PHPMailer/actions)
If this isn't passing, is there something you can do to help?
## Security
-Please disclose any vulnerabilities found responsibly - report any security problems found to the maintainers privately.
-
-PHPMailer versions prior to 5.2.22 (released January 9th 2017) have a local file disclosure vulnerability, [CVE-2017-5223](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2017-5223). If content passed into `msgHTML()` is sourced from unfiltered user input, relative paths can map to absolute local file paths and added as attachments. Also note that `addAttachment` (just like `file_get_contents`, `passthru`, `unlink`, etc) should not be passed user-sourced params either! Reported by Yongxiang Li of Asiasecurity.
-
-PHPMailer versions prior to 5.2.20 (released December 28th 2016) are vulnerable to [CVE-2016-10045](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2016-10045) a remote code execution vulnerability, responsibly reported by [Dawid Golunski](https://legalhackers.com/advisories/PHPMailer-Exploit-Remote-Code-Exec-CVE-2016-10045-Vuln-Patch-Bypass.html), and patched by Paul Buonopane (@Zenexer).
+Please disclose any vulnerabilities found responsibly – report security issues to the maintainers privately.
-PHPMailer versions prior to 5.2.18 (released December 2016) are vulnerable to [CVE-2016-10033](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2016-10033) a critical remote code execution vulnerability, responsibly reported by [Dawid Golunski](http://legalhackers.com/advisories/PHPMailer-Exploit-Remote-Code-Exec-CVE-2016-10033-Vuln.html).
-
-See [SECURITY](https://github.com/PHPMailer/PHPMailer/tree/master/SECURITY.md) for more detail on security issues.
+See [SECURITY](https://github.com/PHPMailer/PHPMailer/tree/master/SECURITY.md) and [PHPMailer's security advisories on GitHub](https://github.com/PHPMailer/PHPMailer/security).
## Contributing
Please submit bug reports, suggestions and pull requests to the [GitHub issue tracker](https://github.com/PHPMailer/PHPMailer/issues).
We're particularly interested in fixing edge-cases, expanding test coverage and updating translations.
-If you found a mistake in the docs, or want to add something, go ahead and amend the wiki - anyone can edit it.
+If you found a mistake in the docs, or want to add something, go ahead and amend the wiki – anyone can edit it.
If you have git clones from prior to the move to the PHPMailer GitHub organisation, you'll need to update any remote URLs referencing the old GitHub location with a command like this from within your clone:
Please *don't* use the SourceForge or Google Code projects any more; they are obsolete and no longer maintained.
## Sponsorship
-Development time and resources for PHPMailer are provided by [Smartmessages.net](https://info.smartmessages.net/), a powerful email marketing system.
+Development time and resources for PHPMailer are provided by [Smartmessages.net](https://info.smartmessages.net/), the world's only privacy-first email marketing system.
+
+<a href="https://info.smartmessages.net/"><img src="https://www.smartmessages.net/img/smartmessages-logo.svg" width="550" alt="Smartmessages.net privacy-first email marketing logo"></a>
+
+Donations are very welcome, whether in beer 🍺, T-shirts 👕, or cold, hard cash 💰. Sponsorship through GitHub is a simple and convenient way to say "thank you" to PHPMailer's maintainers and contributors – just click the "Sponsor" button [on the project page](https://github.com/PHPMailer/PHPMailer). If your company uses PHPMailer, consider taking part in Tidelift's enterprise support programme.
+
+## PHPMailer For Enterprise
-<a href="https://info.smartmessages.net/"><img src="https://www.smartmessages.net/img/smartmessages-logo.svg" width="250" height="28" alt="Smartmessages email marketing"></a>
+Available as part of the Tidelift Subscription.
-Other contributions are gladly received, whether in beer 🍺, T-shirts 👕, Amazon wishlist raids, or cold, hard cash 💰. If you'd like to donate to say "thank you" to maintainers or contributors, please contact them through individual profile pages via [the contributors page](https://github.com/PHPMailer/PHPMailer/graphs/contributors).
+The maintainers of PHPMailer and thousands of other packages are working with Tidelift to deliver commercial
+support and maintenance for the open source packages you use to build your applications. Save time, reduce risk, and
+improve code health, while paying the maintainers of the exact packages you
+use. [Learn more.](https://tidelift.com/subscription/pkg/packagist-phpmailer-phpmailer?utm_source=packagist-phpmailer-phpmailer&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)
## Changelog
See [changelog](changelog.md).
## History
- PHPMailer was originally written in 2001 by Brent R. Matzelle as a [SourceForge project](http://sourceforge.net/projects/phpmailer/).
-- Marcus Bointon (coolbru on SF) and Andy Prevost (codeworxtech) took over the project in 2004.
+- [Marcus Bointon](https://github.com/Synchro) (`coolbru` on SF) and Andy Prevost (`codeworxtech`) took over the project in 2004.
- Became an Apache incubator project on Google Code in 2010, managed by Jim Jagielski.
-- Marcus created his fork on [GitHub](https://github.com/Synchro/PHPMailer) in 2008.
+- Marcus created [his fork on GitHub](https://github.com/Synchro/PHPMailer) in 2008.
- Jim and Marcus decide to join forces and use GitHub as the canonical and official repo for PHPMailer in 2013.
-- PHPMailer moves to the [PHPMailer organisation](https://github.com/PHPMailer) on GitHub in 2013.
+- PHPMailer moves to [the PHPMailer organisation](https://github.com/PHPMailer) on GitHub in 2013.
### What's changed since moving from SourceForge?
- Official successor to the SourceForge and Google Code projects.
- Test suite.
-- Continuous integration with Travis-CI.
+- Continuous integration with Github Actions.
- Composer support.
- Public development.
- Additional languages and language strings.
<?php
+
/**
* PHPMailer - PHP email creation and transport class.
* PHP Version 5.5.
* @author Jim Jagielski (jimjag) <jimjag@gmail.com>
* @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
* @author Brent R. Matzelle (original founder)
- * @copyright 2012 - 2019 Marcus Bointon
+ * @copyright 2012 - 2020 Marcus Bointon
* @copyright 2010 - 2012 Jim Jagielski
* @copyright 2004 - 2009 Andy Prevost
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* Options: null (default), 1 = High, 3 = Normal, 5 = low.
* When null, the header is not set at all.
*
- * @var int
+ * @var int|null
*/
public $Priority;
* SMTP class debug output mode.
* Debug output level.
* Options:
- * * SMTP::DEBUG_OFF: No output
- * * SMTP::DEBUG_CLIENT: Client messages
- * * SMTP::DEBUG_SERVER: Client and server messages
- * * SMTP::DEBUG_CONNECTION: As SERVER plus connection status
- * * SMTP::DEBUG_LOWLEVEL: Noisy, low-level data output, rarely needed
+ * @see SMTP::DEBUG_OFF: No output
+ * @see SMTP::DEBUG_CLIENT: Client messages
+ * @see SMTP::DEBUG_SERVER: Client and server messages
+ * @see SMTP::DEBUG_CONNECTION: As SERVER plus connection status
+ * @see SMTP::DEBUG_LOWLEVEL: Noisy, low-level data output, rarely needed
*
* @see SMTP::$do_debug
*
public $Debugoutput = 'echo';
/**
- * Whether to keep SMTP connection open after each message.
- * If this is set to true then to close the connection
- * requires an explicit call to smtpClose().
+ * Whether to keep the SMTP connection open after each message.
+ * If this is set to true then the connection will remain open after a send,
+ * and closing the connection will require an explicit call to smtpClose().
+ * It's a good idea to use this if you are sending multiple messages as it reduces overhead.
+ * See the mailing list example for how to use it.
*
* @var bool
*/
* Only supported in `mail` and `sendmail` transports, not in SMTP.
*
* @var bool
+ *
+ * @deprecated 6.0.0 PHPMailer isn't a mailing list manager!
*/
public $SingleTo = false;
*
* @var string
*/
- const VERSION = '6.1.4';
+ const VERSION = '6.5.0';
/**
* Error severity: message only, continue processing.
const STOP_CRITICAL = 2;
/**
- * SMTP RFC standard line ending.
+ * The SMTP standard CRLF line break.
+ * If you want to change line break format, change static::$LE, not this.
+ */
+ const CRLF = "\r\n";
+
+ /**
+ * "Folding White Space" a white space string used for line folding.
+ */
+ const FWS = ' ';
+
+ /**
+ * SMTP RFC standard line ending; Carriage Return, Line Feed.
*
* @var string
*/
- protected static $LE = "\r\n";
+ protected static $LE = self::CRLF;
/**
* The maximum line length supported by mail().
$subject = $this->encodeHeader($this->secureHeader($subject));
}
//Calling mail() with null params breaks
+ $this->edebug('Sending with mail()');
+ $this->edebug('Sendmail path: ' . ini_get('sendmail_path'));
+ $this->edebug("Envelope sender: {$this->Sender}");
+ $this->edebug("To: {$to}");
+ $this->edebug("Subject: {$subject}");
+ $this->edebug("Headers: {$header}");
if (!$this->UseSendmailOptions || null === $params) {
$result = @mail($to, $subject, $body, $header);
} else {
+ $this->edebug("Additional params: {$params}");
$result = @mail($to, $subject, $body, $header, $params);
}
-
+ $this->edebug('Result: ' . ($result ? 'true' : 'false'));
return $result;
}
/**
- * Output debugging info via user-defined method.
- * Only generates output if SMTP debug output is enabled (@see SMTP::$do_debug).
+ * Output debugging info via a user-defined method.
+ * Only generates output if debug output is enabled.
*
* @see PHPMailer::$Debugoutput
* @see PHPMailer::$SMTPDebug
switch ($this->Debugoutput) {
case 'error_log':
//Don't output, just log
+ /** @noinspection ForgottenDebugOutputInspection */
error_log($str);
break;
case 'html':
$name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
$pos = strrpos($address, '@');
if (false === $pos) {
- // At-sign is missing.
+ //At-sign is missing.
$error_message = sprintf(
'%s (%s): %s',
$this->lang('invalid_address'),
return false;
}
$params = [$kind, $address, $name];
- // Enqueue addresses with IDN until we know the PHPMailer::$CharSet.
+ //Enqueue addresses with IDN until we know the PHPMailer::$CharSet.
if (static::idnSupported() && $this->has8bitChars(substr($address, ++$pos))) {
if ('Reply-To' !== $kind) {
if (!array_key_exists($address, $this->RecipientsQueue)) {
return false;
}
- // Immediately add standard addresses without IDN.
+ //Immediately add standard addresses without IDN.
return call_user_func_array([$this, 'addAnAddress'], $params);
}
//Use this built-in parser if it's available
$list = imap_rfc822_parse_adrlist($addrstr, '');
foreach ($list as $address) {
- if (('.SYNTAX-ERROR.' !== $address->host) && static::validateAddress(
- $address->mailbox . '@' . $address->host
- )) {
+ if (
+ ('.SYNTAX-ERROR.' !== $address->host) && static::validateAddress(
+ $address->mailbox . '@' . $address->host
+ )
+ ) {
+ //Decode the name part if it's present and encoded
+ if (
+ property_exists($address, 'personal') &&
+ extension_loaded('mbstring') &&
+ preg_match('/^=\?.*\?=$/', $address->personal)
+ ) {
+ $address->personal = mb_decode_mimeheader($address->personal);
+ }
+
$addresses[] = [
'name' => (property_exists($address, 'personal') ? $address->personal : ''),
'address' => $address->mailbox . '@' . $address->host,
} else {
list($name, $email) = explode('<', $address);
$email = trim(str_replace('>', '', $email));
+ $name = trim($name);
if (static::validateAddress($email)) {
+ //If this name is encoded, decode it
+ if (preg_match('/^=\?.*\?=$/', $name)) {
+ $name = mb_decode_mimeheader($name);
+ }
$addresses[] = [
- 'name' => trim(str_replace(['"', "'"], '', $name)),
+ //Remove any surrounding quotes and spaces from the name
+ 'name' => trim($name, '\'" '),
'address' => $email,
];
}
{
$address = trim($address);
$name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
- // Don't validate now addresses with IDN. Will be done in send().
+ //Don't validate now addresses with IDN. Will be done in send().
$pos = strrpos($address, '@');
- if ((false === $pos)
+ if (
+ (false === $pos)
|| ((!$this->has8bitChars(substr($address, ++$pos)) || !static::idnSupported())
&& !static::validateAddress($address))
) {
if (null === $patternselect) {
$patternselect = static::$validator;
}
- if (is_callable($patternselect)) {
- return $patternselect($address);
+ //Don't allow strings as callables, see SECURITY.md and CVE-2021-3603
+ if (is_callable($patternselect) && !is_string($patternselect)) {
+ return call_user_func($patternselect, $address);
}
//Reject line breaks in addresses; it's valid RFC5322, but not RFC5321
if (strpos($address, "\n") !== false || strpos($address, "\r") !== false) {
/*
* This is the pattern used in the HTML5 spec for validation of 'email' type form input elements.
*
- * @see http://www.whatwg.org/specs/web-apps/current-work/#e-mail-state-(type=email)
+ * @see https://html.spec.whatwg.org/#e-mail-state-(type=email)
*/
return (bool) preg_match(
'/^[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}' .
*/
public function punyencodeAddress($address)
{
- // Verify we have required functions, CharSet, and at-sign.
+ //Verify we have required functions, CharSet, and at-sign.
$pos = strrpos($address, '@');
- if (!empty($this->CharSet) &&
+ if (
+ !empty($this->CharSet) &&
false !== $pos &&
static::idnSupported()
) {
$domain = substr($address, ++$pos);
- // Verify CharSet string is a valid one, and domain properly encoded in this CharSet.
+ //Verify CharSet string is a valid one, and domain properly encoded in this CharSet.
if ($this->has8bitChars($domain) && @mb_check_encoding($domain, $this->CharSet)) {
- $domain = mb_convert_encoding($domain, 'UTF-8', $this->CharSet);
+ //Convert the domain from whatever charset it's in to UTF-8
+ $domain = mb_convert_encoding($domain, self::CHARSET_UTF8, $this->CharSet);
//Ignore IDE complaints about this line - method signature changed in PHP 5.4
$errorcode = 0;
if (defined('INTL_IDNA_VARIANT_UTS46')) {
- $punycode = idn_to_ascii($domain, $errorcode, INTL_IDNA_VARIANT_UTS46);
+ //Use the current punycode standard (appeared in PHP 7.2)
+ $punycode = idn_to_ascii($domain, $errorcode, \INTL_IDNA_VARIANT_UTS46);
} elseif (defined('INTL_IDNA_VARIANT_2003')) {
- $punycode = idn_to_ascii($domain, $errorcode, INTL_IDNA_VARIANT_2003);
+ //Fall back to this old, deprecated/removed encoding
+ $punycode = idn_to_ascii($domain, $errorcode, \INTL_IDNA_VARIANT_2003);
} else {
+ //Fall back to a default we don't know about
$punycode = idn_to_ascii($domain, $errorcode);
}
if (false !== $punycode) {
*/
public function preSend()
{
- if ('smtp' === $this->Mailer
- || ('mail' === $this->Mailer && stripos(PHP_OS, 'WIN') === 0)
+ if (
+ 'smtp' === $this->Mailer
+ || ('mail' === $this->Mailer && (\PHP_VERSION_ID >= 80000 || stripos(PHP_OS, 'WIN') === 0))
) {
//SMTP mandates RFC-compliant line endings
//and it's also used with mail() on Windows
- static::setLE("\r\n");
+ static::setLE(self::CRLF);
} else {
//Maintain backward compatibility with legacy Linux command line mailers
static::setLE(PHP_EOL);
}
//Check for buggy PHP versions that add a header with an incorrect line break
- if ('mail' === $this->Mailer
- && ((PHP_VERSION_ID >= 70000 && PHP_VERSION_ID < 70017)
- || (PHP_VERSION_ID >= 70100 && PHP_VERSION_ID < 70103))
+ if (
+ 'mail' === $this->Mailer
+ && ((\PHP_VERSION_ID >= 70000 && \PHP_VERSION_ID < 70017)
+ || (\PHP_VERSION_ID >= 70100 && \PHP_VERSION_ID < 70103))
&& ini_get('mail.add_x_header') === '1'
&& stripos(PHP_OS, 'WIN') === 0
) {
}
try {
- $this->error_count = 0; // Reset errors
+ $this->error_count = 0; //Reset errors
$this->mailHeader = '';
- // Dequeue recipient and Reply-To addresses with IDN
+ //Dequeue recipient and Reply-To addresses with IDN
foreach (array_merge($this->RecipientsQueue, $this->ReplyToQueue) as $params) {
$params[1] = $this->punyencodeAddress($params[1]);
call_user_func_array([$this, 'addAnAddress'], $params);
throw new Exception($this->lang('provide_address'), self::STOP_CRITICAL);
}
- // Validate From, Sender, and ConfirmReadingTo addresses
+ //Validate From, Sender, and ConfirmReadingTo addresses
foreach (['From', 'Sender', 'ConfirmReadingTo'] as $address_kind) {
$this->$address_kind = trim($this->$address_kind);
if (empty($this->$address_kind)) {
}
}
- // Set whether the message is multipart/alternative
+ //Set whether the message is multipart/alternative
if ($this->alternativeExists()) {
$this->ContentType = static::CONTENT_TYPE_MULTIPART_ALTERNATIVE;
}
$this->setMessageType();
- // Refuse to send an empty message unless we are specifically allowing it
+ //Refuse to send an empty message unless we are specifically allowing it
if (!$this->AllowEmpty && empty($this->Body)) {
throw new Exception($this->lang('empty_message'), self::STOP_CRITICAL);
}
//Trim subject consistently
$this->Subject = trim($this->Subject);
- // Create body before headers in case body makes changes to headers (e.g. altering transfer encoding)
+ //Create body before headers in case body makes changes to headers (e.g. altering transfer encoding)
$this->MIMEHeader = '';
$this->MIMEBody = $this->createBody();
- // createBody may have added some headers, so retain them
+ //createBody may have added some headers, so retain them
$tempheaders = $this->MIMEHeader;
$this->MIMEHeader = $this->createHeader();
$this->MIMEHeader .= $tempheaders;
- // To capture the complete message when using mail(), create
- // an extra header list which createHeader() doesn't fold in
+ //To capture the complete message when using mail(), create
+ //an extra header list which createHeader() doesn't fold in
if ('mail' === $this->Mailer) {
if (count($this->to) > 0) {
$this->mailHeader .= $this->addrAppend('To', $this->to);
);
}
- // Sign with DKIM if enabled
- if (!empty($this->DKIM_domain)
+ //Sign with DKIM if enabled
+ if (
+ !empty($this->DKIM_domain)
&& !empty($this->DKIM_selector)
&& (!empty($this->DKIM_private_string)
|| (!empty($this->DKIM_private)
$this->encodeHeader($this->secureHeader($this->Subject)),
$this->MIMEBody
);
- $this->MIMEHeader = rtrim($this->MIMEHeader, "\r\n ") . static::$LE .
+ $this->MIMEHeader = static::stripTrailingWSP($this->MIMEHeader) . static::$LE .
static::normalizeBreaks($header_dkim) . static::$LE;
}
public function postSend()
{
try {
- // Choose the mailer and send through it
+ //Choose the mailer and send through it
switch ($this->Mailer) {
case 'sendmail':
case 'qmail':
return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
}
} catch (Exception $exc) {
+ if ($this->Mailer === 'smtp' && $this->SMTPKeepAlive == true) {
+ $this->smtp->reset();
+ }
$this->setError($exc->getMessage());
$this->edebug($exc->getMessage());
if ($this->exceptions) {
*/
protected function sendmailSend($header, $body)
{
- $header = rtrim($header, "\r\n ") . static::$LE . static::$LE;
-
- // CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped.
- if (!empty($this->Sender) && self::isShellSafe($this->Sender)) {
- if ('qmail' === $this->Mailer) {
+ if ($this->Mailer === 'qmail') {
+ $this->edebug('Sending with qmail');
+ } else {
+ $this->edebug('Sending with sendmail');
+ }
+ $header = static::stripTrailingWSP($header) . static::$LE . static::$LE;
+ //This sets the SMTP envelope sender which gets turned into a return-path header by the receiver
+ //A space after `-f` is optional, but there is a long history of its presence
+ //causing problems, so we don't use one
+ //Exim docs: http://www.exim.org/exim-html-current/doc/html/spec_html/ch-the_exim_command_line.html
+ //Sendmail docs: http://www.sendmail.org/~ca/email/man/sendmail.html
+ //Qmail docs: http://www.qmail.org/man/man8/qmail-inject.html
+ //Example problem: https://www.drupal.org/node/1057954
+ if (empty($this->Sender) && !empty(ini_get('sendmail_from'))) {
+ //PHP config has a sender address we can use
+ $this->Sender = ini_get('sendmail_from');
+ }
+ //CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped.
+ if (!empty($this->Sender) && static::validateAddress($this->Sender) && self::isShellSafe($this->Sender)) {
+ if ($this->Mailer === 'qmail') {
$sendmailFmt = '%s -f%s';
} else {
$sendmailFmt = '%s -oi -f%s -t';
}
- } elseif ('qmail' === $this->Mailer) {
- $sendmailFmt = '%s';
} else {
+ //allow sendmail to choose a default envelope sender. It may
+ //seem preferable to force it to use the From header as with
+ //SMTP, but that introduces new problems (see
+ //<https://github.com/PHPMailer/PHPMailer/issues/2298>), and
+ //it has historically worked this way.
$sendmailFmt = '%s -oi -t';
}
$sendmail = sprintf($sendmailFmt, escapeshellcmd($this->Sendmail), $this->Sender);
+ $this->edebug('Sendmail path: ' . $this->Sendmail);
+ $this->edebug('Sendmail command: ' . $sendmail);
+ $this->edebug('Envelope sender: ' . $this->Sender);
+ $this->edebug("Headers: {$header}");
if ($this->SingleTo) {
foreach ($this->SingleToArray as $toAddr) {
if (!$mail) {
throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
}
+ $this->edebug("To: {$toAddr}");
fwrite($mail, 'To: ' . $toAddr . "\n");
fwrite($mail, $header);
fwrite($mail, $body);
$result = pclose($mail);
+ $addrinfo = static::parseAddresses($toAddr);
$this->doCallback(
($result === 0),
- [$toAddr],
+ [[$addrinfo['address'], $addrinfo['name']]],
$this->cc,
$this->bcc,
$this->Subject,
$this->From,
[]
);
+ $this->edebug("Result: " . ($result === 0 ? 'true' : 'false'));
if (0 !== $result) {
throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
}
$this->From,
[]
);
+ $this->edebug("Result: " . ($result === 0 ? 'true' : 'false'));
if (0 !== $result) {
throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
}
*/
protected static function isShellSafe($string)
{
- // Future-proof
- if (escapeshellcmd($string) !== $string
+ //Future-proof
+ if (
+ escapeshellcmd($string) !== $string
|| !in_array(escapeshellarg($string), ["'$string'", "\"$string\""])
) {
return false;
for ($i = 0; $i < $length; ++$i) {
$c = $string[$i];
- // All other characters have a special meaning in at least one common shell, including = and +.
- // Full stop (.) has a special meaning in cmd.exe, but its impact should be negligible here.
- // Note that this does permit non-Latin alphanumeric characters based on the current locale.
+ //All other characters have a special meaning in at least one common shell, including = and +.
+ //Full stop (.) has a special meaning in cmd.exe, but its impact should be negligible here.
+ //Note that this does permit non-Latin alphanumeric characters based on the current locale.
if (!ctype_alnum($c) && strpos('@_-.', $c) === false) {
return false;
}
*/
protected static function isPermittedPath($path)
{
- return !preg_match('#^[a-z]+://#i', $path);
+ //Matches scheme definition from https://tools.ietf.org/html/rfc3986#section-3.1
+ return !preg_match('#^[a-z][a-z\d+.-]*://#i', $path);
+ }
+
+ /**
+ * Check whether a file path is safe, accessible, and readable.
+ *
+ * @param string $path A relative or absolute path to a file
+ *
+ * @return bool
+ */
+ protected static function fileIsAccessible($path)
+ {
+ if (!static::isPermittedPath($path)) {
+ return false;
+ }
+ $readable = file_exists($path);
+ //If not a UNC path (expected to start with \\), check read permission, see #2069
+ if (strpos($path, '\\\\') !== 0) {
+ $readable = $readable && is_readable($path);
+ }
+ return $readable;
}
/**
*/
protected function mailSend($header, $body)
{
- $header = rtrim($header, "\r\n ") . static::$LE . static::$LE;
+ $header = static::stripTrailingWSP($header) . static::$LE . static::$LE;
$toArr = [];
foreach ($this->to as $toaddr) {
//Sendmail docs: http://www.sendmail.org/~ca/email/man/sendmail.html
//Qmail docs: http://www.qmail.org/man/man8/qmail-inject.html
//Example problem: https://www.drupal.org/node/1057954
- // CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped.
- if (!empty($this->Sender) && static::validateAddress($this->Sender) && self::isShellSafe($this->Sender)) {
- $params = sprintf('-f%s', $this->Sender);
+ //CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped.
+ if (empty($this->Sender) && !empty(ini_get('sendmail_from'))) {
+ //PHP config has a sender address we can use
+ $this->Sender = ini_get('sendmail_from');
}
if (!empty($this->Sender) && static::validateAddress($this->Sender)) {
+ if (self::isShellSafe($this->Sender)) {
+ $params = sprintf('-f%s', $this->Sender);
+ }
$old_from = ini_get('sendmail_from');
ini_set('sendmail_from', $this->Sender);
}
if ($this->SingleTo && count($toArr) > 1) {
foreach ($toArr as $toAddr) {
$result = $this->mailPassthru($toAddr, $this->Subject, $body, $header, $params);
- $this->doCallback($result, [$toAddr], $this->cc, $this->bcc, $this->Subject, $body, $this->From, []);
+ $addrinfo = static::parseAddresses($toAddr);
+ $this->doCallback(
+ $result,
+ [[$addrinfo['address'], $addrinfo['name']]],
+ $this->cc,
+ $this->bcc,
+ $this->Subject,
+ $body,
+ $this->From,
+ []
+ );
}
} else {
$result = $this->mailPassthru($to, $this->Subject, $body, $header, $params);
*/
protected function smtpSend($header, $body)
{
- $header = rtrim($header, "\r\n ") . static::$LE . static::$LE;
+ $header = static::stripTrailingWSP($header) . static::$LE . static::$LE;
$bad_rcpt = [];
if (!$this->smtpConnect($this->SMTPOptions)) {
throw new Exception($this->lang('smtp_connect_failed'), self::STOP_CRITICAL);
}
$callbacks = [];
- // Attempt to send to all recipients
+ //Attempt to send to all recipients
foreach ([$this->to, $this->cc, $this->bcc] as $togroup) {
foreach ($togroup as $to) {
if (!$this->smtp->recipient($to[0], $this->dsn)) {
$isSent = true;
}
- $callbacks[] = ['issent'=>$isSent, 'to'=>$to[0]];
+ $callbacks[] = ['issent' => $isSent, 'to' => $to[0], 'name' => $to[1]];
}
}
- // Only send the DATA command if we have viable recipients
+ //Only send the DATA command if we have viable recipients
if ((count($this->all_recipients) > count($bad_rcpt)) && !$this->smtp->data($header . $body)) {
throw new Exception($this->lang('data_not_accepted'), self::STOP_CRITICAL);
}
foreach ($callbacks as $cb) {
$this->doCallback(
$cb['issent'],
- [$cb['to']],
+ [[$cb['to'], $cb['name']]],
[],
[],
$this->Subject,
$options = $this->SMTPOptions;
}
- // Already connected?
+ //Already connected?
if ($this->smtp->connected()) {
return true;
}
foreach ($hosts as $hostentry) {
$hostinfo = [];
- if (!preg_match(
- '/^(?:(ssl|tls):\/\/)?(.+?)(?::(\d+))?$/',
- trim($hostentry),
- $hostinfo
- )) {
+ if (
+ !preg_match(
+ '/^(?:(ssl|tls):\/\/)?(.+?)(?::(\d+))?$/',
+ trim($hostentry),
+ $hostinfo
+ )
+ ) {
$this->edebug($this->lang('invalid_hostentry') . ' ' . trim($hostentry));
- // Not a valid host entry
+ //Not a valid host entry
continue;
}
- // $hostinfo[1]: optional ssl or tls prefix
- // $hostinfo[2]: the hostname
- // $hostinfo[3]: optional port number
- // The host string prefix can temporarily override the current setting for SMTPSecure
- // If it's not specified, the default value is used
+ //$hostinfo[1]: optional ssl or tls prefix
+ //$hostinfo[2]: the hostname
+ //$hostinfo[3]: optional port number
+ //The host string prefix can temporarily override the current setting for SMTPSecure
+ //If it's not specified, the default value is used
//Check the host name is a valid name or IP address before trying to use it
if (!static::isValidHost($hostinfo[2])) {
$tls = (static::ENCRYPTION_STARTTLS === $this->SMTPSecure);
if ('ssl' === $hostinfo[1] || ('' === $hostinfo[1] && static::ENCRYPTION_SMTPS === $this->SMTPSecure)) {
$prefix = 'ssl://';
- $tls = false; // Can't have SSL and TLS at the same time
+ $tls = false; //Can't have SSL and TLS at the same time
$secure = static::ENCRYPTION_SMTPS;
} elseif ('tls' === $hostinfo[1]) {
$tls = true;
- // tls doesn't use a prefix
+ //TLS doesn't use a prefix
$secure = static::ENCRYPTION_STARTTLS;
}
//Do we need the OpenSSL extension?
}
$host = $hostinfo[2];
$port = $this->Port;
- if (array_key_exists(3, $hostinfo) && is_numeric($hostinfo[3]) && $hostinfo[3] > 0 && $hostinfo[3] < 65536) {
+ if (
+ array_key_exists(3, $hostinfo) &&
+ is_numeric($hostinfo[3]) &&
+ $hostinfo[3] > 0 &&
+ $hostinfo[3] < 65536
+ ) {
$port = (int) $hostinfo[3];
}
if ($this->smtp->connect($prefix . $host, $port, $this->Timeout, $options)) {
}
$this->smtp->hello($hello);
//Automatically enable TLS encryption if:
- // * it's not disabled
- // * we have openssl extension
- // * we are not already using SSL
- // * the server offers STARTTLS
+ //* it's not disabled
+ //* we have openssl extension
+ //* we are not already using SSL
+ //* the server offers STARTTLS
if ($this->SMTPAutoTLS && $sslext && 'ssl' !== $secure && $this->smtp->getServerExt('STARTTLS')) {
$tls = true;
}
if (!$this->smtp->startTLS()) {
throw new Exception($this->lang('connect_host'));
}
- // We must resend EHLO after TLS negotiation
+ //We must resend EHLO after TLS negotiation
$this->smtp->hello($hello);
}
- if ($this->SMTPAuth && !$this->smtp->authenticate(
- $this->Username,
- $this->Password,
- $this->AuthType,
- $this->oauth
- )) {
+ if (
+ $this->SMTPAuth && !$this->smtp->authenticate(
+ $this->Username,
+ $this->Password,
+ $this->AuthType,
+ $this->oauth
+ )
+ ) {
throw new Exception($this->lang('authenticate'));
}
} catch (Exception $exc) {
$lastexception = $exc;
$this->edebug($exc->getMessage());
- // We must have connected, but then failed TLS or Auth, so close connection nicely
+ //We must have connected, but then failed TLS or Auth, so close connection nicely
$this->smtp->quit();
}
}
}
- // If we get here, all connection attempts have failed, so close connection hard
+ //If we get here, all connection attempts have failed, so close connection hard
$this->smtp->close();
- // As we've caught all exceptions, just report whatever the last one was
+ //As we've caught all exceptions, just report whatever the last one was
if ($this->exceptions && null !== $lastexception) {
throw $lastexception;
}
* The default language is English.
*
* @param string $langcode ISO 639-1 2-character language code (e.g. French is "fr")
- * @param string $lang_path Path to the language file directory, with trailing separator (slash)
+ * @param string $lang_path Path to the language file directory, with trailing separator (slash).D
+ * Do not set this from user input!
*
* @return bool
*/
public function setLanguage($langcode = 'en', $lang_path = '')
{
- // Backwards compatibility for renamed language codes
+ //Backwards compatibility for renamed language codes
$renamed_langcodes = [
'br' => 'pt_br',
'cz' => 'cs',
'se' => 'sv',
'rs' => 'sr',
'tg' => 'tl',
+ 'am' => 'hy',
];
- if (isset($renamed_langcodes[$langcode])) {
+ if (array_key_exists($langcode, $renamed_langcodes)) {
$langcode = $renamed_langcodes[$langcode];
}
- // Define full set of translatable strings in English
+ //Define full set of translatable strings in English
$PHPMAILER_LANG = [
'authenticate' => 'SMTP Error: Could not authenticate.',
'connect_host' => 'SMTP Error: Could not connect to SMTP host.',
'extension_missing' => 'Extension missing: ',
];
if (empty($lang_path)) {
- // Calculate an absolute path so it can work if CWD is not here
+ //Calculate an absolute path so it can work if CWD is not here
$lang_path = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'language' . DIRECTORY_SEPARATOR;
}
//Validate $langcode
}
$foundlang = true;
$lang_file = $lang_path . 'phpmailer.lang-' . $langcode . '.php';
- // There is no English translation file
+ //There is no English translation file
if ('en' !== $langcode) {
- // Make sure language file path is readable
- if (!static::isPermittedPath($lang_file) || !file_exists($lang_file)) {
+ //Make sure language file path is readable
+ if (!static::fileIsAccessible($lang_file)) {
$foundlang = false;
} else {
- // Overwrite language-specific strings.
- // This way we'll never have missing translation keys.
- $foundlang = include $lang_file;
+ //$foundlang = include $lang_file;
+ $lines = file($lang_file);
+ foreach ($lines as $line) {
+ //Translation file lines look like this:
+ //$PHPMAILER_LANG['authenticate'] = 'SMTP-Fehler: Authentifizierung fehlgeschlagen.';
+ //These files are parsed as text and not PHP so as to avoid the possibility of code injection
+ //See https://blog.stevenlevithan.com/archives/match-quoted-string
+ $matches = [];
+ if (
+ preg_match(
+ '/^\$PHPMAILER_LANG\[\'([a-z\d_]+)\'\]\s*=\s*(["\'])(.+)*?\2;/',
+ $line,
+ $matches
+ ) &&
+ //Ignore unknown translation keys
+ array_key_exists($matches[1], $PHPMAILER_LANG)
+ ) {
+ //Overwrite language-specific strings so we'll never have missing translation keys.
+ $PHPMAILER_LANG[$matches[1]] = (string)$matches[3];
+ }
+ }
}
}
$this->language = $PHPMAILER_LANG;
- return (bool) $foundlang; // Returns false if language not found
+ return $foundlang; //Returns false if language not found
}
/**
*/
public function addrFormat($addr)
{
- if (empty($addr[1])) { // No name provided
+ if (empty($addr[1])) { //No name provided
return $this->secureHeader($addr[0]);
}
} else {
$soft_break = static::$LE;
}
- // If utf-8 encoding is used, we will need to make sure we don't
- // split multibyte characters when we wrap
+ //If utf-8 encoding is used, we will need to make sure we don't
+ //split multibyte characters when we wrap
$is_utf8 = static::CHARSET_UTF8 === strtolower($this->CharSet);
$lelen = strlen(static::$LE);
$crlflen = strlen(static::$LE);
$lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
$encodedCharPos = strpos($lastChunk, '=');
if (false !== $encodedCharPos) {
- // Found start of encoded character byte within $lookBack block.
- // Check the encoded byte value (the 2 chars after the '=')
+ //Found start of encoded character byte within $lookBack block.
+ //Check the encoded byte value (the 2 chars after the '=')
$hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
$dec = hexdec($hex);
if ($dec < 128) {
- // Single byte character.
- // If the encoded char was found at pos 0, it will fit
- // otherwise reduce maxLength to start of the encoded char
+ //Single byte character.
+ //If the encoded char was found at pos 0, it will fit
+ //otherwise reduce maxLength to start of the encoded char
if ($encodedCharPos > 0) {
$maxLength -= $lookBack - $encodedCharPos;
}
$foundSplitPos = true;
} elseif ($dec >= 192) {
- // First byte of a multi byte character
- // Reduce maxLength to split at start of character
+ //First byte of a multi byte character
+ //Reduce maxLength to split at start of character
$maxLength -= $lookBack - $encodedCharPos;
$foundSplitPos = true;
} elseif ($dec < 192) {
- // Middle byte of a multi byte character, look further back
+ //Middle byte of a multi byte character, look further back
$lookBack += 3;
}
} else {
- // No encoded character found
+ //No encoded character found
$foundSplitPos = true;
}
}
$result .= $this->headerLine('Date', '' === $this->MessageDate ? self::rfcDate() : $this->MessageDate);
- // To be created automatically by mail()
- if ($this->SingleTo) {
- if ('mail' !== $this->Mailer) {
+ //The To header is created automatically by mail(), so needs to be omitted here
+ if ('mail' !== $this->Mailer) {
+ if ($this->SingleTo) {
foreach ($this->to as $toaddr) {
$this->SingleToArray[] = $this->addrFormat($toaddr);
}
- }
- } elseif (count($this->to) > 0) {
- if ('mail' !== $this->Mailer) {
+ } elseif (count($this->to) > 0) {
$result .= $this->addrAppend('To', $this->to);
+ } elseif (count($this->cc) === 0) {
+ $result .= $this->headerLine('To', 'undisclosed-recipients:;');
}
- } elseif (count($this->cc) === 0) {
- $result .= $this->headerLine('To', 'undisclosed-recipients:;');
}
-
$result .= $this->addrAppend('From', [[trim($this->From), $this->FromName]]);
- // sendmail and mail() extract Cc from the header before sending
+ //sendmail and mail() extract Cc from the header before sending
if (count($this->cc) > 0) {
$result .= $this->addrAppend('Cc', $this->cc);
}
- // sendmail and mail() extract Bcc from the header before sending
- if ((
+ //sendmail and mail() extract Bcc from the header before sending
+ if (
+ (
'sendmail' === $this->Mailer || 'qmail' === $this->Mailer || 'mail' === $this->Mailer
)
&& count($this->bcc) > 0
$result .= $this->addrAppend('Reply-To', $this->ReplyTo);
}
- // mail() sets the subject itself
+ //mail() sets the subject itself
if ('mail' !== $this->Mailer) {
$result .= $this->headerLine('Subject', $this->encodeHeader($this->secureHeader($this->Subject)));
}
- // Only allow a custom message ID if it conforms to RFC 5322 section 3.6.4
- // https://tools.ietf.org/html/rfc5322#section-3.6.4
+ //Only allow a custom message ID if it conforms to RFC 5322 section 3.6.4
+ //https://tools.ietf.org/html/rfc5322#section-3.6.4
if ('' !== $this->MessageID && preg_match('/^<.*@.*>$/', $this->MessageID)) {
$this->lastMessageID = $this->MessageID;
} else {
$result .= $this->headerLine('Disposition-Notification-To', '<' . $this->ConfirmReadingTo . '>');
}
- // Add custom headers
+ //Add custom headers
foreach ($this->CustomHeader as $header) {
$result .= $this->headerLine(
trim($header[0]),
$result .= $this->textLine(' boundary="' . $this->boundary[1] . '"');
break;
default:
- // Catches case 'plain': and case '':
+ //Catches case 'plain': and case '':
$result .= $this->textLine('Content-Type: ' . $this->ContentType . '; charset=' . $this->CharSet);
$ismultipart = false;
break;
}
- // RFC1341 part 5 says 7bit is assumed if not specified
+ //RFC1341 part 5 says 7bit is assumed if not specified
if (static::ENCODING_7BIT !== $this->Encoding) {
- // RFC 2045 section 6.4 says multipart MIME parts may only use 7bit, 8bit or binary CTE
+ //RFC 2045 section 6.4 says multipart MIME parts may only use 7bit, 8bit or binary CTE
if ($ismultipart) {
if (static::ENCODING_8BIT === $this->Encoding) {
$result .= $this->headerLine('Content-Transfer-Encoding', static::ENCODING_8BIT);
}
- // The only remaining alternatives are quoted-printable and base64, which are both 7bit compatible
+ //The only remaining alternatives are quoted-printable and base64, which are both 7bit compatible
} else {
$result .= $this->headerLine('Content-Transfer-Encoding', $this->Encoding);
}
}
- if ('mail' !== $this->Mailer) {
-// $result .= static::$LE;
- }
-
return $result;
}
*/
public function getSentMIMEMessage()
{
- return rtrim($this->MIMEHeader . $this->mailHeader, "\n\r") . static::$LE . static::$LE . $this->MIMEBody;
+ return static::stripTrailingWSP($this->MIMEHeader . $this->mailHeader) .
+ static::$LE . static::$LE . $this->MIMEBody;
}
/**
$altBodyEncoding = static::ENCODING_QUOTED_PRINTABLE;
}
//Use this as a preamble in all multipart message types
- $mimepre = 'This is a multi-part message in MIME format.' . static::$LE;
+ $mimepre = 'This is a multi-part message in MIME format.' . static::$LE . static::$LE;
switch ($this->message_type) {
case 'inline':
$body .= $mimepre;
$body .= $this->attachAll('attachment', $this->boundary[1]);
break;
default:
- // Catch case 'plain' and case '', applies to simple `text/plain` and `text/html` body content types
+ //Catch case 'plain' and case '', applies to simple `text/plain` and `text/html` body content types
//Reset the `Encoding` property in case we changed it for line length reasons
$this->Encoding = $bodyEncoding;
$body .= $this->encodeString($this->Body, $this->Encoding);
$result .= $this->textLine('--' . $boundary);
$result .= sprintf('Content-Type: %s; charset=%s', $contentType, $charSet);
$result .= static::$LE;
- // RFC1341 part 5 says 7bit is assumed if not specified
+ //RFC1341 part 5 says 7bit is assumed if not specified
if (static::ENCODING_7BIT !== $encoding) {
$result .= $this->headerLine('Content-Transfer-Encoding', $encoding);
}
* @param string $path Path to the attachment
* @param string $name Overrides the attachment name
* @param string $encoding File encoding (see $Encoding)
- * @param string $type File extension (MIME) type
+ * @param string $type MIME type, e.g. `image/jpeg`; determined automatically from $path if not specified
* @param string $disposition Disposition to use
*
* @throws Exception
$disposition = 'attachment'
) {
try {
- if (!static::isPermittedPath($path) || !@is_file($path)) {
+ if (!static::fileIsAccessible($path)) {
throw new Exception($this->lang('file_access') . $path, self::STOP_CONTINUE);
}
- // If a MIME type is not specified, try to work it out from the file name
+ //If a MIME type is not specified, try to work it out from the file name
if ('' === $type) {
$type = static::filenameToType($path);
}
if ('' === $name) {
$name = $filename;
}
-
if (!$this->validateEncoding($encoding)) {
throw new Exception($this->lang('encoding') . $encoding);
}
2 => $name,
3 => $encoding,
4 => $type,
- 5 => false, // isStringAttachment
+ 5 => false, //isStringAttachment
6 => $disposition,
7 => $name,
];
*/
protected function attachAll($disposition_type, $boundary)
{
- // Return text of body
+ //Return text of body
$mime = [];
$cidUniq = [];
$incl = [];
- // Add all attachments
+ //Add all attachments
foreach ($this->attachment as $attachment) {
- // Check if it is a valid disposition_filter
+ //Check if it is a valid disposition_filter
if ($attachment[6] === $disposition_type) {
- // Check for string attachment
+ //Check for string attachment
$string = '';
$path = '';
$bString = $attachment[5];
//Only include a filename property if we have one
if (!empty($name)) {
$mime[] = sprintf(
- 'Content-Type: %s; name="%s"%s',
+ 'Content-Type: %s; name=%s%s',
$type,
- $this->encodeHeader($this->secureHeader($name)),
+ static::quotedString($this->encodeHeader($this->secureHeader($name))),
static::$LE
);
} else {
static::$LE
);
}
- // RFC1341 part 5 says 7bit is assumed if not specified
+ //RFC1341 part 5 says 7bit is assumed if not specified
if (static::ENCODING_7BIT !== $encoding) {
$mime[] = sprintf('Content-Transfer-Encoding: %s%s', $encoding, static::$LE);
}
$mime[] = 'Content-ID: <' . $this->encodeHeader($this->secureHeader($cid)) . '>' . static::$LE;
}
- // If a filename contains any of these chars, it should be quoted,
- // but not otherwise: RFC2183 & RFC2045 5.1
- // Fixes a warning in IETF's msglint MIME checker
- // Allow for bypassing the Content-Disposition header totally
+ //Allow for bypassing the Content-Disposition header
if (!empty($disposition)) {
$encoded_name = $this->encodeHeader($this->secureHeader($name));
- if (preg_match('/[ ()<>@,;:"\/\[\]?=]/', $encoded_name)) {
- $mime[] = sprintf(
- 'Content-Disposition: %s; filename="%s"%s',
- $disposition,
- $encoded_name,
- static::$LE . static::$LE
- );
- } elseif (!empty($encoded_name)) {
+ if (!empty($encoded_name)) {
$mime[] = sprintf(
'Content-Disposition: %s; filename=%s%s',
$disposition,
- $encoded_name,
+ static::quotedString($encoded_name),
static::$LE . static::$LE
);
} else {
$mime[] = static::$LE;
}
- // Encode as string attachment
+ //Encode as string attachment
if ($bString) {
$mime[] = $this->encodeString($string, $encoding);
} else {
protected function encodeFile($path, $encoding = self::ENCODING_BASE64)
{
try {
- if (!static::isPermittedPath($path) || !file_exists($path)) {
+ if (!static::fileIsAccessible($path)) {
throw new Exception($this->lang('file_open') . $path, self::STOP_CONTINUE);
}
$file_buffer = file_get_contents($path);
return $file_buffer;
} catch (Exception $exc) {
$this->setError($exc->getMessage());
+ $this->edebug($exc->getMessage());
+ if ($this->exceptions) {
+ throw $exc;
+ }
return '';
}
case static::ENCODING_7BIT:
case static::ENCODING_8BIT:
$encoded = static::normalizeBreaks($str);
- // Make sure it ends with a line break
+ //Make sure it ends with a line break
if (substr($encoded, -(strlen(static::$LE))) !== static::$LE) {
$encoded .= static::$LE;
}
switch (strtolower($position)) {
case 'phrase':
if (!preg_match('/[\200-\377]/', $str)) {
- // Can't use addslashes as we don't know the value of magic_quotes_sybase
+ //Can't use addslashes as we don't know the value of magic_quotes_sybase
$encoded = addcslashes($str, "\0..\37\177\\\"");
if (($str === $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
return $encoded;
$charset = static::CHARSET_ASCII;
}
- // Q/B encoding adds 8 chars and the charset ("` =?<charset>?[QB]?<content>?=`").
+ //Q/B encoding adds 8 chars and the charset ("` =?<charset>?[QB]?<content>?=`").
$overhead = 8 + strlen($charset);
if ('mail' === $this->Mailer) {
$maxlen = static::MAX_LINE_LENGTH - $overhead;
}
- // Select the encoding that produces the shortest output and/or prevents corruption.
+ //Select the encoding that produces the shortest output and/or prevents corruption.
if ($matchcount > strlen($str) / 3) {
- // More than 1/3 of the content needs encoding, use B-encode.
+ //More than 1/3 of the content needs encoding, use B-encode.
$encoding = 'B';
} elseif ($matchcount > 0) {
- // Less than 1/3 of the content needs encoding, use Q-encode.
+ //Less than 1/3 of the content needs encoding, use Q-encode.
$encoding = 'Q';
} elseif (strlen($str) > $maxlen) {
- // No encoding needed, but value exceeds max line length, use Q-encode to prevent corruption.
+ //No encoding needed, but value exceeds max line length, use Q-encode to prevent corruption.
$encoding = 'Q';
} else {
- // No reformatting needed
+ //No reformatting needed
$encoding = false;
}
switch ($encoding) {
case 'B':
if ($this->hasMultiBytes($str)) {
- // Use a custom function which correctly encodes and wraps long
- // multibyte strings without breaking lines within a character
+ //Use a custom function which correctly encodes and wraps long
+ //multibyte strings without breaking lines within a character
$encoded = $this->base64EncodeWrapMB($str, "\n");
} else {
$encoded = base64_encode($str);
return strlen($str) > mb_strlen($str, $this->CharSet);
}
- // Assume no multibytes (we can't handle without mbstring functions anyway)
+ //Assume no multibytes (we can't handle without mbstring functions anyway)
return false;
}
}
$mb_length = mb_strlen($str, $this->CharSet);
- // Each line must have length <= 75, including $start and $end
+ //Each line must have length <= 75, including $start and $end
$length = 75 - strlen($start) - strlen($end);
- // Average multi-byte ratio
+ //Average multi-byte ratio
$ratio = $mb_length / strlen($str);
- // Base64 has a 4:3 ratio
+ //Base64 has a 4:3 ratio
$avgLength = floor($length * $ratio * .75);
$offset = 0;
$encoded .= $chunk . $linebreak;
}
- // Chomp the last linefeed
+ //Chomp the last linefeed
return substr($encoded, 0, -strlen($linebreak));
}
*/
public function encodeQ($str, $position = 'text')
{
- // There should not be any EOL in the string
+ //There should not be any EOL in the string
$pattern = '';
$encoded = str_replace(["\r", "\n"], '', $str);
switch (strtolower($position)) {
case 'phrase':
- // RFC 2047 section 5.3
+ //RFC 2047 section 5.3
$pattern = '^A-Za-z0-9!*+\/ -';
break;
/*
/* Intentional fall through */
case 'text':
default:
- // RFC 2047 section 5.1
- // Replace every high ascii, control, =, ? and _ characters
+ //RFC 2047 section 5.1
+ //Replace every high ascii, control, =, ? and _ characters
$pattern = '\000-\011\013\014\016-\037\075\077\137\177-\377' . $pattern;
break;
}
$matches = [];
if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) {
- // If the string contains an '=', make sure it's the first thing we replace
- // so as to avoid double-encoding
+ //If the string contains an '=', make sure it's the first thing we replace
+ //so as to avoid double-encoding
$eqkey = array_search('=', $matches[0], true);
if (false !== $eqkey) {
unset($matches[0][$eqkey]);
$encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded);
}
}
- // Replace spaces with _ (more readable than =20)
- // RFC 2047 section 4.2(2)
+ //Replace spaces with _ (more readable than =20)
+ //RFC 2047 section 4.2(2)
return str_replace(' ', '_', $encoded);
}
$disposition = 'attachment'
) {
try {
- // If a MIME type is not specified, try to work it out from the file name
+ //If a MIME type is not specified, try to work it out from the file name
if ('' === $type) {
$type = static::filenameToType($filename);
}
throw new Exception($this->lang('encoding') . $encoding);
}
- // Append to $attachment array
+ //Append to $attachment array
$this->attachment[] = [
0 => $string,
1 => $filename,
2 => static::mb_pathinfo($filename, PATHINFO_BASENAME),
3 => $encoding,
4 => $type,
- 5 => true, // isStringAttachment
+ 5 => true, //isStringAttachment
6 => $disposition,
7 => 0,
];
$disposition = 'inline'
) {
try {
- if (!static::isPermittedPath($path) || !@is_file($path)) {
+ if (!static::fileIsAccessible($path)) {
throw new Exception($this->lang('file_access') . $path, self::STOP_CONTINUE);
}
- // If a MIME type is not specified, try to work it out from the file name
+ //If a MIME type is not specified, try to work it out from the file name
if ('' === $type) {
$type = static::filenameToType($path);
}
$name = $filename;
}
- // Append to $attachment array
+ //Append to $attachment array
$this->attachment[] = [
0 => $path,
1 => $filename,
2 => $name,
3 => $encoding,
4 => $type,
- 5 => false, // isStringAttachment
+ 5 => false, //isStringAttachment
6 => $disposition,
7 => $cid,
];
$disposition = 'inline'
) {
try {
- // If a MIME type is not specified, try to work it out from the name
+ //If a MIME type is not specified, try to work it out from the name
if ('' === $type && !empty($name)) {
$type = static::filenameToType($name);
}
throw new Exception($this->lang('encoding') . $encoding);
}
- // Append to $attachment array
+ //Append to $attachment array
$this->attachment[] = [
0 => $string,
1 => $name,
2 => $name,
3 => $encoding,
4 => $type,
- 5 => true, // isStringAttachment
+ 5 => true, //isStringAttachment
6 => $disposition,
7 => $cid,
];
*/
public static function rfcDate()
{
- // Set the time zone to whatever the default is to avoid 500 errors
- // Will default to UTC if it's not set properly in php.ini
+ //Set the time zone to whatever the default is to avoid 500 errors
+ //Will default to UTC if it's not set properly in php.ini
date_default_timezone_set(@date_default_timezone_get());
return date('D, j M Y H:i:s O');
public static function isValidHost($host)
{
//Simple syntax limits
- if (empty($host)
+ if (
+ empty($host)
|| !is_string($host)
|| strlen($host) > 256
|| !preg_match('/^([a-zA-Z\d.-]*|\[[a-fA-F\d:]+])$/', $host)
protected function lang($key)
{
if (count($this->language) < 1) {
- $this->setLanguage(); // set the default language
+ $this->setLanguage(); //Set the default language
}
if (array_key_exists($key, $this->language)) {
if ('smtp_connect_failed' === $key) {
- //Include a link to troubleshooting docs on SMTP connection failure
- //this is by far the biggest cause of support questions
+ //Include a link to troubleshooting docs on SMTP connection failure.
+ //This is by far the biggest cause of support questions
//but it's usually not PHPMailer's fault.
return $this->language[$key] . ' https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting';
}
*
* @param string $name Custom header name
* @param string|null $value Header value
+ *
+ * @throws Exception
*/
public function addCustomHeader($name, $value = null)
{
- if (null === $value) {
- // Value passed in as name:value
- $this->CustomHeader[] = explode(':', $name, 2);
- } else {
- $this->CustomHeader[] = [$name, $value];
+ if (null === $value && strpos($name, ':') !== false) {
+ //Value passed in as name:value
+ list($name, $value) = explode(':', $name, 2);
+ }
+ $name = trim($name);
+ $value = trim($value);
+ //Ensure name is not empty, and that neither name nor value contain line breaks
+ if (empty($name) || strpbrk($name . $value, "\r\n") !== false) {
+ if ($this->exceptions) {
+ throw new Exception('Invalid header name or value');
+ }
+
+ return false;
}
+ $this->CustomHeader[] = [$name, $value];
+
+ return true;
}
/**
* @param string $message HTML message string
* @param string $basedir Absolute path to a base directory to prepend to relative paths to images
* @param bool|callable $advanced Whether to use the internal HTML to text converter
- * or your own custom converter @return string $message The transformed message Body
+ * or your own custom converter
+ * @return string The transformed message body
*
* @throws Exception
*
preg_match_all('/(?<!-)(src|background)=["\'](.*)["\']/Ui', $message, $images);
if (array_key_exists(2, $images)) {
if (strlen($basedir) > 1 && '/' !== substr($basedir, -1)) {
- // Ensure $basedir has a trailing /
+ //Ensure $basedir has a trailing /
$basedir .= '/';
}
foreach ($images[2] as $imgindex => $url) {
- // Convert data URIs into embedded images
+ //Convert data URIs into embedded images
//e.g. "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="
+ $match = [];
if (preg_match('#^data:(image/(?:jpe?g|gif|png));?(base64)?,(.+)#', $url, $match)) {
if (count($match) === 4 && static::ENCODING_BASE64 === $match[2]) {
$data = base64_decode($match[3]);
}
//Hash the decoded data, not the URL, so that the same data-URI image used in multiple places
//will only be embedded once, even if it used a different encoding
- $cid = substr(hash('sha256', $data), 0, 32) . '@phpmailer.0'; // RFC2392 S 2
+ $cid = substr(hash('sha256', $data), 0, 32) . '@phpmailer.0'; //RFC2392 S 2
if (!$this->cidExists($cid)) {
$this->addStringEmbeddedImage(
);
continue;
}
- if (// Only process relative URLs if a basedir is provided (i.e. no absolute local paths)
+ if (
+ //Only process relative URLs if a basedir is provided (i.e. no absolute local paths)
!empty($basedir)
- // Ignore URLs containing parent dir traversal (..)
+ //Ignore URLs containing parent dir traversal (..)
&& (strpos($url, '..') === false)
- // Do not change urls that are already inline images
+ //Do not change urls that are already inline images
&& 0 !== strpos($url, 'cid:')
- // Do not change absolute URLs, including anonymous protocol
+ //Do not change absolute URLs, including anonymous protocol
&& !preg_match('#^[a-z][a-z0-9+.-]*:?//#i', $url)
) {
$filename = static::mb_pathinfo($url, PATHINFO_BASENAME);
if ('.' === $directory) {
$directory = '';
}
- // RFC2392 S 2
+ //RFC2392 S 2
$cid = substr(hash('sha256', $url), 0, 32) . '@phpmailer.0';
if (strlen($basedir) > 1 && '/' !== substr($basedir, -1)) {
$basedir .= '/';
if (strlen($directory) > 1 && '/' !== substr($directory, -1)) {
$directory .= '/';
}
- if ($this->addEmbeddedImage(
- $basedir . $directory . $filename,
- $cid,
- $filename,
- static::ENCODING_BASE64,
- static::_mime_types((string) static::mb_pathinfo($filename, PATHINFO_EXTENSION))
- )
+ if (
+ $this->addEmbeddedImage(
+ $basedir . $directory . $filename,
+ $cid,
+ $filename,
+ static::ENCODING_BASE64,
+ static::_mime_types((string) static::mb_pathinfo($filename, PATHINFO_EXTENSION))
+ )
) {
$message = preg_replace(
'/' . $images[1][$imgindex] . '=["\']' . preg_quote($url, '/') . '["\']/Ui',
}
}
$this->isHTML();
- // Convert all message body line breaks to LE, makes quoted-printable encoding work much better
+ //Convert all message body line breaks to LE, makes quoted-printable encoding work much better
$this->Body = static::normalizeBreaks($message);
$this->AltBody = static::normalizeBreaks($this->html2text($message, $advanced));
if (!$this->alternativeExists()) {
* Example usage:
*
* ```php
- * // Use default conversion
+ * //Use default conversion
* $plain = $mail->html2text($html);
- * // Use your own custom converter
+ * //Use your own custom converter
* $plain = $mail->html2text($html, function($html) {
* $converter = new MyHtml2text($html);
* return $converter->get_text();
public function html2text($html, $advanced = false)
{
if (is_callable($advanced)) {
- return $advanced($html);
+ return call_user_func($advanced, $html);
}
return html_entity_decode(
'tiff' => 'image/tiff',
'tif' => 'image/tiff',
'webp' => 'image/webp',
+ 'avif' => 'image/avif',
'heif' => 'image/heif',
'heifs' => 'image/heif-sequence',
'heic' => 'image/heic',
*/
public static function filenameToType($filename)
{
- // In case the path is a URL, strip any query string before getting extension
+ //In case the path is a URL, strip any query string before getting extension
$qpos = strpos($filename, '?');
if (false !== $qpos) {
$filename = substr($filename, 0, $qpos);
if (null === $breaktype) {
$breaktype = static::$LE;
}
- // Normalise to \n
- $text = str_replace(["\r\n", "\r"], "\n", $text);
- // Now convert LE as needed
+ //Normalise to \n
+ $text = str_replace([self::CRLF, "\r"], "\n", $text);
+ //Now convert LE as needed
if ("\n" !== $breaktype) {
$text = str_replace("\n", $breaktype, $text);
}
return $text;
}
+ /**
+ * Remove trailing breaks from a string.
+ *
+ * @param string $text
+ *
+ * @return string The text to remove breaks from
+ */
+ public static function stripTrailingWSP($text)
+ {
+ return rtrim($text, " \r\n\t");
+ }
+
/**
* Return the current line break format string.
*
$privKey = openssl_pkey_get_private($privKeyStr);
}
if (openssl_sign($signHeader, $signature, $privKey, 'sha256WithRSAEncryption')) {
- openssl_pkey_free($privKey);
+ if (\PHP_MAJOR_VERSION < 8) {
+ openssl_pkey_free($privKey);
+ }
return base64_encode($signature);
}
- openssl_pkey_free($privKey);
+ if (\PHP_MAJOR_VERSION < 8) {
+ openssl_pkey_free($privKey);
+ }
return '';
}
*/
public function DKIM_HeaderC($signHeader)
{
+ //Normalize breaks to CRLF (regardless of the mailer)
+ $signHeader = static::normalizeBreaks($signHeader, self::CRLF);
+ //Unfold header lines
//Note PCRE \s is too broad a definition of whitespace; RFC5322 defines it as `[ \t]`
//@see https://tools.ietf.org/html/rfc5322#section-2.2
//That means this may break if you do something daft like put vertical tabs in your headers.
- //Unfold header lines
$signHeader = preg_replace('/\r\n[ \t]+/', ' ', $signHeader);
//Break headers out into an array
- $lines = explode("\r\n", $signHeader);
+ $lines = explode(self::CRLF, $signHeader);
foreach ($lines as $key => $line) {
//If the header is missing a :, skip it as it's invalid
//This is likely to happen because the explode() above will also split
$lines[$key] = trim($heading, " \t") . ':' . trim($value, " \t");
}
- return implode("\r\n", $lines);
+ return implode(self::CRLF, $lines);
}
/**
public function DKIM_BodyC($body)
{
if (empty($body)) {
- return "\r\n";
+ return self::CRLF;
}
- // Normalize line endings to CRLF
- $body = static::normalizeBreaks($body, "\r\n");
+ //Normalize line endings to CRLF
+ $body = static::normalizeBreaks($body, self::CRLF);
//Reduce multiple trailing line breaks to a single one
- return rtrim($body, "\r\n") . "\r\n";
+ return static::stripTrailingWSP($body) . self::CRLF;
}
/**
*/
public function DKIM_Add($headers_line, $subject, $body)
{
- $DKIMsignatureType = 'rsa-sha256'; // Signature & hash algorithms
- $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization methods of header & body
- $DKIMquery = 'dns/txt'; // Query method
+ $DKIMsignatureType = 'rsa-sha256'; //Signature & hash algorithms
+ $DKIMcanonicalization = 'relaxed/simple'; //Canonicalization methods of header & body
+ $DKIMquery = 'dns/txt'; //Query method
$DKIMtime = time();
//Always sign these headers without being asked
+ //Recommended list from https://tools.ietf.org/html/rfc6376#section-5.4.1
$autoSignHeaders = [
- 'From',
- 'To',
- 'CC',
- 'Date',
- 'Subject',
- 'Reply-To',
- 'Message-ID',
- 'Content-Type',
- 'Mime-Version',
- 'X-Mailer',
+ 'from',
+ 'to',
+ 'cc',
+ 'date',
+ 'subject',
+ 'reply-to',
+ 'message-id',
+ 'content-type',
+ 'mime-version',
+ 'x-mailer',
];
if (stripos($headers_line, 'Subject') === false) {
$headers_line .= 'Subject: ' . $subject . static::$LE;
$headersToSign = [];
foreach ($parsedHeaders as $header) {
//Is this header one that must be included in the DKIM signature?
- if (in_array($header['label'], $autoSignHeaders, true)) {
+ if (in_array(strtolower($header['label']), $autoSignHeaders, true)) {
$headersToSignKeys[] = $header['label'];
$headersToSign[] = $header['label'] . ': ' . $header['value'];
if ($this->DKIM_copyHeaderFields) {
//Fold long values
if (strlen($copiedHeader) > self::STD_LINE_LENGTH - 3) {
$copiedHeaderFields .= substr(
- chunk_split($copiedHeader, self::STD_LINE_LENGTH - 3, static::$LE . ' '),
+ chunk_split($copiedHeader, self::STD_LINE_LENGTH - 3, static::$LE . self::FWS),
0,
- -strlen(static::$LE . ' ')
+ -strlen(static::$LE . self::FWS)
);
} else {
$copiedHeaderFields .= $copiedHeader;
$headerKeys = ' h=' . implode(':', $headersToSignKeys) . ';' . static::$LE;
$headerValues = implode(static::$LE, $headersToSign);
$body = $this->DKIM_BodyC($body);
- $DKIMlen = strlen($body); // Length of body
- $DKIMb64 = base64_encode(pack('H*', hash('sha256', $body))); // Base64 of packed binary SHA-256 hash of body
+ //Base64 of packed binary SHA-256 hash of body
+ $DKIMb64 = base64_encode(pack('H*', hash('sha256', $body)));
$ident = '';
if ('' !== $this->DKIM_identity) {
$ident = ' i=' . $this->DKIM_identity . ';' . static::$LE;
' s=' . $this->DKIM_selector . ';' . static::$LE .
' a=' . $DKIMsignatureType . ';' .
' q=' . $DKIMquery . ';' .
- ' l=' . $DKIMlen . ';' .
' t=' . $DKIMtime . ';' .
' c=' . $DKIMcanonicalization . ';' . static::$LE .
$headerKeys .
$headerValues . static::$LE . $dkimSignatureHeader
);
$signature = $this->DKIM_Sign($canonicalizedHeaders);
- $signature = trim(chunk_split($signature, self::STD_LINE_LENGTH - 3, static::$LE . ' '));
+ $signature = trim(chunk_split($signature, self::STD_LINE_LENGTH - 3, static::$LE . self::FWS));
- return static::normalizeBreaks($dkimSignatureHeader . $signature) . static::$LE;
+ return static::normalizeBreaks($dkimSignatureHeader . $signature);
}
/**
return (bool) preg_match('/^(.{' . (self::MAX_LINE_LENGTH + strlen(static::$LE)) . ',})/m', $str);
}
+ /**
+ * If a string contains any "special" characters, double-quote the name,
+ * and escape any double quotes with a backslash.
+ *
+ * @param string $str
+ *
+ * @return string
+ *
+ * @see RFC822 3.4.1
+ */
+ public static function quotedString($str)
+ {
+ if (preg_match('/[ ()<>@,;:"\/\[\]?=]/', $str)) {
+ //If the string contains any of these chars, it must be double-quoted
+ //and any double quotes must be escaped with a backslash
+ return '"' . str_replace('"', '\\"', $str) . '"';
+ }
+
+ //Return the string untouched, it doesn't need quoting
+ return $str;
+ }
+
/**
* Allows for public read access to 'to' property.
* Before the send() call, queued addresses (i.e. with IDN) are not yet included.
<?php
+
/**
* PHPMailer RFC821 SMTP email transport class.
* PHP Version 5.5.
* @author Jim Jagielski (jimjag) <jimjag@gmail.com>
* @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
* @author Brent R. Matzelle (original founder)
- * @copyright 2012 - 2019 Marcus Bointon
+ * @copyright 2012 - 2020 Marcus Bointon
* @copyright 2010 - 2012 Jim Jagielski
* @copyright 2004 - 2009 Andy Prevost
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
*
* @var string
*/
- const VERSION = '6.1.4';
+ const VERSION = '6.5.0';
/**
* SMTP line break constant.
'Amazon_SES' => '/[\d]{3} Ok (.*)/',
'SendGrid' => '/[\d]{3} Ok: queued as (.*)/',
'CampaignMonitor' => '/[\d]{3} 2.0.0 OK:([a-zA-Z\d]{48})/',
+ 'Haraka' => '/[\d]{3} Message Queued \((.*)\)/',
];
/**
*/
public function connect($host, $port = null, $timeout = 30, $options = [])
{
- static $streamok;
- //This is enabled by default since 5.0.0 but some providers disable it
- //Check this once and cache the result
- if (null === $streamok) {
- $streamok = function_exists('stream_socket_client');
- }
- // Clear errors to avoid confusion
+ //Clear errors to avoid confusion
$this->setError('');
- // Make sure we are __not__ connected
+ //Make sure we are __not__ connected
if ($this->connected()) {
- // Already connected, generate error
+ //Already connected, generate error
$this->setError('Already connected to a server');
return false;
if (empty($port)) {
$port = self::DEFAULT_PORT;
}
- // Connect to the SMTP server
+ //Connect to the SMTP server
$this->edebug(
"Connection: opening to $host:$port, timeout=$timeout, options=" .
(count($options) > 0 ? var_export($options, true) : 'array()'),
self::DEBUG_CONNECTION
);
+
+ $this->smtp_conn = $this->getSMTPConnection($host, $port, $timeout, $options);
+
+ if ($this->smtp_conn === false) {
+ //Error info already set inside `getSMTPConnection()`
+ return false;
+ }
+
+ $this->edebug('Connection: opened', self::DEBUG_CONNECTION);
+
+ //Get any announcement
+ $this->last_reply = $this->get_lines();
+ $this->edebug('SERVER -> CLIENT: ' . $this->last_reply, self::DEBUG_SERVER);
+ $responseCode = (int)substr($this->last_reply, 0, 3);
+ if ($responseCode === 220) {
+ return true;
+ }
+ //Anything other than a 220 response means something went wrong
+ //RFC 5321 says the server will wait for us to send a QUIT in response to a 554 error
+ //https://tools.ietf.org/html/rfc5321#section-3.1
+ if ($responseCode === 554) {
+ $this->quit();
+ }
+ //This will handle 421 responses which may not wait for a QUIT (e.g. if the server is being shut down)
+ $this->edebug('Connection: closing due to error', self::DEBUG_CONNECTION);
+ $this->close();
+ return false;
+ }
+
+ /**
+ * Create connection to the SMTP server.
+ *
+ * @param string $host SMTP server IP or host name
+ * @param int $port The port number to connect to
+ * @param int $timeout How long to wait for the connection to open
+ * @param array $options An array of options for stream_context_create()
+ *
+ * @return false|resource
+ */
+ protected function getSMTPConnection($host, $port = null, $timeout = 30, $options = [])
+ {
+ static $streamok;
+ //This is enabled by default since 5.0.0 but some providers disable it
+ //Check this once and cache the result
+ if (null === $streamok) {
+ $streamok = function_exists('stream_socket_client');
+ }
+
$errno = 0;
$errstr = '';
if ($streamok) {
$socket_context = stream_context_create($options);
set_error_handler([$this, 'errorHandler']);
- $this->smtp_conn = stream_socket_client(
+ $connection = stream_socket_client(
$host . ':' . $port,
$errno,
$errstr,
self::DEBUG_CONNECTION
);
set_error_handler([$this, 'errorHandler']);
- $this->smtp_conn = fsockopen(
+ $connection = fsockopen(
$host,
$port,
$errno,
);
restore_error_handler();
}
- // Verify we connected properly
- if (!is_resource($this->smtp_conn)) {
+
+ //Verify we connected properly
+ if (!is_resource($connection)) {
$this->setError(
'Failed to connect to server',
'',
return false;
}
- $this->edebug('Connection: opened', self::DEBUG_CONNECTION);
- // SMTP server can take longer to respond, give longer timeout for first read
- // Windows does not have support for this timeout function
+
+ //SMTP server can take longer to respond, give longer timeout for first read
+ //Windows does not have support for this timeout function
if (strpos(PHP_OS, 'WIN') !== 0) {
- $max = (int) ini_get('max_execution_time');
- // Don't bother if unlimited
- if (0 !== $max && $timeout > $max) {
+ $max = (int)ini_get('max_execution_time');
+ //Don't bother if unlimited, or if set_time_limit is disabled
+ if (0 !== $max && $timeout > $max && strpos(ini_get('disable_functions'), 'set_time_limit') === false) {
@set_time_limit($timeout);
}
- stream_set_timeout($this->smtp_conn, $timeout, 0);
+ stream_set_timeout($connection, $timeout, 0);
}
- // Get any announcement
- $announce = $this->get_lines();
- $this->edebug('SERVER -> CLIENT: ' . $announce, self::DEBUG_SERVER);
- return true;
+ return $connection;
}
/**
$crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT;
}
- // Begin encrypted connection
+ //Begin encrypted connection
set_error_handler([$this, 'errorHandler']);
$crypto_ok = stream_socket_enable_crypto(
$this->smtp_conn,
}
if (array_key_exists('EHLO', $this->server_caps)) {
- // SMTP extensions are available; try to find a proper authentication method
+ //SMTP extensions are available; try to find a proper authentication method
if (!array_key_exists('AUTH', $this->server_caps)) {
$this->setError('Authentication is not allowed at this stage');
- // 'at this stage' means that auth may be allowed after the stage changes
- // e.g. after STARTTLS
+ //'at this stage' means that auth may be allowed after the stage changes
+ //e.g. after STARTTLS
return false;
}
}
switch ($authtype) {
case 'PLAIN':
- // Start authentication
+ //Start authentication
if (!$this->sendCommand('AUTH', 'AUTH PLAIN', 334)) {
return false;
}
- // Send encoded username and password
- if (!$this->sendCommand(
- 'User & Password',
- base64_encode("\0" . $username . "\0" . $password),
- 235
- )
+ //Send encoded username and password
+ if (
+ //Format from https://tools.ietf.org/html/rfc4616#section-2
+ //We skip the first field (it's forgery), so the string starts with a null byte
+ !$this->sendCommand(
+ 'User & Password',
+ base64_encode("\0" . $username . "\0" . $password),
+ 235
+ )
) {
return false;
}
break;
case 'LOGIN':
- // Start authentication
+ //Start authentication
if (!$this->sendCommand('AUTH', 'AUTH LOGIN', 334)) {
return false;
}
}
break;
case 'CRAM-MD5':
- // Start authentication
+ //Start authentication
if (!$this->sendCommand('AUTH CRAM-MD5', 'AUTH CRAM-MD5', 334)) {
return false;
}
- // Get the challenge
+ //Get the challenge
$challenge = base64_decode(substr($this->last_reply, 4));
- // Build the response
+ //Build the response
$response = $username . ' ' . $this->hmac($challenge, $password);
- // send encoded credentials
+ //send encoded credentials
return $this->sendCommand('Username', base64_encode($response), 235);
case 'XOAUTH2':
//The OAuth instance must be set up prior to requesting auth.
}
$oauth = $OAuth->getOauth64();
- // Start authentication
+ //Start authentication
if (!$this->sendCommand('AUTH', 'AUTH XOAUTH2 ' . $oauth, 235)) {
return false;
}
return hash_hmac('md5', $data, $key);
}
- // The following borrowed from
- // http://php.net/manual/en/function.mhash.php#27225
+ //The following borrowed from
+ //http://php.net/manual/en/function.mhash.php#27225
- // RFC 2104 HMAC implementation for php.
- // Creates an md5 HMAC.
- // Eliminates the need to install mhash to compute a HMAC
- // by Lance Rushing
+ //RFC 2104 HMAC implementation for php.
+ //Creates an md5 HMAC.
+ //Eliminates the need to install mhash to compute a HMAC
+ //by Lance Rushing
- $bytelen = 64; // byte length for md5
+ $bytelen = 64; //byte length for md5
if (strlen($key) > $bytelen) {
$key = pack('H*', md5($key));
}
if (is_resource($this->smtp_conn)) {
$sock_status = stream_get_meta_data($this->smtp_conn);
if ($sock_status['eof']) {
- // The socket is valid but we are not connected
+ //The socket is valid but we are not connected
$this->edebug(
'SMTP NOTICE: EOF caught while checking if connected',
self::DEBUG_CLIENT
return false;
}
- return true; // everything looks good
+ return true; //everything looks good
}
return false;
$this->server_caps = null;
$this->helo_rply = null;
if (is_resource($this->smtp_conn)) {
- // close the connection and cleanup
+ //Close the connection and cleanup
fclose($this->smtp_conn);
$this->smtp_conn = null; //Makes for cleaner serialization
$this->edebug('Connection: closed', self::DEBUG_CONNECTION);
* NOTE: this does not count towards line-length limit.
*/
- // Normalize line breaks before exploding
+ //Normalize line breaks before exploding
$lines = explode("\n", str_replace(["\r\n", "\r"], "\n", $msg_data));
/* To distinguish between a complete RFC822 message and a plain message body, we check if the first field
//Send the lines to the server
foreach ($lines_out as $line_out) {
- //RFC2821 section 4.5.2
+ //Dot-stuffing as per RFC5321 section 4.5.2
+ //https://tools.ietf.org/html/rfc5321#section-4.5.2
if (!empty($line_out) && $line_out[0] === '.') {
$line_out = '.' . $line_out;
}
public function hello($host = '')
{
//Try extended hello first (RFC 2821)
- return $this->sendHello('EHLO', $host) or $this->sendHello('HELO', $host);
+ if ($this->sendHello('EHLO', $host)) {
+ return true;
+ }
+
+ //Some servers shut down the SMTP service here (RFC 5321)
+ if (substr($this->helo_rply, 0, 3) == '421') {
+ return false;
+ }
+
+ return $this->sendHello('HELO', $host);
}
/**
$this->client_send($commandstring . static::LE, $command);
$this->last_reply = $this->get_lines();
- // Fetch SMTP code and possible error code explanation
+ //Fetch SMTP code and possible error code explanation
$matches = [];
if (preg_match('/^([\d]{3})[ -](?:([\d]\\.[\d]\\.[\d]{1,2}) )?/', $this->last_reply, $matches)) {
$code = (int) $matches[1];
$code_ex = (count($matches) > 2 ? $matches[2] : null);
- // Cut off error code from each response line
+ //Cut off error code from each response line
$detail = preg_replace(
"/{$code}[ -]" .
($code_ex ? str_replace('.', '\\.', $code_ex) . ' ' : '') . '/m',
$this->last_reply
);
} else {
- // Fall back to simple parsing if regex fails
+ //Fall back to simple parsing if regex fails
$code = (int) substr($this->last_reply, 0, 3);
$code_ex = null;
$detail = substr($this->last_reply, 4);
{
//If SMTP transcripts are left enabled, or debug output is posted online
//it can leak credentials, so hide credentials in all but lowest level
- if (self::DEBUG_LOWLEVEL > $this->do_debug &&
- in_array($command, ['User & Password', 'Username', 'Password'], true)) {
+ if (
+ self::DEBUG_LOWLEVEL > $this->do_debug &&
+ in_array($command, ['User & Password', 'Username', 'Password'], true)
+ ) {
$this->edebug('CLIENT -> SERVER: [credentials hidden]', self::DEBUG_CLIENT);
} else {
$this->edebug('CLIENT -> SERVER: ' . $data, self::DEBUG_CLIENT);
*/
protected function get_lines()
{
- // If the connection is bad, give up straight away
+ //If the connection is bad, give up straight away
if (!is_resource($this->smtp_conn)) {
return '';
}
$selW = null;
while (is_resource($this->smtp_conn) && !feof($this->smtp_conn)) {
//Must pass vars in here as params are by reference
- if (!stream_select($selR, $selW, $selW, $this->Timelimit)) {
+ //solution for signals inspired by https://github.com/symfony/symfony/pull/6540
+ set_error_handler([$this, 'errorHandler']);
+ $n = stream_select($selR, $selW, $selW, $this->Timelimit);
+ restore_error_handler();
+
+ if ($n === false) {
+ $message = $this->getError()['detail'];
+
$this->edebug(
- 'SMTP -> get_lines(): timed-out (' . $this->Timeout . ' sec)',
+ 'SMTP -> get_lines(): select failed (' . $message . ')',
self::DEBUG_LOWLEVEL
);
+
+ //stream_select returns false when the `select` system call is interrupted
+ //by an incoming signal, try the select again
+ if (stripos($message, 'interrupted system call') !== false) {
+ $this->edebug(
+ 'SMTP -> get_lines(): retrying stream_select',
+ self::DEBUG_LOWLEVEL
+ );
+ $this->setError('');
+ continue;
+ }
+
break;
}
+
+ if (!$n) {
+ $this->edebug(
+ 'SMTP -> get_lines(): select timed-out in (' . $this->Timelimit . ' sec)',
+ self::DEBUG_LOWLEVEL
+ );
+ break;
+ }
+
//Deliberate noise suppression - errors are handled afterwards
$str = @fgets($this->smtp_conn, self::MAX_REPLY_LENGTH);
$this->edebug('SMTP INBOUND: "' . trim($str) . '"', self::DEBUG_LOWLEVEL);
$data .= $str;
- // If response is only 3 chars (not valid, but RFC5321 S4.2 says it must be handled),
- // or 4th character is a space or a line break char, we are done reading, break the loop.
- // String array access is a significant micro-optimisation over strlen
+ //If response is only 3 chars (not valid, but RFC5321 S4.2 says it must be handled),
+ //or 4th character is a space or a line break char, we are done reading, break the loop.
+ //String array access is a significant micro-optimisation over strlen
if (!isset($str[3]) || $str[3] === ' ' || $str[3] === "\r" || $str[3] === "\n") {
break;
}
- // Timed-out? Log and break
+ //Timed-out? Log and break
$info = stream_get_meta_data($this->smtp_conn);
if ($info['timed_out']) {
$this->edebug(
- 'SMTP -> get_lines(): timed-out (' . $this->Timeout . ' sec)',
+ 'SMTP -> get_lines(): stream timed-out (' . $this->Timeout . ' sec)',
self::DEBUG_LOWLEVEL
);
break;
}
- // Now check if reads took too long
+ //Now check if reads took too long
if ($endtime && time() > $endtime) {
$this->edebug(
'SMTP -> get_lines(): timelimit reached (' .
} else {
$this->last_smtp_transaction_id = false;
foreach ($this->smtp_transaction_id_patterns as $smtp_transaction_id_pattern) {
+ $matches = [];
if (preg_match($smtp_transaction_id_pattern, $reply, $matches)) {
$this->last_smtp_transaction_id = trim($matches[1]);
break;