Commit 0628b7df by Manzar Hussain

php mailer

parent 56fcf5f9
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.
INTRODUCTION
------------
Uses the PHPMailer library to send emails via SMTP.
For a full description of the module, visit the project page:
http://drupal.org/project/phpmailer_smtp
To submit bug reports and feature suggestions, or to track changes:
http://drupal.org/project/issues/phpmailer_smtp
REQUIREMENTS
------------
* Access to an SMTP server
* The Mail System module. This allows you specify different backends for
formatting and sending e-mails
http://www.drupal.org/project/mailsystem
* PHPMailer library 6 - installed via composer
Optional:
* To connect to an SMTP server using SSL/TLS, your PHP installation needs to
have SSL support.
* Mime Mail module to format HTML emails
http://www.drupal.org/project/mimemail
* Swift Mailer module to format HTML emails
https://www.drupal.org/project/swiftmailer
INSTALLATION
------------
composer require drupal/phpmailer_smtp
CONFIGURATION
-------------
* Configure user permissions at Administer >> User management >> Access
control >> PHPMailer SMTP module.
Only users with the "administer phpmailer smtp settings" permission are
allowed to access the module configuration page.
* Configure your SMTP server settings at Administer >> Configuration >>
PHPMailer SMTP.
* Configure your Mail System settings at Administer >> Configuration >>
Mail System.
Select "PHPMailer SMTP" as "Sender" under "Default Mail System" and "Module-
Specific Configuration" as required.
EXAMPLES
--------
Port 465 is now encouraged: https://tools.ietf.org/html/rfc8314
* Using Google Mail or Google Apps as SMTP server
To send e-mails with Google Mail use the following settings:
SMTP server: smtp.gmail.com
SMTP port: 465
Secure protocol: SSL
Username: your_google_mail_name@gmail.com
or: your_username@your_google_apps_domain.com
Password: your_google_mail_password
In Advanced SMTP settings:
Enable 'Always set "Reply-To" address' checkbox.
Also note the sending limits for Google Mail accounts:
http://mail.google.com/support/bin/answer.py?hl=en&answer=22839
General instructions for Google Mail accounts:
http://mail.google.com/support/bin/answer.py?answer=13287
* Errors when trying to send a test email
If you see the following error messages when trying to send a test email from
the settings page:
SMTP -> ERROR: Failed to connect to server: Connection timed out (110)
SMTP Error: Could not connect to SMTP host.
it means the mail server can not be reached, usually because your hosting
provider is blocking the port by a firewall. The solution is to ask your
provider to allow outgoing connections to your mail server.
* Debug settings
PHPMailer SMTP supports rerouting all e-mails for debugging purposes, to
prevent you from accidentally sending out e-mails to real users from a
development site. To enable this feature, add the following lines to the end
of your settings.php (usually located in sites/default):
$conf['system.maintenance']['phpmailer_smtp_debug_email']
= 'your_debug_email@yoursite.com';
This will change the recipient of all e-mails to the configured address.
{
"name": "drupal/phpmailer_smtp",
"type": "drupal-module",
"description": "Uses the PHPMailer library to send emails via SMTP.",
"homepage": "https://drupal.org/project/phpmailer_smtp",
"license": "GPL-2.0+",
"require": {
"phpmailer/phpmailer": "^6.1.8"
},
"authors": [
{
"name": "Ian McLean (imclean)",
"homepage": "http://drupal.org/u/imclean"
}
],
"support": {
"issues": "https://www.drupal.org/project/issues/phpmailer_smtp",
"source": "https://git.drupalcode.org/project/phpmailer_smtp"
},
"keywords": ["drupal", "phpmailer", "smtp", "email", "mail", "mailsystem", "mail system"]
}
smtp_host: 'localhost'
smtp_hostbackup: ''
smtp_port: 25
smtp_protocol: ''
smtp_username: ''
smtp_password: ''
smtp_hide_password: 0
smtp_fromname: ''
smtp_always_replyto: 0
smtp_keepalive: 0
smtp_debug: 0
smtp_debug_log: 0
phpmailer_smtp_test: ''
smtp_ssl_verify_peer: 1
smtp_ssl_verify_peer_name: 1
smtp_ssl_allow_self_signed: 0
smtp_envelope_sender_option: 'default'
smtp_envelope_sender: ''
smtp_ehlo_host: ''
smtp_timeout: 30
phpmailer_smtp.settings:
type: config_object
label: 'PHPMailer SMTP Settings'
mapping:
smtp_host:
type: string
label: 'SMTP host'
smtp_hostbackup:
type: string
label: 'SMTP host backup'
smtp_port:
type: integer
label: 'SMTP port'
smtp_protocol:
type: string
label: 'SMTP protocol'
smtp_username:
type: string
label: 'SMTP username'
smtp_password:
type: string
label: 'SMTP password'
smtp_hide_password:
type: boolean
label: 'Hide password'
smtp_fromname:
type: string
label: 'From name'
smtp_always_replyto:
type: boolean
label: 'Always set Reply-To'
smtp_keepalive:
type: boolean
label: 'Keep alive'
smtp_debug:
type: integer
label: 'Debug level'
smtp_debug_log:
type: boolean
label: 'Debug log'
phpmailer_smtp_test:
type: string
label: 'SMTP test address'
smtp_ssl_verify_peer:
type: boolean
label: 'Verify peer'
smtp_ssl_verify_peer_name:
type: boolean
label: 'Verify peer name'
smtp_ssl_allow_self_signed:
type: boolean
label: 'Allow self-sigend'
smtp_envelope_sender_option:
type: string
label: 'Envelope sender option'
smtp_envelope_sender:
type: email
label: 'Envelope sender'
smtp_ehlo_host:
type: string
label: 'EHLO host'
smtp_timeout:
type: integer
label: 'SMTP timeout'
{
"require": {
"phpmailer/phpmailer": {
"version": "v6.1.8",
"url": "https://github.com/PHPMailer/PHPMailer/archive/v6.1.8.zip"
}
}
}
name: PHPMailer SMTP
description: Uses the PHPMailer library to send emails via SMTP.
type: module
package: Mail
configure: phpmailer_smtp.settings
core_version_requirement: ^8.8 || ^9
# Information added by Drupal.org packaging script on 2020-11-23
version: '2.0.2'
project: 'phpmailer_smtp'
datestamp: 1606107103
<?php
/**
* @file
* PHPMailer SMTP installation functions.
*/
use PHPMailer\PHPMailer\PHPMailer;
/**
* Implements hook_requirements().
*/
function phpmailer_smtp_requirements($phase) {
$requirements = [];
if (class_exists('PHPMailer\PHPMailer\PHPMailer')) {
$mail = new PHPMailer();
}
if (empty($mail)) {
$requirements['phpmailer_smtp'] = [
'title' => (string) t('PHPMailer library'),
'value' => (string) t('Missing'),
'severity' => REQUIREMENT_ERROR,
'description' => (string) t("Please install the PHPMailer library by executing 'composer update' in your site's root directory."),
];
}
else {
$required_version = '6.1.8';
$installed_version = $mail::VERSION;
$requirements['phpmailer_smtp'] = [
'title' => (string) t('PHPMailer library'),
'value' => $installed_version,
];
if (!version_compare($installed_version, $required_version, '>=')) {
$requirements['phpmailer_smtp']['severity'] = REQUIREMENT_ERROR;
$requirements['phpmailer_smtp']['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,
]);
}
else {
$requirements['phpmailer_smtp']['severity'] = REQUIREMENT_OK;
}
}
return $requirements;
}
/**
* Add SMTP timeout setting.
*/
function phpmailer_smtp_update_8001() {
\Drupal::configFactory()->getEditable('phpmailer_smtp.settings')
->set('smtp_timeout', 30)
->save(TRUE);
}
phpmailer_smtp.settings:
title: 'PHPMailer SMTP'
route_name: phpmailer_smtp.settings
parent: system.admin_config_system
description: "Configure the PHPMailer SMTP module."
<?php
/**
* @file
* Uses the PHPMailer library to send emails via SMTP.
*/
use Drupal\Component\Utility\Html;
use Drupal\Core\Routing\RouteMatchInterface;
/**
* Implements hook_help().
*/
function phpmailer_smtp_help($route_name, RouteMatchInterface $route_match) {
switch ($route_name) {
case 'help.page.phpmailer_smtp':
$text = file_get_contents(__DIR__ . '/README.txt');
return '<pre>' . Html::escape($text) . '</pre>';
default:
}
}
administer phpmailer smtp settings:
title: 'Administer PHPMailer SMTP settings'
restrict access: TRUE
phpmailer_smtp.settings:
path: '/admin/config/system/phpmailer-smtp'
defaults:
_form: '\Drupal\phpmailer_smtp\Form\SettingsForm'
_title: 'Configure the PHPMailer SMTP module'
requirements:
_permission: 'administer phpmailer smtp settings'
<?php
namespace Drupal\phpmailer_smtp\Form;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Link;
use Drupal\Core\Mail\MailManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Defines a form to configure PHPMailer SMTP settings.
*/
class SettingsForm extends ConfigFormBase {
/**
* The mail manager.
*
* @var \Drupal\Core\Mail\MailManagerInterface
*/
protected $mailManager;
/**
* The language manager.
*
* @var \Drupal\Core\Language\LanguageManagerInterface
*/
protected $languageManager;
/**
* The module handler.
*
* @var \Drupal\Core\Extension\ModuleHandlerInterface
*/
protected $moduleHandler;
/**
* Constructor.
*
* @param \Drupal\Core\Mail\MailManagerInterface $mail_manager
* The mail manager.
* @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
* The language manager.
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
* The module handler.
*/
public function __construct(MailManagerInterface $mail_manager, LanguageManagerInterface $language_manager, ModuleHandlerInterface $module_handler) {
$this->mailManager = $mail_manager;
$this->languageManager = $language_manager;
$this->moduleHandler = $module_handler;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('plugin.manager.mail'),
$container->get('language_manager'),
$container->get('module_handler')
);
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'phpmailer_smtp_settings';
}
/**
* {@inheritdoc}
*/
protected function getEditableConfigNames() {
return ['phpmailer_smtp.settings'];
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
// Get immutable config.
$config = $this->configFactory()->get('phpmailer_smtp.settings');
$form['server']['smtp_host'] = [
'#type' => 'textfield',
'#title' => $this->t('Primary SMTP server'),
'#default_value' => $config->get('smtp_host'),
'#description' => $this->t('The host name or IP address of your primary SMTP server.'),
'#required' => TRUE,
];
$form['server']['smtp_hostbackup'] = [
'#type' => 'textfield',
'#title' => $this->t('Backup SMTP server'),
'#default_value' => $config->get('smtp_hostbackup'),
'#description' => $this->t('Optional host name or IP address of a backup server, if the primary server fails. You may override the default port below by appending it to the host name separated by a colon. Example: %hostname', ['%hostname' => 'localhost:587']),
];
$form['server']['smtp_port'] = [
'#type' => 'number',
'#title' => $this->t('SMTP port'),
'#size' => 5,
'#maxlength' => 5,
'#default_value' => $config->get('smtp_port'),
'#description' => $this->t('The standard SMTP port is 25. Secure connections (including Google Mail), typically use 465.'),
'#required' => TRUE,
];
$form['server']['smtp_protocol'] = [
'#type' => 'select',
'#title' => $this->t('Use secure protocol'),
'#default_value' => $config->get('smtp_protocol'),
'#options' => [
'' => $this->t('No'),
'ssl' => $this->t('SSL'),
'tls' => $this->t('TLS'),
],
'#description' => $this->t('Whether to use an encrypted connection to communicate with the SMTP server.'),
];
if (!function_exists('openssl_open')) {
$form['server']['smtp_protocol']['#default_value'] = '';
$form['server']['smtp_protocol']['#disabled'] = TRUE;
$form['server']['smtp_protocol']['#description'] .= ' ' . $this->t('Note: This option has been disabled since your PHP installation does not seem to have support for OpenSSL.');
$config->set('smtp_protocol', '')->save();
}
$form['auth'] = [
'#type' => 'details',
'#title' => $this->t('SMTP authentication'),
'#description' => $this->t('Leave both fields empty, if your SMTP server does not require authentication.'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
];
$form['auth']['smtp_username'] = [
'#type' => 'textfield',
'#title' => $this->t('Username'),
'#default_value' => $config->get('smtp_username'),
];
if (!$config->get('smtp_hide_password')) {
$form['auth']['smtp_password'] = [
'#type' => 'textfield',
'#title' => $this->t('Password'),
'#default_value' => $config->get('smtp_password'),
];
$form['auth']['smtp_hide_password'] = [
'#type' => 'checkbox',
'#title' => $this->t('Hide password'),
'#default_value' => 0,
'#description' => $this->t("Check this option to permanently hide the plain text password. You may still change the password afterwards, but it won't be displayed anymore."),
];
}
else {
$have_password = ($config->get('smtp_password') != '');
$form['auth']['smtp_password'] = [
'#type' => 'password',
'#title' => $have_password ? $this->t('Change password') : $this->t('Password'),
'#description' => $have_password ? $this->t('Leave empty if you do not intend to change the current password.') : '',
];
}
$form['auth']['smtp_delete_password'] = [
'#type' => 'checkbox',
'#title' => $this->t('Delete password'),
'#default_value' => 0,
'#description' => $this->t("Check this option to delete the current password."),
];
$form['advanced'] = [
'#type' => 'details',
'#title' => $this->t('Advanced SMTP settings'),
];
$form['advanced']['smtp_fromname'] = [
'#type' => 'textfield',
'#title' => $this->t('"From" name'),
'#default_value' => $config->get('smtp_fromname'),
'#description' => $this->t('Enter a name that should appear as the sender for all messages. If left blank the site name will be used instead: %sitename.', ['%sitename' => $this->config('system.site')->get('name')]),
];
$form['advanced']['smtp_ehlo_host'] = [
'#type' => 'textfield',
'#title' => $this->t('HELO/EHLO Hostname'),
'#default_value' => $config->get('smtp_ehlo_host'),
'#description' => $this->t('The hostname to use as the default HELO/EHLO string and Message-ID header. Leave blank to let PHPMailer determine it.'),
];
$form['advanced']['smtp_always_replyto'] = [
'#type' => 'checkbox',
'#title' => $this->t('Always set "Reply-To" address'),
'#default_value' => $config->get('smtp_always_replyto'),
'#description' => $this->t('Enables setting the "Reply-To" address to the original sender of the message, if unset. This is required when using Google Mail, which would otherwise overwrite the original sender.'),
];
$form['advanced']['smtp_keepalive'] = [
'#type' => 'checkbox',
'#title' => $this->t('Keep connection alive'),
'#default_value' => $config->get('smtp_keepalive'),
'#description' => $this->t('Whether to reuse an existing connection during a request. Improves performance when sending a lot of e-mails at once.'),
];
$form['advanced']['smtp_debug'] = [
'#type' => 'select',
'#title' => $this->t('Debug level'),
'#default_value' => $config->get('smtp_debug'),
'#options' => [
0 => $this->t('Disabled'),
1 => $this->t('Errors only'),
2 => $this->t('Server responses'),
4 => $this->t('Full communication'),
],
'#description' => $this->t("Debug the communication with the SMTP server. You normally shouldn't enable this unless you're trying to debug e-mail sending problems."),
];
$form['advanced']['smtp_debug_log'] = [
'#type' => 'checkbox',
'#title' => $this->t("Record debugging output in Drupal's log"),
'#default_value' => $config->get('smtp_debug_log'),
'#description' => $this->t("If this is checked, the debugging out put that is produced will also be recorded in Drupal's database log."),
'#states' => [
'visible' => [
':input[name=smtp_debug]' => ['!value' => 0],
],
],
];
$form['advanced']['smtp_timeout'] = [
'#type' => 'number',
'#step' => 1,
'#title' => $this->t('SMTP timeout'),
'#default_value' => $config->get('smtp_timeout'),
'#description' => $this->t('The number of seconds to wait for a response from the SMTP server.'),
];
$form['advanced']['ssl_settings'] = [
'#type' => 'fieldset',
'#title' => $this->t('Advanced SSL settings'),
'#description' => $this->t('If you are attempting to connect to a broken or malconfigured secure mail server, you can try toggling one or more of these options. <strong>If changing any of these options allows connection to the server, you should consider either fixing the SSL certifcate, or using a different SMTP server, as the connection may be insecure.</strong>'),
];
$ssl_verify_peer = $config->get('smtp_ssl_verify_peer');
$form['advanced']['ssl_settings']['smtp_ssl_verify_peer'] = [
'#type' => 'checkbox',
'#title' => $this->t('Verfy peer'),
'#default_value' => isset($ssl_verify_peer) ? $ssl_verify_peer : 1,
'#description' => $this->t('If this is checked, it will require verification of the SSL certificate being used on the mail server.'),
];
$ssl_verify_peer_name = $config->get('smtp_ssl_verify_peer_name');
$form['advanced']['ssl_settings']['smtp_ssl_verify_peer_name'] = [
'#type' => 'checkbox',
'#title' => $this->t('Verfy peer name'),
'#default_value' => isset($ssl_verify_peer_name) ? $ssl_verify_peer_name : 1,
'#description' => $this->t("If this is checked, it will require verification of the mail server's name in the SSL certificate."),
];
$ssl_allow_self_signed = $config->get('smtp_ssl_allow_self_signed');
$form['advanced']['ssl_settings']['smtp_ssl_allow_self_signed'] = [
'#type' => 'checkbox',
'#title' => $this->t('Allow self signed'),
'#default_value' => isset($ssl_allow_self_signed) ? $ssl_allow_self_signed : 0,
'#description' => $this->t('If this is checked, it will allow conecting to a mail server with a self-signed SSL certificate. (This requires "Verfy peer" to be enabled.)'),
'#states' => [
'enabled' => [
':input[name="ssl_verify_peer"]' => ['checked' => TRUE],
],
],
];
$form['advanced']['envelope_sender_settings'] = [
'#type' => 'fieldset',
'#title' => $this->t('Envelope Sender Settings'),
'#description' => $this->t('Specify what should be used in the SMTP <em>MAIL FROM:</em> command. Usually this will be <em>Default</em>'),
];
$form['advanced']['envelope_sender_settings']['smtp_envelope_sender_option'] = [
'#type' => 'select',
'#title' => $this->t('Envelope sender'),
'#default_value' => $config->get('smtp_envelope_sender_option'),
'#options' => [
'default' => $this->t('Default'),
'site_mail' => $this->t('Site mail'),
'from_address' => $this->t('From header'),
'other' => $this->t('Other..'),
],
];
$form['advanced']['envelope_sender_settings']['smtp_envelope_sender'] = [
'#type' => 'email',
'#title' => $this->t('Envelope sender address'),
'#default_value' => $config->get('smtp_envelope_sender'),
'#description' => $this->t('Type in an address to use as the envelope sender.'),
'#states' => [
'visible' => [
':input[name="smtp_envelope_sender_option"]' => ['value' => 'other'],
],
],
];
$form['test'] = [
'#type' => 'details',
'#title' => $this->t('Test configuration'),
];
$form['test']['phpmailer_smtp_test'] = [
'#type' => 'email',
'#title' => $this->t('Recipient'),
'#default_value' => '',
'#description' => $this->t('Type in an address to have a test e-mail sent there.'),
];
return parent::buildForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
if (intval($form_state->getValue('smtp_port') == 0)) {
$form_state->setErrorByName('smtp_port', $this->t('You must enter a valid SMTP port number.'));
}
parent::validateForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$values = $form_state->getValues();
// Save the configuration changes.
$phpmailer_smtp_config = $this->config('phpmailer_smtp.settings');
$phpmailer_smtp_config->set('smtp_host', $values['smtp_host'])
->set('smtp_hostbackup', $values['smtp_hostbackup'])
->set('smtp_port', $values['smtp_port'])
->set('smtp_protocol', $values['smtp_protocol'])
->set('smtp_ssl_verify_peer', $values['smtp_ssl_verify_peer'])
->set('smtp_ssl_verify_peer_name', $values['smtp_ssl_verify_peer_name'])
->set('smtp_ssl_allow_self_signed', $values['smtp_ssl_allow_self_signed'])
->set('smtp_username', $values['smtp_username'])
->set('smtp_fromname', $values['smtp_fromname'])
->set('smtp_ehlo_host', $values['smtp_ehlo_host'])
->set('smtp_always_replyto', $values['smtp_always_replyto'])
->set('smtp_keepalive', $values['smtp_keepalive'])
->set('smtp_debug', $values['smtp_debug'])
->set('smtp_debug_log', $values['smtp_debug_log'])
->set('smtp_timeout', $values['smtp_timeout'])
->set('smtp_envelope_sender_option', $values['smtp_envelope_sender_option'])
->set('smtp_envelope_sender', $values['smtp_envelope_sender']);
// Only save option if it is present.
if (!empty($values['smtp_hide_password'])) {
$phpmailer_smtp_config->set('smtp_hide_password', $values['smtp_hide_password']);
}
// Only save the password if it is not empty.
if (!empty($values['smtp_password'])) {
$phpmailer_smtp_config->set('smtp_password', $values['smtp_password']);
}
// Check option to delete the password.
if (!empty($values['smtp_delete_password'])) {
$phpmailer_smtp_config->set('smtp_password', '');
}
$phpmailer_smtp_config->save();
// Send a test email message, if an email address was entered.
if ($values['phpmailer_smtp_test']) {
$this->sendTestEmail($values);
}
parent::submitForm($form, $form_state);
}
/**
* Sends a test email.
*
* @param array $values
* Array of form values.
*/
private function sendTestEmail(array $values) {
// Since this is being sent to an email address that may not necessarily
// be tied to a user account, use the site's default language.
$langcode = $this->languageManager->getDefaultLanguage()->getId();
// Prepare the message without sending.
$message = $this->mailManager->mail('phpmailer_smtp', 'test', $values['phpmailer_smtp_test'], $langcode, [], NULL, FALSE);
$message['subject'] = (string) $this->t('PHPMailer SMTP test email');
$message['body'] = (string) $this->t('Your site is properly configured to send emails using the PHPMailer library.');
// Send the message using PHPMailer SMTP.
$phpMailerSmtp = $this->mailManager->createInstance('phpmailer_smtp');
$phpMailerSmtp->mail($message);
// Some users may not have the dblog module enabled.
if ($this->moduleHandler->moduleExists('dblog')) {
$watchdog_url = Link::createFromRoute($this->t('Check the logs'), 'dblog.overview');
$this->messenger()->addMessage($this->t('A test e-mail has been sent to %email. @watchdog-url for any error messages.', [
'%email' => $values['phpmailer_smtp_test'],
'@watchdog-url' => $watchdog_url->toString(),
]));
}
else {
$this->messenger()->addMessage($this->t('A test e-mail has been sent to %email.', [
'%email' => $values['phpmailer_smtp_test'],
]));
}
}
}
<?php
namespace Drupal\phpmailer_smtp\Plugin\Mail;
use Drupal\Component\Utility\Html;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Mail\MailFormatHelper;
use Drupal\Core\Mail\MailInterface;
use Drupal\Core\Render\Markup;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Implements the base PHPMailer SMTP class for the Drupal MailInterface.
*
* Base PHPMailer for Drupal implementation with support for SMTP keep-alive.
*
* @Mail(
* id = "phpmailer_smtp",
* label = @Translation("PHPMailer SMTP"),
* description = @Translation("Sends emails via SMTP using the PHPMailer library.")
* )
*/
class PhpMailerSmtp extends PHPMailer implements MailInterface, ContainerFactoryPluginInterface {
use StringTranslationTrait;
/**
* Config factory.
*
* @var \Drupal\Core\Config\ConfigFactoryInterface
*/
protected $configFactory;
/**
* PHPMailer SMTP Config.
*
* @var \Drupal\Core\Config\ImmutableConfig
*/
protected $config;
/**
* Whether to allow sending messages with an empty body.
*
* @var bool
*/
public $AllowEmpty = TRUE;
/**
* Verbose debug output level configured for Drupal.
*
* @var int
*
* In order to be able to log error messages with actual error information and
* see what actually went wrong for a particular message, PHPMailer::SMTPDebug
* always needs to be enabled.
*
* PhpMailerSmtp::SmtpSend() overrides PHPMailer::SmtpSend() to capture the
* debug output string and make it available for \Drupal::logger() calls.
*
* @see PHPMailer::SMTPDebug
* @see SMTP::do_debug
* @see PhpMailerSmtp::SmtpSend()
* @see PhpMailerSmtp::drupalDebugOutput
*/
public $drupalDebug = 0;
/**
* Overrides PHPMailer::SMTPDebug.
*
* @var int
*
* Capture SMTP communication errors by default.
*/
public $SMTPDebug = 2;
/**
* Stores the verbose debug output of the SMTP communication.
*
* @var string
*/
public $drupalDebugOutput = '';
/**
* Logger channel factory.
*
* @var \Drupal\Core\Logger\LoggerChannelFactoryInterface
*/
protected $loggerFactory;
/**
* The messenger.
*
* @var \Drupal\Core\Messenger\MessengerInterface
*/
protected $messenger;
/**
* 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(
$container->get('config.factory'),
$container->get('logger.factory'),
$container->get('messenger')
);
}
/**
* Constructor.
*/
public function __construct(ConfigFactoryInterface $config, LoggerChannelFactoryInterface $logger_factory, MessengerInterface $messenger) {
// Throw exceptions instead of dying (since 5.0.0).
if (method_exists(get_parent_class($this), '__construct')) {
parent::__construct(TRUE);
}
$this->configFactory = $config;
$this->config = $config->get('phpmailer_smtp.settings');
$this->loggerFactory = $logger_factory;
$this->messenger = $messenger;
$this->IsSMTP();
$this->Reset();
$this->SMTPAutoTLS = FALSE;
$this->Host = $this->config->get('smtp_host', '');
if ($backup = $this->config->get('smtp_hostbackup', '')) {
$this->Host .= ';' . $backup;
}
$this->Port = $this->config->get('smtp_port', '25');
$smtp_protocol = $this->config->get('smtp_protocol', '');
$this->SMTPSecure = $smtp_protocol;
if (!empty($smtp_protocol)) {
$ssl_verify_peer = $this->config->get('smtp_ssl_verify_peer');
$this->SMTPOptions['ssl']['verify_peer'] = isset($ssl_verify_peer) ? $ssl_verify_peer : 1;
$ssl_verify_peer_name = $this->config->get('smtp_ssl_verify_peer_name');
$this->SMTPOptions['ssl']['verify_peer_name'] = isset($ssl_verify_peer_name) ? $ssl_verify_peer_name : 1;
$ssl_allow_self_signed = $this->config->get('smtp_ssl_allow_self_signed');
$this->SMTPOptions['ssl']['allow_self_signed'] = isset($ssl_allow_self_signed) ? $ssl_allow_self_signed : 0;
}
// Use SMTP authentication if both username and password are given.
$this->Username = $this->config->get('smtp_username', '');
$this->Password = $this->config->get('smtp_password', '');
$this->SMTPAuth = (bool) ($this->Username != '' && $this->Password != '');
$this->SMTPKeepAlive = $this->config->get('smtp_keepalive', 0);
$this->Timeout = $this->config->get('smtp_timeout', 30);
$this->drupalDebug = $this->config->get('smtp_debug', 0);
if ($this->drupalDebug > $this->SMTPDebug && \Drupal::currentUser()->hasPermission('administer phpmailer smtp settings')) {
$this->SMTPDebug = $this->drupalDebug;
}
}
/**
* Send mail via SMTP.
*
* Wrapper around PHPMailer::SmtpSend() with exception handling.
*/
public function smtpSend($header, $body) {
if ($this->SMTPDebug) {
// Clear possibly previously captured debug output.
$this->drupalDebugOutput = '';
ob_start();
}
try {
$result = parent::SmtpSend($header, $body);
// Close connection when not using SMTP keep-alive.
if (!$this->SMTPKeepAlive) {
$this->SmtpClose();
}
}
catch (Exception $exception) {
}
if ($this->SMTPDebug) {
if ($this->drupalDebug && ($this->drupalDebugOutput = ob_get_contents())) {
$this->messenger->addMessage(Markup::create($this->drupalDebugOutput));
if ($this->config->get('smtp_debug_log', 0)) {
$this->loggerFactory->get('phpmailer_smtp')->debug('Output of communication with SMTP server:<br /><pre>{output}</pre>', [
'output' => str_replace("<br>\n", "\n", Html::decodeEntities($this->drupalDebugOutput)),
]);
}
}
ob_end_clean();
}
// Reinitialize properties.
$this->reset();
if (isset($exception)) {
// Pass exception to caller.
throw $exception;
}
return $result;
}
/**
* Re-initialize properties after sending mail.
*/
public function reset() {
$this->clearAllRecipients();
$this->clearReplyTos();
$this->clearAttachments();
$this->clearCustomHeaders();
$this->Priority = 3;
$this->CharSet = 'utf-8';
$this->ContentType = 'text/plain';
$this->Encoding = '8bit';
// Set default From name.
$from_name = $this->config->get('smtp_fromname');
if ($from_name == '') {
// Fall back on the site name.
$from_name = $this->configFactory->get('system.site')->get('name');
}
$this->FromName = $from_name;
$this->Sender = '';
$this->MessageID = '';
}
/**
* Overrides PHPMailer::__destruct().
*/
public function __destruct() {
// Disable debug output if SMTP keep-alive is enabled.
// PHP is most likely shutting down altogether (this class is instantiated
// as a static singleton). Since logging facilities (e.g., database
// connection) quite potentially have been shut down already, simply turn
// off SMTP debugging. Without this override, debug output would be printed
// on the screen and CLI output.
if ($this->SMTPKeepAlive && isset($this->smtp->do_debug)) {
$this->smtp->do_debug = 0;
}
parent::__destruct();
}
/**
* Provide more user-friendly error messages.
*
* Note: messages should not end with a dot.
*/
public function setLanguage($langcode = 'en', $lang_path = 'language/') {
// Retrieve English defaults to ensure all message keys are set.
parent::SetLanguage('en');
// Overload with Drupal translations.
$this->language = [
'authenticate' => $this->t('SMTP error: Could not authenticate.'),
'connect_host' => $this->t('SMTP error: Could not connect to host.'),
'data_not_accepted' => $this->t('SMTP error: Data not accepted.'),
'smtp_connect_failed' => $this->t('SMTP error: Could not connect to SMTP host.'),
'smtp_error' => $this->t('SMTP server error:'),
// Messages used during email generation.
'empty_message' => $this->t('Message body empty'),
'encoding' => $this->t('Unknown encoding:'),
'variable_set' => $this->t('Cannot set or reset variable:'),
'file_access' => $this->t('File error: Could not access file:'),
'file_open' => $this->t('File error: Could not open file:'),
// Non-administrative messages.
'from_failed' => $this->t('The following From address failed:'),
'invalid_address' => $this->t('Invalid address'),
'provide_address' => $this->t('You must provide at least one recipient e-mail address.'),
'recipients_failed' => $this->t('The following recipients failed:'),
] + $this->language;
return TRUE;
}
/**
* Wrap PHPMailer::RFCDate() to return the current timezone.
*/
public static function rfcDate() {
$tz = date('Z');
$tzs = ($tz < 0) ? '-' : '+';
$tz = abs($tz);
$tz = (int) ($tz / 3600) * 100 + ($tz % 3600) / 60;
$result = sprintf("%s %s%04d", date('D, j M Y H:i:s'), $tzs, $tz);
return $result;
}
/**
* Concatenates and wraps the e-mail body for plain-text mails.
*
* @param array $message
* A message array, as described in hook_mail_alter().
*
* @return array
* The formatted $message.
*/
public function format(array $message) {
// Join the body array into one string.
$message['body'] = implode("\n\n", $message['body']);
// 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;
}
/**
* Sends an e-mail message composed by drupal_mail().
*
* @param array $message
* A message array, as described in hook_mail_alter().
*
* @return bool
* TRUE if the mail was successfully accepted, otherwise FALSE.
*
* @see PHPMailer::Send()
*/
public function mail(array $message) {
try {
// Convert headers to lowercase.
$headers = array_change_key_case($message['headers']);
unset($message['headers']);
// Parse 'From' address.
$from = $this->parseAddresses($headers['from']);
$from = reset($from);
$this->From = $from['address'];
if ($from['name'] != '') {
$this->FromName = $from['name'];
}
unset($headers['from']);
// @todo This \still\ might not be the correct way to do this.
$phpmailer_smtp_debug_email = $this->configFactory->get('system.maintenance')->get('phpmailer_smtp_debug_email');
if (empty($phpmailer_smtp_debug_email)) {
// Set recipients.
foreach ($this->parseAddresses($message['to']) as $address) {
$this->AddAddress($address['address'], $address['name']);
}
// Extract CCs and BCCs from headers.
if (!empty($headers['cc'])) {
foreach ($this->parseAddresses($headers['cc']) as $address) {
$this->AddCC($address['address'], $address['name']);
}
}
if (!empty($headers['bcc'])) {
foreach ($this->parseAddresses($headers['bcc']) as $address) {
$this->AddBCC($address['address'], $address['name']);
}
}
}
else {
// Reroute to debug e-mail address.
// @todo This might not be the correct way to do this.
$this->AddAddress($phpmailer_smtp_debug_email);
}
unset($headers['cc'], $headers['bcc']);
// Extract Reply-To from headers.
if (isset($headers['reply-to'])) {
foreach ($this->parseAddresses($headers['reply-to']) as $address) {
$this->AddReplyTo($address['address'], $address['name']);
}
unset($headers['reply-to']);
}
// @todo This might not be the correct way to do this.
elseif ($this->config->get('smtp_always_replyto')) {
// If no Reply-To header has been explicitly set, use the From address
// to be able to respond to e-mails sent via Google Mail.
$this->AddReplyTo($from['address'], $from['name']);
}
// Extract Content-Type and charset.
if (isset($headers['content-type'])) {
$content_type = explode(';', $headers['content-type']);
$this->ContentType = trim(array_shift($content_type));
foreach ($content_type as $param) {
$param = explode('=', $param, 2);
$key = trim($param[0]);
if ($key == 'charset') {
$this->CharSet = trim($param[1]);
}
else {
$this->ContentType .= '; ' . $key . '=' . trim($param[1]);
}
}
unset($headers['content-type']);
}
// Set additional properties.
$properties = [
'x-priority' => 'Priority',
'content-transfer-encoding' => 'Encoding',
'message-id' => 'MessageID',
];
foreach ($properties as $source => $property) {
if (isset($headers[$source])) {
$this->$property = $headers[$source];
unset($headers[$source]);
}
}
// Return-Path should not be set by Drupal.
if (isset($headers['return-path'])) {
unset($headers['return-path']);
}
// X-Mailer is set by PHPMailer which is the mailer.
if (isset($headers['x-mailer'])) {
unset($headers['x-mailer']);
}
// Set default sender address.
$envelopeSender = $this->parseAddresses($message['from']);
$envelopeSender = reset($envelopeSender);
$this->Sender = $envelopeSender['address'];
// Check envelope sender option.
$senderOption = $this->config->get('smtp_envelope_sender_option');
if ($senderOption === 'site_mail') {
$this->Sender = $this->configFactory->get('system.site')->get('mail');
}
if ($senderOption === 'from_address') {
$this->Sender = $from['address'];
}
if ($senderOption === 'other') {
$this->Sender = $this->config->get('smtp_envelope_sender');
}
if (!empty($this->config->get('smtp_ehlo_host'))) {
$this->Hostname = $this->config->get('smtp_ehlo_host');
}
// This one is always set by PHPMailer.
unset($headers['mime-version']);
// Add remaining header lines.
// Note: Any header lines MUST already be checked by the caller for
// unwanted newline characters to avoid header injection.
// @see PHPMailer::SecureHeader()
foreach ($headers as $key => $value) {
$this->AddCustomHeader($key, $value);
}
$this->Subject = $message['subject'];
$this->Body = $message['body'];
return $this->Send();
}
catch (Exception $e) {
// Log the error including verbose debug information.
// Since DBLog module is the most common case, we use HTML to format the
// message for visual inspection. For sites running with Syslog or other
// logging modules, we put the actual values on separate lines (\n), so
// the surrounding HTML markup doesn't get too disturbing.
// Message is a safe $this->t() string from PhpMailerSmtp::SetLanguage().
$output = $e->getMessage();
// Attempt to delimit summary from full message.
$output .= " \n";
$arguments = [];
// Append SMTP communication output.
if ($this->drupalDebugOutput) {
// PHPMailer debug output contains HTML linebreaks. PRE is more
// readable.
$output .= '<p><strong>Server response:</strong></p>';
$output .= "<pre>\n@smtp_output\n</pre>";
$arguments += [
'@smtp_output' => str_replace("<br>\n", "\n", Html::decodeEntities($this->drupalDebugOutput)),
];
}
// We need to log the message in order to be able to debug why the server
// responded with an error. The mail body may contain passwords and other
// sensitive information, which should not be logged. Since all kind of
// mails are processed and Drupal provides no way to mark sensible data,
// it is technically impossible prevent logging in all cases.
// Remove $params; they've already been processed and may contain sensible
// data.
unset($message['params']);
// Subject.
$output .= "<p><strong>Subject:</strong> \n@subject\n</p>";
$arguments += [
'@subject' => $message['subject'],
];
unset($message['subject']);
// Body.
$output .= '<p><strong>Body:</strong></p>';
$output .= "<pre>\n@body\n</pre>";
$arguments += [
'@body' => $message['body'],
];
unset($message['body']);
// Rest of $message.
$output .= '<p><strong>Message:</strong></p>';
$output .= "<pre>\n@message\n</pre>";
$arguments += [
'@message' => var_export($message, TRUE),
];
$this->loggerFactory->get('phpmailer_smtp')->error($output, $arguments);
return FALSE;
}
}
}
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