3 namespace Drupal\Core\Mail;
5 use Drupal\Component\Render\PlainTextOutput;
6 use Drupal\Core\Logger\LoggerChannelFactoryInterface;
7 use Drupal\Core\Plugin\DefaultPluginManager;
8 use Drupal\Core\Cache\CacheBackendInterface;
9 use Drupal\Core\Extension\ModuleHandlerInterface;
10 use Drupal\Core\Config\ConfigFactoryInterface;
11 use Drupal\Core\Render\RenderContext;
12 use Drupal\Core\Render\RendererInterface;
13 use Drupal\Core\StringTranslation\StringTranslationTrait;
14 use Drupal\Core\StringTranslation\TranslationInterface;
17 * Provides a Mail plugin manager.
19 * @see \Drupal\Core\Annotation\Mail
20 * @see \Drupal\Core\Mail\MailInterface
23 class MailManager extends DefaultPluginManager implements MailManagerInterface {
25 use StringTranslationTrait;
30 * @var \Drupal\Core\Config\ConfigFactoryInterface
32 protected $configFactory;
37 * @var \Drupal\Core\Logger\LoggerChannelFactoryInterface
39 protected $loggerFactory;
44 * @var \Drupal\Core\Render\RendererInterface
49 * List of already instantiated mail plugins.
53 protected $instances = [];
56 * Constructs the MailManager object.
58 * @param \Traversable $namespaces
59 * An object that implements \Traversable which contains the root paths
60 * keyed by the corresponding namespace to look for plugin implementations.
61 * @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
62 * Cache backend instance to use.
63 * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
64 * The module handler to invoke the alter hook with.
65 * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
66 * The configuration factory.
67 * @param \Drupal\Core\Logger\LoggerChannelFactoryInterface $logger_factory
68 * The logger channel factory.
69 * @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
70 * The string translation service.
71 * @param \Drupal\Core\Render\RendererInterface $renderer
74 public function __construct(\Traversable $namespaces, CacheBackendInterface $cache_backend, ModuleHandlerInterface $module_handler, ConfigFactoryInterface $config_factory, LoggerChannelFactoryInterface $logger_factory, TranslationInterface $string_translation, RendererInterface $renderer) {
75 parent::__construct('Plugin/Mail', $namespaces, $module_handler, 'Drupal\Core\Mail\MailInterface', 'Drupal\Core\Annotation\Mail');
76 $this->alterInfo('mail_backend_info');
77 $this->setCacheBackend($cache_backend, 'mail_backend_plugins');
78 $this->configFactory = $config_factory;
79 $this->loggerFactory = $logger_factory;
80 $this->stringTranslation = $string_translation;
81 $this->renderer = $renderer;
85 * Overrides PluginManagerBase::getInstance().
87 * Returns an instance of the mail plugin to use for a given message ID.
89 * The selection of a particular implementation is controlled via the config
90 * 'system.mail.interface', which is a keyed array. The default
91 * implementation is the mail plugin whose ID is the value of 'default' key. A
92 * more specific match first to key and then to module will be used in
93 * preference to the default. To specify a different plugin for all mail sent
94 * by one module, set the plugin ID as the value for the key corresponding to
95 * the module name. To specify a plugin for a particular message sent by one
96 * module, set the plugin ID as the value for the array key that is the
97 * message ID, which is "${module}_${key}".
99 * For example to debug all mail sent by the user module by logging it to a
100 * file, you might set the variable as something like:
104 * 'default' => 'php_mail',
105 * 'user' => 'devel_mail_log',
109 * Finally, a different system can be specified for a specific message ID (see
110 * the $key param), such as one of the keys used by the contact module:
114 * 'default' => 'php_mail',
115 * 'user' => 'devel_mail_log',
116 * 'contact_page_autoreply' => 'null_mail',
120 * Other possible uses for system include a mail-sending plugin that actually
121 * sends (or duplicates) each message to SMS, Twitter, instant message, etc,
122 * or a plugin that queues up a large number of messages for more efficient
123 * bulk sending or for sending via a remote gateway so as to reduce the load
124 * on the local server.
126 * @param array $options
127 * An array with the following key/value pairs:
128 * - module: (string) The module name which was used by
129 * \Drupal\Core\Mail\MailManagerInterface->mail() to invoke hook_mail().
130 * - key: (string) A key to identify the email sent. The final message ID
131 * is a string represented as {$module}_{$key}.
133 * @return \Drupal\Core\Mail\MailInterface
134 * A mail plugin instance.
136 * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
138 public function getInstance(array $options) {
139 $module = $options['module'];
140 $key = $options['key'];
141 $message_id = $module . '_' . $key;
143 $configuration = $this->configFactory->get('system.mail')->get('interface');
145 // Look for overrides for the default mail plugin, starting from the most
146 // specific message_id, and falling back to the module name.
147 if (isset($configuration[$message_id])) {
148 $plugin_id = $configuration[$message_id];
150 elseif (isset($configuration[$module])) {
151 $plugin_id = $configuration[$module];
154 $plugin_id = $configuration['default'];
157 if (empty($this->instances[$plugin_id])) {
158 $this->instances[$plugin_id] = $this->createInstance($plugin_id);
160 return $this->instances[$plugin_id];
166 public function mail($module, $key, $to, $langcode, $params = [], $reply = NULL, $send = TRUE) {
167 // Mailing can invoke rendering (e.g., generating URLs, replacing tokens),
168 // but e-mails are not HTTP responses: they're not cached, they don't have
169 // attachments. Therefore we perform mailing inside its own render context,
170 // to ensure it doesn't leak into the render context for the HTTP response
171 // to the current request.
172 return $this->renderer->executeInRenderContext(new RenderContext(), function() use ($module, $key, $to, $langcode, $params, $reply, $send) {
173 return $this->doMail($module, $key, $to, $langcode, $params, $reply, $send);
178 * Composes and optionally sends an email message.
180 * @param string $module
181 * A module name to invoke hook_mail() on. The {$module}_mail() hook will be
182 * called to complete the $message structure which will already contain
185 * A key to identify the email sent. The final message ID for email altering
186 * will be {$module}_{$key}.
188 * The email address or addresses where the message will be sent to. The
189 * formatting of this string will be validated with the
190 * @link http://php.net/manual/filter.filters.validate.php PHP email validation filter. @endlink
193 * - user@example.com, anotheruser@example.com
194 * - User <user@example.com>
195 * - User <user@example.com>, Another User <anotheruser@example.com>
196 * @param string $langcode
197 * Language code to use to compose the email.
198 * @param array $params
199 * (optional) Parameters to build the email.
200 * @param string|null $reply
201 * Optional email address to be used to answer.
203 * If TRUE, call an implementation of
204 * \Drupal\Core\Mail\MailInterface->mail() to deliver the message, and
205 * store the result in $message['result']. Modules implementing
206 * hook_mail_alter() may cancel sending by setting $message['send'] to
210 * The $message array structure containing all details of the message. If
211 * already sent ($send = TRUE), then the 'result' element will contain the
212 * success indicator of the email, failure being already written to the
213 * watchdog. (Success means nothing more than the message being accepted at
214 * php-level, which still doesn't guarantee it to be delivered.)
216 * @see \Drupal\Core\Mail\MailManagerInterface::mail()
218 public function doMail($module, $key, $to, $langcode, $params = [], $reply = NULL, $send = TRUE) {
219 $site_config = $this->configFactory->get('system.site');
220 $site_mail = $site_config->get('mail');
221 if (empty($site_mail)) {
222 $site_mail = ini_get('sendmail_from');
225 // Bundle up the variables into a structured array for altering.
227 'id' => $module . '_' . $key,
231 'from' => $site_mail,
232 'reply-to' => $reply,
233 'langcode' => $langcode,
240 // Build the default headers.
242 'MIME-Version' => '1.0',
243 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
244 'Content-Transfer-Encoding' => '8Bit',
245 'X-Mailer' => 'Drupal',
247 // To prevent email from looking like spam, the addresses in the Sender and
248 // Return-Path headers should have a domain authorized to use the
249 // originating SMTP server.
250 $headers['Sender'] = $headers['Return-Path'] = $site_mail;
251 $headers['From'] = $site_config->get('name') . ' <' . $site_mail . '>';
253 $headers['Reply-to'] = $reply;
255 $message['headers'] = $headers;
257 // Build the email (get subject and body, allow additional headers) by
258 // invoking hook_mail() on this module. We cannot use
259 // moduleHandler()->invoke() as we need to have $message by reference in
261 if (function_exists($function = $module . '_mail')) {
262 $function($key, $message, $params);
265 // Invoke hook_mail_alter() to allow all modules to alter the resulting
267 $this->moduleHandler->alter('mail', $message);
269 // Retrieve the responsible implementation for this message.
270 $system = $this->getInstance(['module' => $module, 'key' => $key]);
272 // Format the message body.
273 $message = $system->format($message);
275 // Optionally send email.
277 // The original caller requested sending. Sending was canceled by one or
278 // more hook_mail_alter() implementations. We set 'result' to NULL,
279 // because FALSE indicates an error in sending.
280 if (empty($message['send'])) {
281 $message['result'] = NULL;
283 // Sending was originally requested and was not canceled.
285 // Ensure that subject is plain text. By default translated and
286 // formatted strings are prepared for the HTML context and email
287 // subjects are plain strings.
288 if ($message['subject']) {
289 $message['subject'] = PlainTextOutput::renderFromHtml($message['subject']);
291 $message['result'] = $system->mail($message);
293 if (!$message['result']) {
294 $this->loggerFactory->get('mail')
295 ->error('Error sending email (from %from to %to with reply-to %reply).', [
296 '%from' => $message['from'],
297 '%to' => $message['to'],
298 '%reply' => $message['reply-to'] ? $message['reply-to'] : $this->t('not set'),
300 drupal_set_message($this->t('Unable to send email. Contact the site administrator if the problem persists.'), 'error');