3 namespace Drupal\Core\Mail;
5 use Drupal\Component\Render\MarkupInterface;
6 use Drupal\Component\Render\PlainTextOutput;
7 use Drupal\Component\Utility\Html;
8 use Drupal\Component\Utility\Unicode;
9 use Drupal\Core\Logger\LoggerChannelFactoryInterface;
10 use Drupal\Core\Messenger\MessengerTrait;
11 use Drupal\Core\Plugin\DefaultPluginManager;
12 use Drupal\Core\Cache\CacheBackendInterface;
13 use Drupal\Core\Extension\ModuleHandlerInterface;
14 use Drupal\Core\Config\ConfigFactoryInterface;
15 use Drupal\Core\Render\Markup;
16 use Drupal\Core\Render\RenderContext;
17 use Drupal\Core\Render\RendererInterface;
18 use Drupal\Core\StringTranslation\StringTranslationTrait;
19 use Drupal\Core\StringTranslation\TranslationInterface;
22 * Provides a Mail plugin manager.
24 * @see \Drupal\Core\Annotation\Mail
25 * @see \Drupal\Core\Mail\MailInterface
28 class MailManager extends DefaultPluginManager implements MailManagerInterface {
31 use StringTranslationTrait;
36 * @var \Drupal\Core\Config\ConfigFactoryInterface
38 protected $configFactory;
43 * @var \Drupal\Core\Logger\LoggerChannelFactoryInterface
45 protected $loggerFactory;
50 * @var \Drupal\Core\Render\RendererInterface
55 * List of already instantiated mail plugins.
59 protected $instances = [];
62 * Constructs the MailManager object.
64 * @param \Traversable $namespaces
65 * An object that implements \Traversable which contains the root paths
66 * keyed by the corresponding namespace to look for plugin implementations.
67 * @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
68 * Cache backend instance to use.
69 * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
70 * The module handler to invoke the alter hook with.
71 * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
72 * The configuration factory.
73 * @param \Drupal\Core\Logger\LoggerChannelFactoryInterface $logger_factory
74 * The logger channel factory.
75 * @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
76 * The string translation service.
77 * @param \Drupal\Core\Render\RendererInterface $renderer
80 public function __construct(\Traversable $namespaces, CacheBackendInterface $cache_backend, ModuleHandlerInterface $module_handler, ConfigFactoryInterface $config_factory, LoggerChannelFactoryInterface $logger_factory, TranslationInterface $string_translation, RendererInterface $renderer) {
81 parent::__construct('Plugin/Mail', $namespaces, $module_handler, 'Drupal\Core\Mail\MailInterface', 'Drupal\Core\Annotation\Mail');
82 $this->alterInfo('mail_backend_info');
83 $this->setCacheBackend($cache_backend, 'mail_backend_plugins');
84 $this->configFactory = $config_factory;
85 $this->loggerFactory = $logger_factory;
86 $this->stringTranslation = $string_translation;
87 $this->renderer = $renderer;
91 * Overrides PluginManagerBase::getInstance().
93 * Returns an instance of the mail plugin to use for a given message ID.
95 * The selection of a particular implementation is controlled via the config
96 * 'system.mail.interface', which is a keyed array. The default
97 * implementation is the mail plugin whose ID is the value of 'default' key. A
98 * more specific match first to key and then to module will be used in
99 * preference to the default. To specify a different plugin for all mail sent
100 * by one module, set the plugin ID as the value for the key corresponding to
101 * the module name. To specify a plugin for a particular message sent by one
102 * module, set the plugin ID as the value for the array key that is the
103 * message ID, which is "${module}_${key}".
105 * For example to debug all mail sent by the user module by logging it to a
106 * file, you might set the variable as something like:
110 * 'default' => 'php_mail',
111 * 'user' => 'devel_mail_log',
115 * Finally, a different system can be specified for a specific message ID (see
116 * the $key param), such as one of the keys used by the contact module:
120 * 'default' => 'php_mail',
121 * 'user' => 'devel_mail_log',
122 * 'contact_page_autoreply' => 'null_mail',
126 * Other possible uses for system include a mail-sending plugin that actually
127 * sends (or duplicates) each message to SMS, Twitter, instant message, etc,
128 * or a plugin that queues up a large number of messages for more efficient
129 * bulk sending or for sending via a remote gateway so as to reduce the load
130 * on the local server.
132 * @param array $options
133 * An array with the following key/value pairs:
134 * - module: (string) The module name which was used by
135 * \Drupal\Core\Mail\MailManagerInterface->mail() to invoke hook_mail().
136 * - key: (string) A key to identify the email sent. The final message ID
137 * is a string represented as {$module}_{$key}.
139 * @return \Drupal\Core\Mail\MailInterface
140 * A mail plugin instance.
142 * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
144 public function getInstance(array $options) {
145 $module = $options['module'];
146 $key = $options['key'];
147 $message_id = $module . '_' . $key;
149 $configuration = $this->configFactory->get('system.mail')->get('interface');
151 // Look for overrides for the default mail plugin, starting from the most
152 // specific message_id, and falling back to the module name.
153 if (isset($configuration[$message_id])) {
154 $plugin_id = $configuration[$message_id];
156 elseif (isset($configuration[$module])) {
157 $plugin_id = $configuration[$module];
160 $plugin_id = $configuration['default'];
163 if (empty($this->instances[$plugin_id])) {
164 $this->instances[$plugin_id] = $this->createInstance($plugin_id);
166 return $this->instances[$plugin_id];
172 public function mail($module, $key, $to, $langcode, $params = [], $reply = NULL, $send = TRUE) {
173 // Mailing can invoke rendering (e.g., generating URLs, replacing tokens),
174 // but e-mails are not HTTP responses: they're not cached, they don't have
175 // attachments. Therefore we perform mailing inside its own render context,
176 // to ensure it doesn't leak into the render context for the HTTP response
177 // to the current request.
178 return $this->renderer->executeInRenderContext(new RenderContext(), function () use ($module, $key, $to, $langcode, $params, $reply, $send) {
179 return $this->doMail($module, $key, $to, $langcode, $params, $reply, $send);
184 * Composes and optionally sends an email message.
186 * @param string $module
187 * A module name to invoke hook_mail() on. The {$module}_mail() hook will be
188 * called to complete the $message structure which will already contain
191 * A key to identify the email sent. The final message ID for email altering
192 * will be {$module}_{$key}.
194 * The email address or addresses where the message will be sent to. The
195 * formatting of this string will be validated with the
196 * @link http://php.net/manual/filter.filters.validate.php PHP email validation filter. @endlink
199 * - user@example.com, anotheruser@example.com
200 * - User <user@example.com>
201 * - User <user@example.com>, Another User <anotheruser@example.com>
202 * @param string $langcode
203 * Language code to use to compose the email.
204 * @param array $params
205 * (optional) Parameters to build the email.
206 * @param string|null $reply
207 * Optional email address to be used to answer.
209 * If TRUE, call an implementation of
210 * \Drupal\Core\Mail\MailInterface->mail() to deliver the message, and
211 * store the result in $message['result']. Modules implementing
212 * hook_mail_alter() may cancel sending by setting $message['send'] to
216 * The $message array structure containing all details of the message. If
217 * already sent ($send = TRUE), then the 'result' element will contain the
218 * success indicator of the email, failure being already written to the
219 * watchdog. (Success means nothing more than the message being accepted at
220 * php-level, which still doesn't guarantee it to be delivered.)
222 * @see \Drupal\Core\Mail\MailManagerInterface::mail()
224 public function doMail($module, $key, $to, $langcode, $params = [], $reply = NULL, $send = TRUE) {
225 $site_config = $this->configFactory->get('system.site');
226 $site_mail = $site_config->get('mail');
227 if (empty($site_mail)) {
228 $site_mail = ini_get('sendmail_from');
231 // Bundle up the variables into a structured array for altering.
233 'id' => $module . '_' . $key,
237 'from' => $site_mail,
238 'reply-to' => $reply,
239 'langcode' => $langcode,
246 // Build the default headers.
248 'MIME-Version' => '1.0',
249 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
250 'Content-Transfer-Encoding' => '8Bit',
251 'X-Mailer' => 'Drupal',
253 // To prevent email from looking like spam, the addresses in the Sender and
254 // Return-Path headers should have a domain authorized to use the
255 // originating SMTP server.
256 $headers['Sender'] = $headers['Return-Path'] = $site_mail;
257 // Headers are usually encoded in the mail plugin that implements
258 // \Drupal\Core\Mail\MailInterface::mail(), for example,
259 // \Drupal\Core\Mail\Plugin\Mail\PhpMail::mail(). The site name must be
260 // encoded here to prevent mail plugins from encoding the email address,
261 // which would break the header.
262 $headers['From'] = Unicode::mimeHeaderEncode($site_config->get('name'), TRUE) . ' <' . $site_mail . '>';
264 $headers['Reply-to'] = $reply;
266 $message['headers'] = $headers;
268 // Build the email (get subject and body, allow additional headers) by
269 // invoking hook_mail() on this module. We cannot use
270 // moduleHandler()->invoke() as we need to have $message by reference in
272 if (function_exists($function = $module . '_mail')) {
273 $function($key, $message, $params);
276 // Invoke hook_mail_alter() to allow all modules to alter the resulting
278 $this->moduleHandler->alter('mail', $message);
280 // Retrieve the responsible implementation for this message.
281 $system = $this->getInstance(['module' => $module, 'key' => $key]);
283 // Attempt to convert relative URLs to absolute.
284 foreach ($message['body'] as &$body_part) {
285 if ($body_part instanceof MarkupInterface) {
286 $body_part = Markup::create(Html::transformRootRelativeUrlsToAbsolute((string) $body_part, \Drupal::request()->getSchemeAndHttpHost()));
290 // Format the message body.
291 $message = $system->format($message);
293 // Optionally send email.
295 // The original caller requested sending. Sending was canceled by one or
296 // more hook_mail_alter() implementations. We set 'result' to NULL,
297 // because FALSE indicates an error in sending.
298 if (empty($message['send'])) {
299 $message['result'] = NULL;
301 // Sending was originally requested and was not canceled.
303 // Ensure that subject is plain text. By default translated and
304 // formatted strings are prepared for the HTML context and email
305 // subjects are plain strings.
306 if ($message['subject']) {
307 $message['subject'] = PlainTextOutput::renderFromHtml($message['subject']);
309 $message['result'] = $system->mail($message);
311 if (!$message['result']) {
312 $this->loggerFactory->get('mail')
313 ->error('Error sending email (from %from to %to with reply-to %reply).', [
314 '%from' => $message['from'],
315 '%to' => $message['to'],
316 '%reply' => $message['reply-to'] ? $message['reply-to'] : $this->t('not set'),
318 $this->messenger()->addError($this->t('Unable to send email. Contact the site administrator if the problem persists.'));