Commit 5a9a23ae by Manzar Hussain

add another smtp

parent bb4790b6
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
SMTP Authentication Support module for Drupal 8.x.
This module adds SMTP functionality to Drupal.
REQUIREMENTS
------------
* Access to an SMTP server that will accept mail from you.
* The following PHP extensions need to be installed: hash, date & pcre.
* The PHPMailer class has been unbundled, and must be installed with composer.
Refer to https://github.com/PHPMailer/PHPMailer for details.
* Optional: To connect to an SMTP server using SSL, you need to have the
openssl package installed on your server, and your webserver and PHP
installation need to have additional components installed and configured.
INSTALLATION INSTRUCTIONS
-------------------------
1. Copy the files included in the tarball into a directory named "smtp" in
your Drupal /modules/ or /modules/contrib/ directory.
2. Enable the module:
a. Login as site administrator, visit the Extend page, and enable SMTP.
b. Run "drush pm-enable smtp" on the command line.
3. Enable the SMTP Authentication Support module on the Manage -> Extend
page.
4. Fill in required settings on the Manage -> Configuration -> System ->
SMTP Authentication Support page.
5. Enjoy.
CONFIGURATION
------------
* Configure the user permissions in Administration -> People -> Permissions:
- Administer SMTP Authentication Support module.
RELATED MODULES
---------------
You may find the following modules helpful:
- mailsystem: controls which mail-related modules are used by other actions.
- mimemail: Makes HTML email easier to send.
- pet: Previewable Templating module
- rules: can send emails when "events" happen, such as publishing a node.
NOTES
-----
Valid SMTP Server
This module sends email by connecting to an SMTP server. Therefore, you need
to have access to an SMTP server, that is configured to accept email from you,
for this module to work.
Selecting Connection Port
Mail servers listen for new mail on TCP/IP numbered "ports", and while these
can be whatever the administrator determines, the standard values are:
+ 25 : Internet-wide email transmission by default in cleartext but can
upgrade to TLS when both sides support it;
+ 465 : A version of port 25 for which SSL is enabled from the beginning.
Now deprecated in favour of port 587 and the use of "STARTTLS";
+ 587 : "Mail submission" - used for clients talking to a "smarthost"
server (e.g. the ISP server) for queueing and/or forwarding.
The recommendation is for SMTP module to use port 587 with STARTTLS for
secure (especially cross-internet) connections to the ISP email server,
and port 25 for insecure and/or local connections. However, the actual port
and server to use will depend on the email server you will be using, and
if the above does not work for you, you should refer to that server's
documentation for more help.
Finally, it is worth mentioning that the popular development tool "mailhog"
uses port "8025".
Setting the From email address:
Drupal normally uses the From email address (see Manage -> Configuration ->
Site information -> E-mail address) as the Mail From address. It is important
for this to be the correct address and many ISPs will block email that comes
from an address they do not recognise as "theirs".
Sending mail to GMail requires SSL or TLS. Connecting to an SMTP server using
SSL is possible only if PHP's openssl extension is working. If the SMTP
module detects openssl is available it will display the options in the SMTP
settings page. Alternatively, run on the web host:
php -i | grep "Stream Socket Transports"
and look for at least one of:
ssl, tls, tlsv1.1, tlsv1.2
in the output.
Google Mail Authentication:
GMail currently supports using OAuth2 to authenticate senders of email, to
ensure that only the valid owners can use it. OAuth2 will be required from
early 2021 and new accounts will require it from mid-2020.
This restriction means that GMail and GSuite email addresses cannot be used
without also enabling OAuth2, which is not currently supported by the module.
----
Note for Office365 users:
The 'E-mail from name' field will most likley be ignored by Office365-hosted
Exchange. Please see this Microsoft KB article for more details:
https://support.microsoft.com/en-us/help/4458479/improvements-in-smtp-authenticated-submission-client-protocol
{
"name": "drupal/smtp",
"description": "Allow for site emails to be sent through an SMTP server of your choice.",
"type": "drupal-module",
"license": "GPL-2.0-or-later",
"homepage": "https://www.drupal.org/project/smtp",
"support": {
"issues": "https://www.drupal.org/project/issues/smtp"
},
"require": {
"drupal/core": "^8.8 || ^9",
"phpmailer/phpmailer": "^6.1.7"
},
"extra": {
"branch-alias": {
"dev-8.x-1.x": "1.x-dev"
}
},
"suggest": {
"drupal/mailsystem": "Allows using SMTP alongside other mail modules."
}
}
smtp_on: false
smtp_host: ''
smtp_hostbackup: ''
smtp_port: '25'
smtp_protocol: 'standard'
smtp_autotls: true
smtp_timeout: 30
smtp_username: ''
smtp_password: ''
smtp_from: ''
smtp_fromname: ''
smtp_client_hostname: ''
smtp_client_helo: ''
smtp_allowhtml: ''
smtp_test_address: ''
smtp_debugging: false
prev_mail_system: 'php_mail'
smtp_keepalive: false
smtp.settings:
type: config_object
label: 'SMTP config.'
mapping:
smtp_on:
type: boolean
label: 'Turn this module on or off'
smtp_host:
type: string
label: 'SMTP server'
smtp_hostbackup:
type: string
label: 'SMTP backup server'
smtp_port:
type: string
label: 'SMTP port'
smtp_protocol:
type: string
label: 'Use encrypted protocol'
smtp_autotls:
type: boolean
label: 'Enable TLS encryption automatically when supported by the remote host'
smtp_timeout:
type: integer
label: 'Amount of seconds for the SMTP command to timeout'
smtp_username:
type: string
label: 'Username'
smtp_password:
type: string
label: 'Password'
smtp_from:
type: email
label: 'E-mail from address'
smtp_fromname:
type: text
label: 'E-mail from name'
smtp_client_hostname:
type: string
label: 'Hostname'
smtp_client_helo:
type: string
label: 'HELO'
smtp_allowhtml:
type: string
label: 'Allow to send e-mails formated as HTML'
smtp_test_address:
type: email
label: 'E-mail address to send a test e-mail to'
smtp_debugging:
type: boolean
label: 'Enable debugging'
prev_mail_system:
type: string
label: 'Previous mail system'
smtp_keepalive:
type: boolean
label: 'Enable the connection keep alive function'
{
"require": {
"phpmailer/phpmailer": {
"version": "^6.1.7",
"url": "https://github.com/PHPMailer/PHPMailer/archive/v6.1.7.zip"
}
}
}
name: SMTP Authentication Support
description: "Allow for site emails to be sent through an SMTP server of your choice."
package: Mail
type: module
core_version_requirement: ^8.8 || ^9
configure: smtp.config
# Information added by Drupal.org packaging script on 2020-09-25
version: '8.x-1.0'
project: 'smtp'
datestamp: 1601070987
<?php
/**
* @file
* The installation instructions for the SMTP Authentication Support.
*/
use Drupal\Core\Url;
use PHPMailer\PHPMailer\PHPMailer;
/**
* Implements hook_uninstall().
*/
function smtp_uninstall() {
// Restore previous mail system.
_disable_smtp();
// Cleaning garbage.
$config = \Drupal::service('config.factory');
$smtp_config = $config->getEditable('smtp.settings');
$smtp_config->delete();
}
/**
* Add SMTP timeout configuration and change default to 30.
*/
function smtp_update_8001() {
\Drupal::configFactory()->getEditable('smtp.settings')
->set('smtp_timeout', 30)
->save(TRUE);
}
/**
* Add SMTP keepalive configuration and set default to FALSE.
*/
function smtp_update_8002() {
\Drupal::configFactory()->getEditable('smtp.settings')
->set('smtp_keepalive', FALSE)
->save(TRUE);
}
/**
* If mailsystem exists, disable smtp mailsystem automatically.
*/
function smtp_update_8004() {
$mailsystem_enabled = \Drupal::moduleHandler()->moduleExists('mailsystem');
if ($mailsystem_enabled) {
_disable_smtp();
}
}
/**
* Implements hook_install().
*/
function smtp_install() {
$messenger = \Drupal::messenger();
// @var \Drupal\Core\Routing\RouteBuilderInterface $routeBuilder $route_builder.
$route_builder = \Drupal::service('router.builder');
// Makes the 'smtp.config' route available here, see hook_install doc.
$route_builder->rebuild();
$messenger->addMessage(t('Thanks for installing SMTP Authentication Support'));
$messenger->addMessage(t('Server settings on <a href="@url_settings">SMTP Authentication Support</a>', [
'@url_settings' => Url::fromRoute('smtp.config')->toString(),
]));
}
/**
* Disable the SMTP mailsystem if the mailsystem module is installed.
*
* @param $modules
* @param $is_syncing
*/
function smtp_modules_installed($modules, $is_syncing = FALSE) {
if (in_array('mailsystem', $modules) && !$is_syncing) {
// If mailsystem module is enabled, make sure SMTP is disabled.
_disable_smtp();
}
}
/**
* Implements hook_requirements().
*/
function smtp_requirements(string $phase) {
$requirements = [];
if ($phase == 'runtime') {
// Ensure PHPMailer exists.
if (class_exists(PHPMailer::class)) {
$mail = new PHPMailer();
}
if (empty($mail)) {
$requirements['smtp_phpmailer'] = [
'title' => (string) t('SMTP: PHPMailer Library'),
'value' => (string) t('Missing'),
'severity' => REQUIREMENT_ERROR,
'description' => t('PHPMailer is Required for SMTP to function.'),
];
// If PHPMailer is not found, SMTP should not be set as the mail system.
_disable_smtp();
return $requirements;
}
else {
$required_version = '6.1.7';
$installed_version = $mail::VERSION;
$reflector = new \ReflectionClass('\PHPMailer\PHPMailer\PHPMailer');
$requirements['smtp_phpmailer'] = [
'title' => (string) t('SMTP: PHPMailer library'),
'value' => $installed_version,
'description' => t('PHPMailer is located at %path', ['%path' => $reflector->getFileName()]),
];
if (!version_compare($installed_version, $required_version, '>=')) {
$requirements['smtp_phpmailer']['severity'] = REQUIREMENT_ERROR;
$requirements['smtp_phpmailer']['description'] = (string) t("PHPMailer library @version or higher is required. Please install a newer version by executing 'composer update' in your site's root directory.", [
'@version' => $required_version,
]);
// If incorrect version, SMTP should not be set as the mail system.
_disable_smtp();
}
else {
$requirements['smtp_phpmailer']['severity'] = REQUIREMENT_INFO;
/** @var \Drupal\smtp\ConnectionTester\ConnectionTester $tester */
$tester = \Drupal::service('smtp.connection_tester');
$tester->testConnection();
$requirements = array_merge($requirements, $tester->hookRequirements($phase));
}
}
}
return $requirements;
}
/**
* Helper function to disable SMTP and restore the default mailsystem.
*/
function _disable_smtp() {
$config = \Drupal::service('config.factory');
// Always make sure SMTP is disabled.
$smtp_config = $config->getEditable('smtp.settings');
if (!$smtp_config->get('smtp_on')) {
return;
}
// Set the internal SMTP module config off.
$smtp_config->set('smtp_on', FALSE)->save();
// Set the default back to either the previous mail system or php_mail.
$mail_config = $config->getEditable('system.mail');
$current_default = $mail_config->get('interface.default');
$system_default = 'php_mail';
if ($current_default == 'SMTPMailSystem') {
$default_interface = (!$smtp_config->get('prev_mail_system')) ? $smtp_config->get('prev_mail_system') : $system_default;
$mail_config->set('interface.default', $default_interface)
->save();
}
}
smtp.config:
title: SMTP Authentication Support
route_name: smtp.config
parent: system.admin_config_system
description: 'Allow for site emails to be sent through an SMTP server of your choice.'
weight: -20
<?php
/**
* @file
* Enables Drupal to send e-mail directly to an SMTP server.
*
* This module uses a customized extract of the PHPMailer
* library (originally by Brent R. Matzelle, now maintained
* by Codeworx Tech.) relicensed from LGPL to GPL, included
* as a part of the module.
*
* Overriding mail handling in Drupal to make SMTP the default
* transport layer, requires to change the 'system.mail.interface'
* default value ['default' => 'Drupal\Core\Mail\PhpMail'].
* This module uses ['default' => 'SMTPMailSystem'].
*/
use Drupal\Core\Routing\RouteMatchInterface;
/**
* Implements hook_help().
*/
function smtp_help($route_name, RouteMatchInterface $route_match) {
switch ($route_name) {
case 'help.page.smtp':
return t('Allow for site emails to be sent through an SMTP server of your choice.');
}
}
/**
* Implements hook_mail().
*/
function smtp_mail($key, &$message, $params) {
if ($key == 'smtp-test') {
$message['subject'] = $params['subject'];
$message['body'] = $params['body'];
}
}
/**
* Implements hook_queue_info().
*/
function smtp_queue_info() {
$queues['smtp_send_queue'] = [
'worker callback' => 'smtp_send_queue_runner',
'cron' => [
'time' => 60,
],
];
return $queues;
}
/**
* Smtp_send_queue queuer.
*/
function smtp_send_queue($mailerObj) {
$queue = Drupal::queue('smtp_send_queue');
$queue->createItem($mailerObj);
}
/**
* SMTP queue runner function.
*
* @param array $variables
* Variables to send trought runner.
*/
function smtp_send_queue_runner(array $variables) {
_smtp_mailer_send($variables);
}
/**
* Helper function to send mails.
*
* @param array $variables
* Variables to send email.
*
* @return bool
* True if email was sent. False otherwise.
*/
function _smtp_mailer_send(array $variables) {
$smtp_config = \Drupal::config('smtp.settings');
$mailer = $variables['mailer'];
$to = $variables['to'];
$from = $variables['from'];
$logger = \Drupal::logger('smtp');
// Let the people know what is going on.
$logger->info('Sending mail to: @to', ['@to' => $to]);
// Try to send e-mail. If it fails, set watchdog entry.
try {
$mailer->Send();
}
catch (Exception $e) {
$logger->error('Error sending e-mail from @from to @to: @error_message', [
'@from' => $from,
'@to' => $to,
'@error_message' => $mailer->ErrorInfo,
]);
return FALSE;
}
if (!$smtp_config->get('smtp_keepalive')) {
$mailer->SmtpClose();
}
return TRUE;
}
administer smtp module:
title: 'Administer SMTP Authentication Support module'
description: 'Perform administration tasks for SMTP Authentication Support module.'
restrict access: true
<?php
/**
* @file
* Post update functions for Smtp.
*/
/**
* Rebuild caches to ensure services changes are read in.
*/
function smtp_post_update_connection_tester() {
// Empty update to cause a cache rebuild so that the service changes are read.
}
/**
* Add SMTP timeout configuration and change default to 30.
*/
function smtp_post_update_set_smtp_timeout() {
\Drupal::configFactory()->getEditable('smtp.settings')
->set('smtp_timeout', 30)
->save(TRUE);
}
/**
* Add SMTP keepalive configuration and set default to FALSE.
*/
function smtp_post_update_set_smtp_keepalive() {
\Drupal::configFactory()->getEditable('smtp.settings')
->set('smtp_keepalive', FALSE)
->save(TRUE);
}
/**
* Add SMTP Auto TLS configuration and set default to TRUE.
*/
function smtp_post_update_set_smtp_autotls() {
\Drupal::configFactory()->getEditable('smtp.settings')
->set('smtp_autotls', TRUE)
->save(TRUE);
}
/**
* Rebuild caches to ensure the connection typo service change is updated.
*/
function smtp_post_update_connection_typo() {
// Empty update to cause a cache rebuild so that the service changes are read.
// Caused by this typo: https://www.drupal.org/project/smtp/issues/3150369
}
\ No newline at end of file
smtp.config:
path: '/admin/config/system/smtp'
defaults:
_title: 'SMTP Authentication Support'
_form: 'Drupal\smtp\Form\SMTPConfigForm'
requirements:
_permission: 'administer smtp module'
services:
smtp.logger_channel:
class: Drupal\Core\Logger\LoggerChannel
factory: logger.factory:get
arguments: ['smtp']
smtp.config:
class: Drupal\Core\Config\Config
factory: config.factory:getEditable
arguments: ['smtp.settings']
smtp.connection_tester:
class: Drupal\smtp\ConnectionTester\ConnectionTester
arguments: ['@config.factory', '@smtp.logger_channel', '@plugin.manager.mail']
<?php
namespace Drupal\smtp\ConnectionTester;
use Drupal\Core\Config\ConfigFactory;
use Drupal\Core\Mail\MailManager;
use Drupal\Core\Mail\MailManagerInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\mailsystem\MailsystemManager;
use PHPMailer\PHPMailer\Exception as PHPMailerException;
use PHPMailer\PHPMailer\PHPMailer;
use Psr\Log\LoggerInterface;
/**
* Allows testing the SMTP connection.
*/
class ConnectionTester {
use StringTranslationTrait;
// These constants de not seem to be available outside of the .install file
// so we need to declare them here.
const REQUIREMENT_OK = 0;
const REQUIREMENT_ERROR = 2;
/**
* The severity of the connection issue; set during class construction.
*
* @var int
*/
protected $severity;
/**
* Description of the connection, set during construction..
*
* @var string
*/
protected $value;
/**
* PHP Mailer Object.
*
* @var \PHPMailer\PHPMailer\PHPMailer
*/
protected $phpMailer;
/**
* The Config Factory.
*
* @var \Drupal\Core\Config\ConfigFactoryInterface
*/
protected $configFactory;
/**
* The SMTP Config.
*
* @var \Drupal\Core\Config\Config
*/
protected $smtpConfig;
/**
* The smtp logger channel.
*
* @var \Drupal\Core\Logger\LoggerChannelInterface
*/
protected $logger;
/**
* The mail manager.
*
* @var \Drupal\Core\Mail\MailManagerInterface
*/
protected $mailManager;
/**
* The SMTP ConnectionTester constructor.
*
* @param \Drupal\Core\Config\ConfigFactory $config_factory
* @param \Psr\Log\LoggerInterface $logger
* The logger channel.
* @param \Drupal\Core\Mail\MailManagerInterface $mail_manager
* The Mail manager.
*/
public function __construct(ConfigFactory $config_factory, LoggerInterface $logger, MailManagerInterface $mail_manager) {
$this->configFactory = $config_factory;
$this->smtpConfig = $config_factory->get('smtp.settings');
$this->mailManager = $mail_manager;
$this->logger = $logger;
if (!class_exists(PHPMailer::class)) {
$this->logger->error('Unable to initialize PHPMailer, Class does not exist.');
return;
}
$this->phpMailer = new PHPMailer(TRUE);
}
public function setMailer(PHPMailer $mailer) {
$this->phpMailer = $mailer;
}
/**
* Test SMTP connection.
*/
public function testConnection() {
if (!$this->configurePhpMailer()) {
$this->severity = self::REQUIREMENT_ERROR;
$this->value = $this->t('Unable to initialize PHPMailer.');
return FALSE;
}
$smtp_enabled = $this->smtpConfig->get('smtp_on');
// Check to see if MailSystem is enabled and is using SMTPMailSystem.
if (\Drupal::moduleHandler()->moduleExists('mailsystem')) {
$mailsystem_defaults = $this->configFactory->get('mailsystem.settings')->get('defaults');
$smtp_enabled = in_array('SMTPMailSystem', $mailsystem_defaults);
}
if (!$smtp_enabled) {
$this->severity = self::REQUIREMENT_OK;
$this->value = $this->t('SMTP module is enabled but turned off.');
return FALSE;
}
try {
if ($this->phpMailer->smtpConnect()) {
$this->severity = self::REQUIREMENT_OK;
$this->value = $this->t('SMTP module is enabled, turned on, and connection is valid.');
return TRUE;
}
$this->severity = REQUIREMENT_ERROR;
$this->value = $this->t('SMTP module is enabled, turned on, but SmtpConnect() returned FALSE.');
return FALSE;
}
catch (PHPMailerException $e) {
$this->value = $this->t('SMTP module is enabled, turned on, but SmtpConnect() threw exception @e', [
'@e' => $e->getMessage(),
]);
$this->severity = self::REQUIREMENT_ERROR;
}
catch (\Exception $e) {
$this->value = $this->t('SMTP module is enabled, turned on, but SmtpConnect() threw an unexpected exception');
$this->severity = self::REQUIREMENT_ERROR;
}
return FALSE;
}
/**
* Testable implementation of hook_requirements().
*/
public function hookRequirements(string $phase) {
$requirements = [];
if ($phase == 'runtime') {
$requirements['smtp_connection'] = [
'title' => $this->t('SMTP connection')->__toString(),
'value' => $this->value->__toString(),
'severity' => $this->severity,
];
}
return $requirements;
}
/**
* Get a PHPMailer object ready to be tested.
*
* @return bool
* True if config was set, False if phpMailer didn't exist.
*/
protected function configurePhpMailer() {
if ($this->phpMailer) {
// Set debug to FALSE for the connection test; further debugging can be
// used when sending actual mails.
$this->phpMailer->SMTPDebug = FALSE;
// Hardcoded Timeout for testing so the reports page doesn't stall out.
$this->phpMailer->Timeout = 5;
$this->phpMailer->Host = implode(';', array_filter(
[
$this->smtpConfig->get('smtp_host'),
$this->smtpConfig->get('smtp_hostbackup'),
]
));
$this->phpMailer->Port = $this->smtpConfig->get('smtp_port');
$protocol = $this->smtpConfig->get('smtp_protocol');
$this->phpMailer->SMTPAutoTLS = $this->smtpConfig->get('smtp_autotls');
$this->phpMailer->SMTPSecure = in_array($protocol, ['ssl', 'tls'], TRUE) ? $protocol : '';
if ($smtp_client_hostname = $this->smtpConfig->get('smtp_client_hostname')) {
$this->phpMailer->Hostname = $smtp_client_hostname;
}
if ($helo = $this->smtpConfig->get('smtp_client_helo')) {
$this->phpMailer->Helo = $helo;
}
$username = $this->smtpConfig->get('smtp_username');
$password = $this->smtpConfig->get('smtp_password');
if ($username && $password) {
$this->phpMailer->SMTPAuth = TRUE;
$this->phpMailer->Username = $username;
$this->phpMailer->Password = $password;
}
return TRUE;
}
return FALSE;
}
}
<?php
namespace Drupal\smtp\Form;
use Drupal\Core\Extension\ModuleHandlerInterface;
use PHPMailer\PHPMailer\PHPMailer;
use Drupal\Component\Utility\EmailValidatorInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Mail\MailManagerInterface;
use Drupal\Core\Messenger\Messenger;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Implements the SMTP admin settings form.
*/
class SMTPConfigForm extends ConfigFormBase {
/**
* Drupal messenger service.
*
* @var \Drupal\Core\Messenger\Messenger
*/
protected $messenger;
/**
* Email Validator service.
*
* @var \Drupal\Component\Utility\EmailValidatorInterface
*/
protected $emailValidator;
/**
* The current active user.
*
* @var \Drupal\Core\Session\AccountProxyInterface
*/
protected $currentUser;
/**
* The mail manager service.
*
* @var \Drupal\Core\Mail\MailManagerInterface
*/
protected $mailManager;
/**
* The module handler service.
*
* @var \Drupal\Core\Extension\ModuleHandlerInterface
*/
protected $moduleHandler;
/**
* Constructs $messenger and $config_factory objects.
*
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The factory for configuration objects.
* @param \Drupal\Core\Messenger\Messenger $messenger
* The D8 messenger object.
* @param \Drupal\Component\Utility\EmailValidatorInterface $email_validator
* The Email Validator Service.
*/
public function __construct(ConfigFactoryInterface $config_factory, Messenger $messenger, EmailValidatorInterface $email_validator, AccountProxyInterface $current_user, MailManagerInterface $mail_manager, ModuleHandlerInterface $module_handler) {
$this->messenger = $messenger;
$this->emailValidator = $email_validator;
$this->currentUser = $current_user;
$this->mailManager = $mail_manager;
$this->moduleHandler = $module_handler;
parent::__construct($config_factory);
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('config.factory'),
$container->get('messenger'),
$container->get('email.validator'),
$container->get('current_user'),
$container->get('plugin.manager.mail'),
$container->get('module_handler')
);
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'smtp_admin_settings';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$config = $this->configFactory->getEditable('smtp.settings');
// Don't overwrite the default if MailSystem module is enabled.
$mailsystem_enabled = $this->moduleHandler->moduleExists('mailsystem');
if ($config->get('smtp_on')) {
$this->messenger->addMessage($this->t('SMTP module is active.'));
if ($mailsystem_enabled) {
$this->messenger->addWarning($this->t('SMTP module will use the mailsystem module upon config save.'));
}
}
elseif ($mailsystem_enabled) {
$this->messenger->addMessage($this->t('SMTP module is managed by <a href=":mailsystem">the mail system module</a>', [':mailsystem' => Url::fromRoute('mailsystem.settings')->toString()]));
}
else {
$this->messenger->addMessage($this->t('SMTP module is INACTIVE.'));
}
$this->messenger->addMessage($this->t('Disabled fields are overridden in site-specific configuration file.'), 'warning');
if ($mailsystem_enabled) {
$form['onoff']['smtp_on']['#type'] = 'value';
$form['onoff']['smtp_on']['#value'] = 'mailsystem';
}
else {
$form['onoff'] = [
'#type' => 'details',
'#title' => $this->t('Install options'),
'#open' => TRUE,
];
$form['onoff']['smtp_on'] = [
'#type' => 'radios',
'#title' => $this->t('Set SMTP as the default mailsystem'),
'#default_value' => $config->get('smtp_on') ? 'on' : 'off',
'#options' => ['on' => $this->t('On'), 'off' => $this->t('Off')],
'#description' => $this->t('When on, all mail is passed through the SMTP module.'),
'#disabled' => $this->isOverridden('smtp_on'),
];
// Force Disabling if PHPmailer doesn't exist.
if (!class_exists(PHPMailer::class)) {
$form['onoff']['smtp_on']['#disabled'] = TRUE;
$form['onoff']['smtp_on']['#default_value'] = 'off';
$form['onoff']['smtp_on']['#description'] = $this->t('<strong>SMTP cannot be enabled because the PHPMailer library is missing.</strong>');
}
}
$form['server'] = [
'#type' => 'details',
'#title' => $this->t('SMTP server settings'),
'#open' => TRUE,
];
$form['server']['smtp_host'] = [
'#type' => 'textfield',
'#title' => $this->t('SMTP server'),
'#default_value' => $config->get('smtp_host'),
'#description' => $this->t('The address of your outgoing SMTP server.'),
'#disabled' => $this->isOverridden('smtp_host'),
];
$form['server']['smtp_hostbackup'] = [
'#type' => 'textfield',
'#title' => $this->t('SMTP backup server'),
'#default_value' => $config->get('smtp_hostbackup'),
'#description' => $this->t("The address of your outgoing SMTP backup server. If the primary server can\'t be found this one will be tried. This is optional."),
'#disabled' => $this->isOverridden('smtp_hostbackup'),
];
$form['server']['smtp_port'] = [
'#type' => 'number',
'#title' => $this->t('SMTP port'),
'#size' => 6,
'#maxlength' => 6,
'#default_value' => $config->get('smtp_port'),
'#description' => $this->t('The default SMTP port is 25, if that is being blocked try 80. Gmail uses 465. See :url for more information on configuring for use with Gmail.',
[':url' => 'http://gmail.google.com/support/bin/answer.py?answer=13287']),
'#disabled' => $this->isOverridden('smtp_port'),
];
// Only display the option if openssl is installed.
if (function_exists('openssl_open')) {
$encryption_options = [
'standard' => $this->t('No'),
'ssl' => $this->t('Use SSL'),
'tls' => $this->t('Use TLS'),
];
$encryption_description = $this->t('This allows connection to an SMTP server that requires SSL encryption such as Gmail.');
}
// If openssl is not installed, use normal protocol.
else {
$config->set('smtp_protocol', 'standard');
$encryption_options = ['standard' => $this->t('No')];
$encryption_description = $this->t('Your PHP installation does not have SSL enabled. See the :url page on php.net for more information. Gmail requires SSL.',
[':url' => 'http://php.net/openssl']);
}
$form['server']['smtp_protocol'] = [
'#type' => 'select',
'#title' => $this->t('Use encrypted protocol'),
'#default_value' => $config->get('smtp_protocol'),
'#options' => $encryption_options,
'#description' => $encryption_description,
'#disabled' => $this->isOverridden('smtp_protocol'),
];
$form['server']['smtp_autotls'] = [
'#type' => 'radios',
'#title' => $this->t('Enable TLS encryption automatically'),
'#default_value' => $config->get('smtp_autotls') ? 'on' : 'off',
'#options' => ['on' => $this->t('On'), 'off' => $this->t('Off')],
'#description' => $this->t('Whether to enable TLS encryption automatically if a server supports it, even if the protocol is not set to "tls".'),
'#disabled' => $this->isOverridden('smtp_autotls'),
];
$form['server']['smtp_timeout'] = [
'#type' => 'number',
'#title' => $this->t('Timeout'),
'#size' => 6,
'#maxlength' => 6,
'#default_value' => $config->get('smtp_timeout'),
'#description' => $this->t('Amount of seconds for the SMTP commands to timeout.'),
'#disabled' => $this->isOverridden('smtp_timeout'),
];
$form['auth'] = [
'#type' => 'details',
'#title' => $this->t('SMTP Authentication'),
'#description' => $this->t('Leave blank if your SMTP server does not require authentication.'),
'#open' => TRUE,
];
$form['auth']['smtp_username'] = [
'#type' => 'textfield',
'#title' => $this->t('Username'),
'#default_value' => $config->get('smtp_username'),
'#description' => $this->t('SMTP Username.'),
'#disabled' => $this->isOverridden('smtp_username'),
];
$form['auth']['smtp_password'] = [
'#type' => 'password',
'#title' => $this->t('Password'),
'#default_value' => $config->get('smtp_password'),
'#description' => $this->t("SMTP password. If you have already entered your password before, you should leave this field blank, unless you want to change the stored password. Please note that this password will be stored as plain-text inside Drupal\'s core configuration variables."),
'#disabled' => $this->isOverridden('smtp_password'),
];
$form['email_options'] = [
'#type' => 'details',
'#title' => $this->t('E-mail options'),
'#open' => TRUE,
];
$form['email_options']['smtp_from'] = [
'#type' => 'textfield',
'#title' => $this->t('E-mail from address'),
'#default_value' => $config->get('smtp_from'),
'#description' => $this->t('The e-mail address that all e-mails will be from.'),
'#disabled' => $this->isOverridden('smtp_from'),
];
$form['email_options']['smtp_fromname'] = [
'#type' => 'textfield',
'#title' => $this->t('E-mail from name'),
'#default_value' => $config->get('smtp_fromname'),
'#description' => $this->t('The name that all e-mails will be from. If left blank will use a default of: @name . Some providers (such as Office365) may ignore this field. For more information, please check SMTP module documentation and your email provider documentation.',
['@name' => $this->configFactory->get('system.site')->get('name')]),
'#disabled' => $this->isOverridden('smtp_fromname'),
];
$form['email_options']['smtp_allowhtml'] = [
'#type' => 'checkbox',
'#title' => $this->t('Allow to send e-mails formatted as HTML'),
'#default_value' => $config->get('smtp_allowhtml'),
'#description' => $this->t('Checking this box will allow HTML formatted e-mails to be sent with the SMTP protocol.'),
'#disabled' => $this->isOverridden('smtp_allowhtml'),
];
$form['client'] = [
'#type' => 'details',
'#title' => $this->t('SMTP client settings'),
'#open' => TRUE,
];
$form['client']['smtp_client_hostname'] = [
'#type' => 'textfield',
'#title' => $this->t('Hostname'),
'#default_value' => $config->get('smtp_client_hostname'),
'#description' => $this->t('The hostname to use in the Message-Id and Received headers, and as the default HELO string. Leave blank for using %server_name.',
['%server_name' => isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : 'localhost.localdomain']),
'#disabled' => $this->isOverridden('smtp_client_hostname'),
];
$form['client']['smtp_client_helo'] = [
'#type' => 'textfield',
'#title' => $this->t('HELO'),
'#default_value' => $config->get('smtp_client_helo'),
'#description' => $this->t('The SMTP HELO/EHLO of the message. Defaults to hostname (see above).'),
'#disabled' => $this->isOverridden('smtp_client_helo'),
];
$form['email_test'] = [
'#type' => 'details',
'#title' => $this->t('Send test e-mail'),
'#open' => TRUE,
];
$form['email_test']['smtp_test_address'] = [
'#type' => 'textfield',
'#title' => $this->t('E-mail address to send a test e-mail to'),
'#default_value' => '',
'#description' => $this->t('Type in an address to have a test e-mail sent there.'),
];
$form['smtp_debugging'] = [
'#type' => 'checkbox',
'#title' => $this->t('Enable debugging'),
'#default_value' => $config->get('smtp_debugging'),
'#description' => $this->t('Checking this box will print SMTP messages from the server for every e-mail that is sent.'),
'#disabled' => $this->isOverridden('smtp_debugging'),
];
$form['server']['smtp_keepalive'] = [
'#type' => 'checkbox',
'#title' => $this->t('Turn on the SMTP keep alive feature'),
'#default_value' => $config->get('smtp_keepalive'),
'#description' => $this->t('Enabling this option will keep the SMTP connection open instead of it being openned and then closed for each mail'),
];
return parent::buildForm($form, $form_state);
}
/**
* Check if config variable is overridden by the settings.php.
*
* @param string $name
* SMTP settings key.
*
* @return bool
* Boolean.
*/
protected function isOverridden($name) {
$original = $this->configFactory->getEditable('smtp.settings')->get($name);
$current = $this->configFactory->get('smtp.settings')->get($name);
return $original != $current;
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
$values = $form_state->getValues();
if ($values['smtp_on'] !== 'off' && $values['smtp_host'] == '') {
$form_state->setErrorByName('smtp_host', $this->t('You must enter an SMTP server address.'));
}
if ($values['smtp_on'] !== 'off' && $values['smtp_port'] == '') {
$form_state->setErrorByName('smtp_port', $this->t('You must enter an SMTP port number.'));
}
if ($values['smtp_timeout'] == '' || $values['smtp_timeout'] < 1) {
$form_state->setErrorByName('smtp_timeout', $this->t('You must enter a Timeout value greater than 0.'));
}
if ($values['smtp_from'] && !$this->emailValidator->isValid($values['smtp_from'])) {
$form_state->setErrorByName('smtp_from', $this->t('The provided from e-mail address is not valid.'));
}
if ($values['smtp_test_address'] && !$this->emailValidator->isValid($values['smtp_test_address'])) {
$form_state->setErrorByName('smtp_test_address', $this->t('The provided test e-mail address is not valid.'));
}
// If username is set empty, we must set both
// username/password empty as well.
if (empty($values['smtp_username'])) {
$values['smtp_password'] = '';
}
// A little hack. When form is presented,
// the password is not shown (Drupal way of doing).
// So, if user submits the form without changing the password,
// we must prevent it from being reset.
elseif (empty($values['smtp_password'])) {
$form_state->unsetValue('smtp_password');
}
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$values = $form_state->getValues();
$config = $this->configFactory->getEditable('smtp.settings');
$mail_config = $this->configFactory->getEditable('system.mail');
$mail_system = $mail_config->get('interface.default');
// Updating config vars.
if (isset($values['smtp_password']) && !$this->isOverridden('smtp_password')) {
$config->set('smtp_password', $values['smtp_password']);
}
if (!$this->isOverridden('smtp_on')) {
$config->set('smtp_on', $values['smtp_on'] == 'on')->save();
}
if (!$this->isOverridden('smtp_autotls')) {
$config->set('smtp_autotls', $values['smtp_autotls'] == 'on')->save();
}
$config_keys = [
'smtp_host',
'smtp_hostbackup',
'smtp_port',
'smtp_protocol',
'smtp_timeout',
'smtp_username',
'smtp_from',
'smtp_fromname',
'smtp_client_hostname',
'smtp_client_helo',
'smtp_allowhtml',
'smtp_debugging',
'smtp_keepalive',
];
foreach ($config_keys as $name) {
if (!$this->isOverridden($name)) {
$config->set($name, $values[$name])->save();
}
}
// Set as default mail system if module is enabled.
if ($config->get('smtp_on') ||
($this->isOverridden('smtp_on') && $values['smtp_on'] == 'on')) {
if ($mail_system != 'SMTPMailSystem') {
$config->set('prev_mail_system', $mail_system);
}
$mail_system = 'SMTPMailSystem';
$mail_config->set('interface.default', $mail_system)->save();
}
else {
$default_system_mail = 'php_mail';
$mail_config = $this->configFactory->getEditable('system.mail');
$default_interface = $mail_config->get('prev_mail_system') ? $mail_config->get('prev_mail_system') : $default_system_mail;
$mail_config->set('interface.default', $default_interface)->save();
}
// If an address was given, send a test e-mail message.
if ($test_address = $values['smtp_test_address']) {
$params['subject'] = $this->t('Drupal SMTP test e-mail');
$params['body'] = [$this->t('If you receive this message it means your site is capable of using SMTP to send e-mail.')];
// If module is off, send the test message
// with SMTP by temporarily overriding.
if (!$config->get('smtp_on')) {
$original = $mail_config->get('interface');
$mail_system = 'SMTPMailSystem';
$mail_config->set('interface.default', $mail_system)->save();
}
if ($this->mailManager->mail('smtp', 'smtp-test', $test_address, $this->currentUser->getPreferredLangcode(), $params)) {
$this->messenger->addMessage($this->t('A test e-mail has been sent to @email via SMTP. You may want to check the log for any error messages.', ['@email' => $test_address]));
}
if (!$config->get('smtp_on')) {
$mail_config->set('interface', $original)->save();
}
}
parent::submitForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
protected function getEditableConfigNames() {
return [
'smtp.settings',
];
}
}
<?php
namespace Drupal\smtp\Plugin\Mail;
use Drupal\Component\Utility\EmailValidatorInterface;
use Drupal\Component\Utility\Unicode;
use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\Core\Mail\MailFormatHelper;
use Drupal\Core\Mail\MailInterface;
use Drupal\Core\Messenger\Messenger;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use PHPMailer\PHPMailer\PHPMailer;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesserInterface;
/**
* Modify the drupal mail system to use smtp when sending emails.
*
* Include the option to choose between plain text or HTML.
*
* @Mail(
* id = "SMTPMailSystem",
* label = @Translation("SMTP Mailer"),
* description = @Translation("Sends the message, using SMTP.")
* )
*/
class SMTPMailSystem implements MailInterface, ContainerFactoryPluginInterface {
use StringTranslationTrait;
protected $AllowHtml;
protected $smtpConfig;
/**
* Logger.
*
* @var \Drupal\Core\Logger\LoggerChannelFactoryInterface
*/
protected $logger;
/**
* Messenger.
*
* @var \Drupal\Core\Messenger\Messenger
*/
protected $messenger;
/**
* Email validator.
*
* @var \Drupal\Component\Utility\EmailValidatorInterface
*/
protected $emailValidator;
/**
* The config factory service.
*
* @var \Drupal\Core\Config\ConfigFactoryInterface
*/
protected $configFactory;
/**
* The curent user service.
*
* @var \Drupal\Core\Session\AccountProxyInterface
*/
protected $currentUser;
/**
* The File System service.
*
* @var \Drupal\Core\File\FileSystemInterface
*/
protected $fileSystem;
/**
* The file mime type guesser service.
*
* @var \Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesserInterface
*/
protected $mimeTypeGuesser;
/**
* Constructs a SMPTMailSystem object.
*
* @param array $configuration
* The configuration array.
* @param string $plugin_id
* The plug-in ID.
* @param mixed $plugin_definition
* The plug-in definition.
* @param \Drupal\Core\Logger\LoggerChannelFactoryInterface $logger
* The logger object.
* @param \Drupal\Core\Messenger\Messenger $messenger
* The messenger object.
* @param \Drupal\Component\Utility\EmailValidatorInterface $emailValidator
* The messenger object.
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The config factory object.
* @param \Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesserInterface $mime_type_guesser
* The file mime type guesser service.
*/
public function __construct(array $configuration,
$plugin_id,
$plugin_definition,
LoggerChannelFactoryInterface $logger,
Messenger $messenger,
EmailValidatorInterface $emailValidator,
ConfigFactoryInterface $config_factory,
AccountProxyInterface $account,
FileSystemInterface $file_system,
MimeTypeGuesserInterface $mime_type_guesser) {
$this->smtpConfig = $config_factory->get('smtp.settings');
$this->logger = $logger;
$this->messenger = $messenger;
$this->emailValidator = $emailValidator;
$this->configFactory = $config_factory;
$this->currentUser = $account;
$this->fileSystem = $file_system;
$this->mimeTypeGuesser = $mime_type_guesser;
}
/**
* Creates an instance of the plugin.
*
* @param \Symfony\Component\DependencyInjection\ContainerInterface $container
* The container to pull out services used in the plugin.
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin ID for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
*
* @return static
* Returns an instance of this plugin.
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('logger.factory'),
$container->get('messenger'),
$container->get('email.validator'),
$container->get('config.factory'),
$container->get('current_user'),
$container->get('file_system'),
$container->get('file.mime_type.guesser')
);
}
/**
* Concatenate and wrap the e-mail body for either plain-text or HTML emails.
*
* @param array $message
* A message array, as described in hook_mail_alter().
*
* @return array
* The formatted $message.
*/
public function format(array $message) {
$this->AllowHtml = $this->smtpConfig->get('smtp_allowhtml');
// Join the body array into one string.
$message['body'] = implode("\n\n", $message['body']);
if ($this->AllowHtml == 0) {
// Convert any HTML to plain-text.
$message['body'] = MailFormatHelper::htmlToText($message['body']);
// Wrap the mail body for sending.
$message['body'] = MailFormatHelper::wrapMail($message['body']);
}
return $message;
}
/**
* Send the e-mail message.
*
* @param array $message
* A message array, as described in hook_mail_alter().
*
* @return mixed
* TRUE if the mail was successfully accepted, otherwise FALSE.
*
* @throws \PHPMailer\PHPMailer\Exception
*
* @see drupal_mail()
*/
public function mail(array $message) {
$logger = $this->logger->get('smtp');
if (!class_exists(PHPMailer::class)) {
$logger->error($this->t('Unable to send mail: PHPMailer class was not found.'));
return FALSE;
}
$to = $message['to'];
$body = $message['body'];
$headers = $message['headers'];
$subject = $message['subject'];
// Create a new PHPMailer object - autoloaded from registry.
$mailer = new PHPMailer(TRUE);
// Use email.validator due to different validation standard by PHPMailer.
$mailer::$validator = [$this->emailValidator, 'isValid'];
// Override PHPMailer default timeout if requested.
$smtp_timeout = $this->smtpConfig->get('smtp_timeout');
if (!empty($smtp_timeout)) {
$mailer->Timeout = $smtp_timeout;
}
// Turn on debugging, if requested.
if ($this->smtpConfig->get('smtp_debugging')
&& $this->currentUser->hasPermission('administer smtp module')) {
$mailer->SMTPDebug = TRUE;
}
// Turn on KeepAlive feature if requested.
if ($this->smtpConfig->get('smtp_keepalive')) {
$mailer->SMTPKeepAlive = TRUE;
}
// Prefer the from_name from the message.
if (!empty($message['params']['from_name'])) {
$from_name = $message['params']['from_name'];
}
// If the smtp_fromname is set, it overrides the name that was passed as
// part of the $from address.
elseif (!empty($this->smtpConfig->get('smtp_fromname'))) {
$from_name = $this->smtpConfig->get('smtp_fromname');
}
if (empty($from_name)) {
// If value is not defined in settings, use site_name.
$from_name = $this->configFactory->get('system.site')->get('name');
}
// Set from email.
if (!empty($message['params']['from_mail'])) {
$from = $message['params']['from_mail'];
}
// Set SMTP module email from.
elseif ($this->emailValidator->isValid($this->smtpConfig->get('smtp_from'))) {
$from = $this->smtpConfig->get('smtp_from');
}
if (empty($from)) {
$from = $message['from'];
// The $from address might contain the "name" part. If it does, split it,
// since PHPMailer expects $from to be the raw email address.
$matches = [];
if (preg_match('/^(.*)\s\<(.*)\>$/', $from, $matches)) {
$from = $matches[2];
}
}
$headers['Sender'] = $from;
$headers['Return-Path'] = $from;
$headers['Reply-To'] = $from;
// Defines the From value to what we expect.
$mailer->From = $from;
$mailer->FromName = Unicode::mimeHeaderEncode($from_name);
$mailer->Sender = $from;
$hostname = $this->smtpConfig->get('smtp_client_hostname');
if ($hostname != '') {
$mailer->Hostname = $hostname;
}
$helo = $this->smtpConfig->get('smtp_client_helo');
if ($helo != '') {
$mailer->Helo = $helo;
}
// Create the list of 'To:' recipients.
$torecipients = explode(',', $to);
foreach ($torecipients as $torecipient) {
$to_comp = $this->getComponents($torecipient);
$mailer->AddAddress($to_comp['email'], $to_comp['name']);
}
// Parse the headers of the message and set the PHPMailer object's settings
// accordingly.
foreach ($headers as $key => $value) {
switch (strtolower($key)) {
case 'from':
if ($from == NULL or $from == '') {
// If a from value was already given, then set based on header.
// Should be the most common situation since drupal_mail moves the.
// from to headers.
$from = $value;
$mailer->From = $value;
$mailer->FromName = '';
$mailer->Sender = $value;
}
break;
case 'content-type':
// Parse several values on the Content-type header,
// storing them in an array like.
// key=value -> $vars['key']='value'.
$vars = explode(';', $value);
foreach ($vars as $i => $var) {
if ($cut = strpos($var, '=')) {
$new_var = trim(strtolower(substr($var, $cut + 1)));
$new_key = trim(substr($var, 0, $cut));
unset($vars[$i]);
$vars[$new_key] = $new_var;
}
}
// Set the charset based on the provided value,
// otherwise set it to UTF-8 (which is Drupal's internal default).
$mailer->CharSet = isset($vars['charset']) ? $vars['charset'] : 'UTF-8';
// If $vars is empty then set an empty value at index 0,
// to avoid a PHP warning in the next statement.
$vars[0] = isset($vars[0]) ? $vars[0] : '';
switch ($vars[0]) {
case 'text/plain':
// The message includes only a plain text part.
$mailer->IsHTML(FALSE);
$content_type = 'text/plain';
break;
case 'text/html':
// The message includes only an HTML part.
$mailer->IsHTML(TRUE);
$content_type = 'text/html';
break;
case 'multipart/related':
// Get the boundary ID from the Content-Type header.
$boundary = $this->getSubstring($value, 'boundary', '"', '"');
// The message includes an HTML part w/inline attachments.
$mailer->ContentType = $content_type = 'multipart/related; boundary="' . $boundary . '"';
break;
case 'multipart/alternative':
// The message includes both a plain text and an HTML part.
$mailer->ContentType = $content_type = 'multipart/alternative';
// Get the boundary ID from the Content-Type header.
$boundary = $this->getSubstring($value, 'boundary', '"', '"');
break;
case 'multipart/mixed':
// The message includes one or more attachments.
$mailer->ContentType = $content_type = 'multipart/mixed';
// Get the boundary ID from the Content-Type header.
$boundary = $this->getSubstring($value, 'boundary', '"', '"');
break;
default:
// Everything else is unsupported by PHPMailer.
$this->messenger->addMessage($this->t('The %header of your message is not supported by PHPMailer and will be sent as text/plain instead.',
['%header' => "Content-Type: $value"]),
'error');
$logger->error($this->t('The %header of your message is not supported by PHPMailer and will be sent as text/plain instead.',
['%header' => "Content-Type: $value"]));
// Force the Content-Type to be text/plain.
$mailer->IsHTML(FALSE);
$content_type = 'text/plain';
}
break;
case 'reply-to':
// Only add a "reply-to" if it's not the same as "return-path".
if ($value != $headers['Return-Path']) {
$reply_to_comp = $this->getComponents($value);
$mailer->AddReplyTo($reply_to_comp['email'], $reply_to_comp['name']);
}
break;
case 'content-transfer-encoding':
$mailer->Encoding = $value;
break;
case 'return-path':
$mailer->Sender = $value;
break;
case 'mime-version':
case 'x-mailer':
// Let PHPMailer specify these.
break;
case 'errors-to':
$mailer->AddCustomHeader('Errors-To: ' . $value);
break;
case 'cc':
$cc_recipients = explode(',', $value);
foreach ($cc_recipients as $cc_recipient) {
$cc_comp = $this->getComponents($cc_recipient);
$mailer->AddCC($cc_comp['email'], $cc_comp['name']);
}
break;
case 'bcc':
$bcc_recipients = explode(',', $value);
foreach ($bcc_recipients as $bcc_recipient) {
$bcc_comp = $this->getComponents($bcc_recipient);
$mailer->AddBCC($bcc_comp['email'], Unicode::mimeHeaderEncode($bcc_comp['name']));
}
break;
default:
// The header key is not special - add it as is.
$mailer->AddCustomHeader($key . ': ' . $value);
}
}
// TODO
// Need to figure out the following.
//
// Add one last header item, but not if it has already been added.
// $errors_to = FALSE;
// foreach ($mailer->CustomHeader as $custom_header) {
// if ($custom_header[0] = '') {
// $errors_to = TRUE;
// }
// }
// if ($errors_to) {
// $mailer->AddCustomHeader('Errors-To: '. $from);
// }.
// Add the message's subject.
$mailer->Subject = $subject;
// Processes the message's body.
switch ($content_type) {
case 'multipart/related':
$mailer->Body = $body;
// TODO: Figure out if there is anything more to handling this type.
break;
case 'multipart/alternative':
// Split the body based on the boundary ID.
$body_parts = $this->boundarySplit($body, $boundary);
foreach ($body_parts as $body_part) {
// If plain/text within the body part, add it to $mailer->AltBody.
if (strpos($body_part, 'text/plain')) {
// Clean up the text.
$body_part = trim($this->removeHeaders(trim($body_part)));
// Include it as part of the mail object.
$mailer->AltBody = $body_part;
}
// If plain/html within the body part, add it to $mailer->Body.
elseif (strpos($body_part, 'text/html')) {
// Clean up the text.
$body_part = trim($this->removeHeaders(trim($body_part)));
// Include it as part of the mail object.
$mailer->Body = $body_part;
}
}
break;
case 'multipart/mixed':
// Split the body based on the boundary ID.
$body_parts = $this->boundarySplit($body, $boundary);
// Determine if there is an HTML part.
$text_html = FALSE;
foreach ($body_parts as $body_part) {
if (strpos($body_part, 'text/html')) {
$text_html = TRUE;
}
}
foreach ($body_parts as $body_part) {
// If test/plain within the body part, add it to either
// $mailer->AltBody or $mailer->Body, depending on whether there is
// also a text/html part ot not.
if (strpos($body_part, 'multipart/alternative')) {
// Get boundary ID from the Content-Type header.
$boundary2 = $this->getSubstring($body_part, 'boundary', '"', '"');
// Clean up the text.
$body_part = trim($this->removeHeaders(trim($body_part)));
// Split the body based on the boundary ID.
$body_parts2 = $this->boundarySplit($body_part, $boundary2);
foreach ($body_parts2 as $body_part2) {
// If plain/text within the body part, add it to $mailer->AltBody.
if (strpos($body_part2, 'text/plain')) {
// Clean up the text.
$body_part2 = trim($this->removeHeaders(trim($body_part2)));
// Include it as part of the mail object.
$mailer->AltBody = $body_part2;
$mailer->ContentType = 'multipart/mixed';
}
// If plain/html within the body part, add it to $mailer->Body.
elseif (strpos($body_part2, 'text/html')) {
// Get the encoding.
$body_part2_encoding = trim($this->getSubstring($body_part2, 'Content-Transfer-Encoding', ' ', "\n"));
// Clean up the text.
$body_part2 = trim($this->removeHeaders(trim($body_part2)));
// Check whether the encoding is base64, and if so, decode it.
if (mb_strtolower($body_part2_encoding) == 'base64') {
// Include it as part of the mail object.
$mailer->Body = base64_decode($body_part2);
// Ensure the whole message is recoded in the base64 format.
$mailer->Encoding = 'base64';
}
else {
// Include it as part of the mail object.
$mailer->Body = $body_part2;
}
$mailer->ContentType = 'multipart/mixed';
}
}
}
// If text/plain within the body part, add it to $mailer->Body.
elseif (strpos($body_part, 'text/plain')) {
// Clean up the text.
$body_part = trim($this->removeHeaders(trim($body_part)));
if ($text_html) {
$mailer->AltBody = $body_part;
$mailer->IsHTML(TRUE);
$mailer->ContentType = 'multipart/mixed';
}
else {
$mailer->Body = $body_part;
$mailer->IsHTML(FALSE);
$mailer->ContentType = 'multipart/mixed';
}
}
// If text/html within the body part, add it to $mailer->Body.
elseif (strpos($body_part, 'text/html')) {
// Clean up the text.
$body_part = trim($this->removeHeaders(trim($body_part)));
// Include it as part of the mail object.
$mailer->Body = $body_part;
$mailer->IsHTML(TRUE);
$mailer->ContentType = 'multipart/mixed';
}
// Add the attachment.
elseif (strpos($body_part, 'Content-Disposition: attachment;') && !isset($message['params']['attachments'])) {
$file_path = $this->getSubstring($body_part, 'filename=', '"', '"');
$file_name = $this->getSubstring($body_part, ' name=', '"', '"');
$file_encoding = $this->getSubstring($body_part, 'Content-Transfer-Encoding', ' ', "\n");
$file_type = $this->getSubstring($body_part, 'Content-Type', ' ', ';');
if (file_exists($file_path)) {
if (!$mailer->AddAttachment($file_path, $file_name, $file_encoding, $file_type)) {
$this->messenger->addMessage($this->t('Attachment could not be found or accessed.'));
}
}
else {
// Clean up the text.
$body_part = trim($this->removeHeaders(trim($body_part)));
if (mb_strtolower($file_encoding) == 'base64') {
$attachment = base64_decode($body_part);
}
elseif (mb_strtolower($file_encoding) == 'quoted-printable') {
$attachment = quoted_printable_decode($body_part);
}
else {
$attachment = $body_part;
}
$attachment_new_filename = $this->fileSystem->tempnam('temporary://', 'smtp');
$file_path = file_save_data($attachment, $attachment_new_filename, FileSystemInterface::EXISTS_REPLACE);
$real_path = $this->fileSystem->realpath($file_path->uri);
if (!$mailer->AddAttachment($real_path, $file_name)) {
$this->messenger->addMessage($this->t('Attachment could not be found or accessed.'));
}
}
}
}
break;
default:
$mailer->Body = $body;
break;
}
// Process mimemail attachments, which are prepared in mimemail_mail().
if (!empty($message['params']['attachments'])) {
foreach ($message['params']['attachments'] as $attachment) {
if (isset($attachment['filecontent'])) {
$mailer->AddStringAttachment($attachment['filecontent'], $attachment['filename'], 'base64', $attachment['filemime']);
}
if (isset($attachment['filepath'])) {
$filename = isset($attachment['filename']) ? $attachment['filename'] : basename($attachment['filepath']);
$filemime = isset($attachment['filemime']) ? $attachment['filemime'] : $this->mimeTypeGuesser->guess($attachment['filepath']);
$mailer->AddAttachment($attachment['filepath'], $filename, 'base64', $filemime);
}
}
}
// Set the authentication settings.
$username = $this->smtpConfig->get('smtp_username');
$password = $this->smtpConfig->get('smtp_password');
// If username and password are given, use SMTP authentication.
if ($username != '' && $password != '') {
$mailer->SMTPAuth = TRUE;
$mailer->Username = $username;
$mailer->Password = $password;
}
// Set the protocol prefix for the smtp host.
switch ($this->smtpConfig->get('smtp_protocol')) {
case 'ssl':
$mailer->SMTPSecure = 'ssl';
break;
case 'tls':
$mailer->SMTPSecure = 'tls';
break;
default:
$mailer->SMTPSecure = '';
}
$mailer->SMTPAutoTLS = $this->smtpConfig->get('smtp_autotls');
// Set other connection settings.
$mailer->Host = $this->smtpConfig->get('smtp_host') . ';' . $this->smtpConfig->get('smtp_hostbackup');
$mailer->Port = $this->smtpConfig->get('smtp_port');
$mailer->Mailer = 'smtp';
$mailerArr = [
'mailer' => $mailer,
'to' => $to,
'from' => $from,
];
if ($this->smtpConfig->get('smtp_queue')) {
$logger->info($this->t('Queue sending mail to: @to', ['@to' => $to]));
smtp_send_queue($mailerArr);
}
else {
return $this->smtpMailerSend($mailerArr);
}
return TRUE;
}
/**
* Splits the input into parts based on the given boundary.
*
* Swiped from Mail::MimeDecode, with modifications based on Drupal's coding
* standards and this bug report: http://pear.php.net/bugs/bug.php?id=6495
*
* @param string $input
* A string containing the body text to parse.
* @param string $boundary
* A string with the boundary string to parse on.
*
* @return array
* An array containing the resulting mime parts
*/
protected function boundarySplit($input, $boundary) {
$parts = [];
$bs_possible = substr($boundary, 2, -2);
$bs_check = '\"' . $bs_possible . '\"';
if ($boundary == $bs_check) {
$boundary = $bs_possible;
}
$tmp = explode('--' . $boundary, $input);
for ($i = 1; $i < count($tmp); $i++) {
if (trim($tmp[$i])) {
$parts[] = $tmp[$i];
}
}
return $parts;
}
/**
* Strips the headers from the body part.
*
* @param string $input
* A string containing the body part to strip.
*
* @return string
* A string with the stripped body part.
*/
protected function removeHeaders($input) {
$part_array = explode("\n", $input);
// Will strip these headers according to RFC2045.
$headers_to_strip = [
'Content-Type',
'Content-Transfer-Encoding',
'Content-ID',
'Content-Disposition',
];
$pattern = '/^(' . implode('|', $headers_to_strip) . '):/';
while (count($part_array) > 0) {
// Ignore trailing spaces/newlines.
$line = rtrim($part_array[0]);
// If the line starts with a known header string.
if (preg_match($pattern, $line)) {
$line = rtrim(array_shift($part_array));
// Remove line containing matched header.
// If line ends in a ';' and the next line starts with four spaces,
// it's a continuation of the header split onto the next line.
// Continue removing lines while we have this condition.
while (substr($line, -1) == ';' && count($part_array) > 0 && substr($part_array[0], 0, 4) == ' ') {
$line = rtrim(array_shift($part_array));
}
}
else {
// No match header, must be past headers; stop searching.
break;
}
}
$output = implode("\n", $part_array);
return $output;
}
/**
* Returns a string that is contained within another string.
*
* Returns the string from within $source that is some where after $target
* and is between $beginning_character and $ending_character.
*
* @param string $source
* A string containing the text to look through.
* @param string $target
* A string containing the text in $source to start looking from.
* @param string $beginning_character
* A string containing the character just before the sought after text.
* @param string $ending_character
* A string containing the character just after the sought after text.
*
* @return string
* A string with the text found between the $beginning_character and the
* $ending_character.
*/
protected function getSubstring($source, $target, $beginning_character, $ending_character) {
$search_start = strpos($source, $target) + 1;
$first_character = strpos($source, $beginning_character, $search_start) + 1;
$second_character = strpos($source, $ending_character, $first_character) + 1;
$substring = substr($source, $first_character, $second_character - $first_character);
$string_length = strlen($substring) - 1;
if ($substring[$string_length] == $ending_character) {
$substring = substr($substring, 0, $string_length);
}
return $substring;
}
/**
* Returns an array of name and email address from a string.
*
* @param string $input
* A string that contains different possible combinations of names and
* email address.
*
* @return array
* An array containing a name and an email address.
*/
protected function getComponents($input) {
$input = trim($input);
$components = [
'input' => $input,
'name' => '',
'email' => '',
];
// If the input is a valid email address in its entirety,
// then there is nothing to do, just return that.
if ($this->emailValidator->isValid($input)) {
$components['email'] = $input;
return $components;
}
// Check if $input has one of the following formats, extract what we can:
// some name <address@example.com>.
// "another name" <address@example.com>.
// <address@example.com>.
if (preg_match('/^"?([^"\t\n]*)"?\s*<([^>\t\n]*)>$/', $input, $matches)) {
$components['name'] = trim($matches[1]);
$components['email'] = trim($matches[2]);
}
return $components;
}
/**
* Wrapper around global static call to increase testability.
*
* @param array $mailerArr
* Variables to send email.
*
* @return bool
* True if email was sent. False otherwise.
*
* @see _smtp_mailer_send;
*/
function smtpMailerSend($mailerArr) {
return _smtp_mailer_send($mailerArr);
}
}
<?php
namespace Drupal\Tests\smtp\Kernel\ConnectionTester;
use Drupal\KernelTests\KernelTestBase;
use Drupal\smtp\ConnectionTester\ConnectionTester;
use PHPMailer\PHPMailer\Exception as PHPMailerException;
use PHPMailer\PHPMailer\PHPMailer;
/**
* Class DeleteEntityTest.
*
* @group acquia_contenthub
*
* @package Drupal\Tests\acquia_contenthub\Kernel
*/
class ConnectionTesterTest extends KernelTestBase {
public static $modules = [
'smtp',
];
/**
* Test for hookRequirements().
*
* @param string $message
* The test message.
* @param bool $smtp_on
* Mock value of whether SMTP is on or not.
* @param bool $result
* Mock result of ::SmtpConnect().
* @param string $exception
* The exception, if any, that the mock SmtpConnect() should throw.
* @param array $expected
* The expected result; ignored if an exception is expected.
*
* @cover ::hookRequirements
* @dataProvider providerHookRequirements
*/
public function testHookRequirements(string $message, bool $smtp_on, bool $result, string $exception, array $expected) {
$smtp_settings = \Drupal::configFactory()
->getEditable('smtp.settings');
$smtp_settings->set('smtp_on', $smtp_on);
$smtp_settings->save();
$object = \Drupal::service('smtp.connection_tester');
$object->setMailer($this->getMockMailer($result, $exception));
$object->testConnection();
$output = $object->hookRequirements('runtime');
if ($output != $expected) {
print_r([
'message' => $message,
'output' => $output,
'expected' => $expected,
]);
}
$this->assertTrue($output == $expected, $message);
}
/**
* Provider for testHookRequirements().
*/
public function providerHookRequirements() {
return [
[
'message' => 'SMTP on, working.',
'$smtp_on' => TRUE,
'result' => TRUE,
'exception' => '',
'expected' => [
'smtp_connection' => [
'title' => 'SMTP connection',
'value' => 'SMTP module is enabled, turned on, and connection is valid.',
'severity' => ConnectionTester::REQUIREMENT_OK,
],
],
],
[
'message' => 'SMTP on, result FALSE.',
'$smtp_on' => TRUE,
'result' => FALSE,
'exception' => '',
'expected' => [
'smtp_connection' => [
'title' => 'SMTP connection',
'value' => 'SMTP module is enabled, turned on, but SmtpConnect() returned FALSE.',
'severity' => ConnectionTester::REQUIREMENT_ERROR,
],
],
],
[
'message' => 'SMTP on, PHPMailerException.',
'$smtp_on' => TRUE,
'result' => FALSE,
'exception' => PHPMailerException::class,
'expected' => [
'smtp_connection' => [
'title' => 'SMTP connection',
'value' => 'SMTP module is enabled, turned on, but SmtpConnect() threw exception EXCEPTION MESSAGE',
'severity' => ConnectionTester::REQUIREMENT_ERROR,
],
],
],
[
'message' => 'SMTP on, Exception.',
'$smtp_on' => TRUE,
'result' => FALSE,
'exception' => \Exception::class,
'expected' => [
'smtp_connection' => [
'title' => 'SMTP connection',
'value' => 'SMTP module is enabled, turned on, but SmtpConnect() threw an unexpected exception',
'severity' => ConnectionTester::REQUIREMENT_ERROR,
],
],
],
[
'message' => 'SMTP off.',
'$smtp_on' => FALSE,
'result' => FALSE,
'exception' => '',
'expected' => [
'smtp_connection' => [
'title' => 'SMTP connection',
'value' => 'SMTP module is enabled but turned off.',
'severity' => ConnectionTester::REQUIREMENT_OK,
],
],
],
];
}
/**
* Create a mock PHPMailer class for testing the exceptions.
*
* @param $result
* Expected Result.
* @param $exception
* Exception passed in.
*
* @return \PHPMailer\PHPMailer\PHPMailer|__anonymous@4029
*/
private function getMockMailer($result, $exception) {
$class = new class($result, $exception) extends PHPMailer {
public function __construct($result, $exception) {
$this->result = $result;
$this->exception = $exception;
}
/**
* Mock function for connection.
*/
public function smtpConnect($options = NULL) {
if ($this->exception) {
$class = $this->exception;
throw new $class('EXCEPTION MESSAGE');
}
return $this->result;
}
};
return $class;
}
}
<?php
namespace Drupal\Tests\smtp\Unit\Plugin\Mail;
use Drupal\Component\Utility\EmailValidator;
use Drupal\Component\Utility\EmailValidatorInterface;
use Drupal\Core\File\FileSystem;
use Drupal\Core\File\MimeType\MimeTypeGuesser;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\Core\Logger\LoggerChannelInterface;
use Drupal\Core\Messenger\Messenger;
use Drupal\Core\Session\AccountProxy;
use Drupal\Core\StringTranslation\TranslationInterface;
use Drupal\smtp\Plugin\Mail\SMTPMailSystem;
use Drupal\Tests\UnitTestCase;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception as PHPMailerException;
use Prophecy\Argument;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Validate requirements for SMTPMailSystem.
*
* @group SMTP
*/
class SMTPMailSystemTest extends UnitTestCase {
/**
* The email validator.
*
* @var \Drupal\Component\Utility\EmailValidatorInterface
*/
protected $emailValidator;
/**
* {@inheritdoc}
*/
protected function setUp() {
$this->mockConfigFactory = $this->getConfigFactoryStub([
'smtp.settings' => ['smtp_timeout' => 30],
'system.site' => ['name' => 'Mock site name'],
]);
$this->mockLogger = $this->prophesize(LoggerChannelFactoryInterface::class);
$this->mockLogger->get('smtp')->willReturn($this->prophesize(LoggerChannelInterface::class));
$this->mockMessenger = $this->prophesize(Messenger::class);
$this->mockCurrentUser = $this->prophesize(AccountProxy::class);
$this->mockFileSystem = $this->prophesize(FileSystem::class);
$this->mimeTypeGuesser = $this->prophesize(MimeTypeGuesser::class);
$mockContainer = $this->mockContainer = $this->prophesize(ContainerInterface::class);
$mockContainer->get('config.factory')->willReturn($this->mockConfigFactory);
$mockContainer->get('logger.factory')->willReturn($this->mockLogger->reveal());
$mockContainer->get('messenger')->willReturn($this->mockMessenger->reveal());
$mockContainer->get('current_user')->willReturn($this->mockCurrentUser->reveal());
$mockContainer->get('file_system')->willReturn($this->mockFileSystem->reveal());
$mockContainer->get('file.mime_type.guesser')->willReturn($this->mimeTypeGuesser->reveal());
$mockStringTranslation = $this->prophesize(TranslationInterface::class);
$mockStringTranslation->translate(Argument::any())->willReturnArgument(0);
$mockStringTranslation->translate(Argument::any(), Argument::any())->willReturnArgument(0);
$mockStringTranslation->translateString(Argument::any())->willReturn('.');
$mockContainer->get('string_translation')->willReturn($mockStringTranslation->reveal());
// Email validator.
$this->emailValidator = new EmailValidator();
$mockContainer->get('email.validator')->willReturn($this->emailValidator);
\Drupal::setContainer($this->mockContainer->reveal());
}
/**
* Provides scenarios for getComponents().
*/
public function getComponentsProvider() {
return [
[
// Input.
'name@example.com',
// Expected.
[
'name' => '',
'email' => 'name@example.com',
],
],
[
' name@example.com',
[
'name' => '',
'input' => 'name@example.com',
'email' => 'name@example.com',
],
],
[
'name@example.com ',
[
'name' => '',
'input' => 'name@example.com',
'email' => 'name@example.com',
],
],
[
'some name <address@example.com>',
[
'name' => 'some name',
'email' => 'address@example.com',
],
],
[
'"some name" <address@example.com>',
[
'name' => 'some name',
'email' => 'address@example.com',
],
],
[
'<address@example.com>',
[
'name' => '',
'email' => 'address@example.com',
],
],
];
}
/**
* Test getComponents().
*
* @dataProvider getComponentsProvider
*/
public function testGetComponents($input, $expected) {
$mailSystem = new SMTPMailSystemTestHelper([], '', [], $this->mockLogger->reveal(), $this->mockMessenger->reveal(), $this->emailValidator, $this->mockConfigFactory, $this->mockCurrentUser->reveal(), $this->mockFileSystem->reveal(), $this->mimeTypeGuesser->reveal());
$ret = $mailSystem->publiGetComponents($input);
if (!empty($expected['input'])) {
$this->assertEquals($expected['input'], $ret['input']);
}
else {
$this->assertEquals($input, $ret['input']);
}
$this->assertEquals($expected['name'], $ret['name']);
$this->assertEquals($expected['email'], $ret['email']);
}
/**
* Provides scenarios for testMailValidator().
*/
public function mailValidatorProvider() {
$emailValidatorPhpMailerDefault = new EmailValidatorPhpMailerDefault();
$emailValidatorDrupal = new EmailValidator();
return [
'Without umlauts, PHPMailer default validator, no exception' => [
'test@drupal.org',
'PhpUnit Localhost <phpunit@localhost.com>',
$emailValidatorPhpMailerDefault,
NULL,
],
'With umlauts in local part, PHPMailer default validator, exception' => [
'testmüller@drupal.org',
'PhpUnit Localhost <phpunit@localhost.com>',
$emailValidatorPhpMailerDefault,
PHPMailerException::class,
],
'With umlauts in domain part, PHPMailer default validator, exception' => [
'test@müllertest.de',
'PhpUnit Localhost <phpunit@localhost.com>',
$emailValidatorPhpMailerDefault,
PHPMailerException::class,
],
'Without top-level domain in domain part, PHPMailer default validator, exception' => [
'test@drupal',
'PhpUnit Localhost <phpunit@localhost.com>',
$emailValidatorPhpMailerDefault,
PHPMailerException::class,
],
'Without umlauts, Drupal mail validator, no exception' => [
'test@drupal.org',
'PhpUnit Localhost <phpunit@localhost.com>',
$emailValidatorDrupal,
NULL,
],
'With umlauts in local part, Drupal mail validator, no exception' => [
'testmüller@drupal.org',
'PhpUnit Localhost <phpunit@localhost.com>',
$emailValidatorDrupal,
NULL,
],
'With umlauts in domain part, Drupal mail validator, no exception' => [
'test@müllertest.de',
'PhpUnit Localhost <phpunit@localhost.com>',
$emailValidatorDrupal,
NULL,
],
'Without top-level domain in domain part, Drupal mail validator, no exception' => [
'test@drupal',
'PhpUnit Localhost <phpunit@localhost.com>',
$emailValidatorDrupal,
NULL,
],
];
}
/**
* Test mail() with focus on the mail validator.
*
* @dataProvider mailValidatorProvider
*/
public function testMailValidator(string $to, string $from, EmailValidatorInterface $validator, $exception) {
$this->emailValidator = $validator;
$mailSystem = new SMTPMailSystemTestHelper(
[],
'',
[],
$this->mockLogger->reveal(),
$this->mockMessenger->reveal(),
$validator,
$this->mockConfigFactory,
$this->mockCurrentUser->reveal(),
$this->mockFileSystem->reveal(),
$this->mimeTypeGuesser->reveal()
);
$message = [
'to' => $to,
'from' => $from,
'body' => 'Some test content for testMailValidatorDrupal',
'headers' => [
'content-type' => 'text/plain',
],
'subject' => 'testMailValidatorDrupal',
];
if (isset($exception)) {
$this->expectException($exception);
}
// Call function.
$result = $mailSystem->mail($message);
// More important than the result is that no exception was thrown, if
// $exception is unset.
self::assertTrue($result);
}
}
/**
* Test helper for SMTPMailSystemTest.
*/
class SMTPMailSystemTestHelper extends SMTPMailSystem {
/**
* Exposes getComponents for testing.
*/
public function publiGetComponents($input) {
return $this->getComponents($input);
}
/**
* Dummy of smtpMailerSend.
*/
public function smtpMailerSend($mailerArr) {
return TRUE;
}
}
/**
* An adaptor class wrapping the default PHPMailer validator.
*/
class EmailValidatorPhpMailerDefault implements EmailValidatorInterface {
/**
* {@inheritdoc}
*
* This function validates in same way the PHPMailer class does in its
* default behavior.
*/
public function isValid($email) {
PHPMailer::$validator = 'php';
return PHPMailer::validateAddress($email);
}
}
<?php
namespace Drupal\Tests\smtp\Unit;
use Drupal\Component\Utility\EmailValidatorInterface;
use Drupal\Core\Config\Config;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Form\FormState;
use Drupal\Core\Mail\MailManagerInterface;
use Drupal\Core\Messenger\Messenger;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\StringTranslation\TranslationInterface;
use Drupal\smtp\Form\SMTPConfigForm;
use Drupal\Tests\UnitTestCase;
use Prophecy\Argument;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Validate requirements for SMTPConfigForm.
*
* @group SMTP
*/
class SMTPConfigFormTest extends UnitTestCase {
/**
* Test setup.
*/
public function setup() {
$this->mockConfigFactory = $this->prophesize(ConfigFactoryInterface::class);
$this->mockConfig = $this->prophesize(Config::class);
$this->mockConfigFactory->get('smtp.settings')->willReturn($this->mockConfig->reveal());
$this->mockConfigFactory->getEditable('smtp.settings')->willReturn($this->mockConfig->reveal());
$this->mockConfigSystemSite = $this->prophesize(Config::class);
$this->mockConfigSystemSite->get('name')->willReturn('Site name');
$this->mockConfigFactory->get('system.site')->willReturn($this->mockConfigSystemSite->reveal());
$this->mockMessenger = $this->prophesize(Messenger::class);
$this->mockEmailValidator = $this->prophesize(EmailValidatorInterface::class);
$this->mockCurrentUser = $this->prophesize(AccountProxyInterface::class);
$this->mockMailManager = $this->prophesize(MailManagerInterface::class);
$this->mockModuleHandler = $this->prophesize(ModuleHandlerInterface::class);
$mockContainer = $this->mockContainer = $this->prophesize(ContainerInterface::class);
$mockContainer->get('config.factory')->willReturn($this->mockConfigFactory->reveal());
$mockContainer->get('messenger')->willReturn($this->mockMessenger->reveal());
$mockContainer->get('email.validator')->willReturn($this->mockEmailValidator->reveal());
$mockContainer->get('current_user')->willReturn($this->mockCurrentUser->reveal());
$mockContainer->get('plugin.manager.mail')->willReturn($this->mockMailManager->reveal());
$mockContainer->get('module_handler')->willReturn($this->mockModuleHandler->reveal());
$mockStringTranslation = $this->prophesize(TranslationInterface::class);
$mockStringTranslation->translate(Argument::any())->willReturnArgument(0);
$mockStringTranslation->translate(Argument::any(), Argument::any())->willReturnArgument(0);
$mockStringTranslation->translateString(Argument::any())->willReturn('.');
$mockContainer->get('string_translation')->willReturn($mockStringTranslation->reveal());
\Drupal::setContainer($this->mockContainer->reveal());
}
/**
* Sets the default smtp config.
*/
public function setDefaultConfig() {
$this->mockConfig->get('smtp_on')->willReturn(TRUE);
$this->mockConfig->get('smtp_host')->willReturn('');
$this->mockConfig->get('smtp_hostbackup')->willReturn('');
$this->mockConfig->get('smtp_port')->willReturn('');
$this->mockConfig->get('smtp_protocol')->willReturn('');
$this->mockConfig->get('smtp_autotls')->willReturn(TRUE);
$this->mockConfig->get('smtp_timeout')->willReturn('');
$this->mockConfig->get('smtp_username')->willReturn('');
$this->mockConfig->get('smtp_password')->willReturn('');
$this->mockConfig->get('smtp_from')->willReturn('');
$this->mockConfig->get('smtp_fromname')->willReturn('');
$this->mockConfig->get('smtp_allowhtml')->willReturn('');
$this->mockConfig->get('smtp_client_hostname')->willReturn('');
$this->mockConfig->get('smtp_client_helo')->willReturn('');
$this->mockConfig->get('smtp_debugging')->willReturn('');
$this->mockConfig->get('smtp_keepalive')->willReturn(FALSE);
}
/**
* Test if enabled message is properly shown.
*/
public function testBuildFormEnabledMessage() {
$this->setDefaultConfig();
$this->mockConfig->get('smtp_on')->willReturn(TRUE);
$formBuilder = SMTPConfigForm::create($this->mockContainer->reveal());
$form = [];
$formBuilder->buildForm($form, new FormState());
$this->mockMessenger->addMessage(Argument::which('getUntranslatedString', 'SMTP module is active.'))->shouldHaveBeenCalled();
}
/**
* Test if enabled message is properly shown.
*/
public function testBuildFormDisabledMessage() {
$this->setDefaultConfig();
$this->mockConfig->get('smtp_on')->willReturn(FALSE);
$formBuilder = SMTPConfigForm::create($this->mockContainer->reveal());
$form = [];
$formBuilder->buildForm($form, new FormState());
$this->mockMessenger->addMessage(Argument::which('getUntranslatedString', 'SMTP module is INACTIVE.'))->shouldHaveBeenCalled();
}
/**
* Test form id.
*/
public function testGetFormId() {
$formBuilder = SMTPConfigForm::create($this->mockContainer->reveal());
$form_id = $formBuilder->getFormId();
$this->assertEquals('smtp_admin_settings', $form_id);
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment