MailManager.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. <?php
  2. namespace Drupal\Core\Mail;
  3. use Drupal\Component\Render\PlainTextOutput;
  4. use Drupal\Component\Utility\Unicode;
  5. use Drupal\Core\Logger\LoggerChannelFactoryInterface;
  6. use Drupal\Core\Messenger\MessengerTrait;
  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;
  15. /**
  16. * Provides a Mail plugin manager.
  17. *
  18. * @see \Drupal\Core\Annotation\Mail
  19. * @see \Drupal\Core\Mail\MailInterface
  20. * @see plugin_api
  21. */
  22. class MailManager extends DefaultPluginManager implements MailManagerInterface {
  23. use MessengerTrait;
  24. use StringTranslationTrait;
  25. /**
  26. * The config factory.
  27. *
  28. * @var \Drupal\Core\Config\ConfigFactoryInterface
  29. */
  30. protected $configFactory;
  31. /**
  32. * The logger factory.
  33. *
  34. * @var \Drupal\Core\Logger\LoggerChannelFactoryInterface
  35. */
  36. protected $loggerFactory;
  37. /**
  38. * The renderer.
  39. *
  40. * @var \Drupal\Core\Render\RendererInterface
  41. */
  42. protected $renderer;
  43. /**
  44. * List of already instantiated mail plugins.
  45. *
  46. * @var array
  47. */
  48. protected $instances = [];
  49. /**
  50. * Constructs the MailManager object.
  51. *
  52. * @param \Traversable $namespaces
  53. * An object that implements \Traversable which contains the root paths
  54. * keyed by the corresponding namespace to look for plugin implementations.
  55. * @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
  56. * Cache backend instance to use.
  57. * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
  58. * The module handler to invoke the alter hook with.
  59. * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
  60. * The configuration factory.
  61. * @param \Drupal\Core\Logger\LoggerChannelFactoryInterface $logger_factory
  62. * The logger channel factory.
  63. * @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
  64. * The string translation service.
  65. * @param \Drupal\Core\Render\RendererInterface $renderer
  66. * The renderer.
  67. */
  68. public function __construct(\Traversable $namespaces, CacheBackendInterface $cache_backend, ModuleHandlerInterface $module_handler, ConfigFactoryInterface $config_factory, LoggerChannelFactoryInterface $logger_factory, TranslationInterface $string_translation, RendererInterface $renderer) {
  69. parent::__construct('Plugin/Mail', $namespaces, $module_handler, 'Drupal\Core\Mail\MailInterface', 'Drupal\Core\Annotation\Mail');
  70. $this->alterInfo('mail_backend_info');
  71. $this->setCacheBackend($cache_backend, 'mail_backend_plugins');
  72. $this->configFactory = $config_factory;
  73. $this->loggerFactory = $logger_factory;
  74. $this->stringTranslation = $string_translation;
  75. $this->renderer = $renderer;
  76. }
  77. /**
  78. * Overrides PluginManagerBase::getInstance().
  79. *
  80. * Returns an instance of the mail plugin to use for a given message ID.
  81. *
  82. * The selection of a particular implementation is controlled via the config
  83. * 'system.mail.interface', which is a keyed array. The default
  84. * implementation is the mail plugin whose ID is the value of 'default' key. A
  85. * more specific match first to key and then to module will be used in
  86. * preference to the default. To specify a different plugin for all mail sent
  87. * by one module, set the plugin ID as the value for the key corresponding to
  88. * the module name. To specify a plugin for a particular message sent by one
  89. * module, set the plugin ID as the value for the array key that is the
  90. * message ID, which is "${module}_${key}".
  91. *
  92. * For example to debug all mail sent by the user module by logging it to a
  93. * file, you might set the variable as something like:
  94. *
  95. * @code
  96. * array(
  97. * 'default' => 'php_mail',
  98. * 'user' => 'devel_mail_log',
  99. * );
  100. * @endcode
  101. *
  102. * Finally, a different system can be specified for a specific message ID (see
  103. * the $key param), such as one of the keys used by the contact module:
  104. *
  105. * @code
  106. * array(
  107. * 'default' => 'php_mail',
  108. * 'user' => 'devel_mail_log',
  109. * 'contact_page_autoreply' => 'null_mail',
  110. * );
  111. * @endcode
  112. *
  113. * Other possible uses for system include a mail-sending plugin that actually
  114. * sends (or duplicates) each message to SMS, Twitter, instant message, etc,
  115. * or a plugin that queues up a large number of messages for more efficient
  116. * bulk sending or for sending via a remote gateway so as to reduce the load
  117. * on the local server.
  118. *
  119. * @param array $options
  120. * An array with the following key/value pairs:
  121. * - module: (string) The module name which was used by
  122. * \Drupal\Core\Mail\MailManagerInterface->mail() to invoke hook_mail().
  123. * - key: (string) A key to identify the email sent. The final message ID
  124. * is a string represented as {$module}_{$key}.
  125. *
  126. * @return \Drupal\Core\Mail\MailInterface
  127. * A mail plugin instance.
  128. *
  129. * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
  130. */
  131. public function getInstance(array $options) {
  132. $module = $options['module'];
  133. $key = $options['key'];
  134. $message_id = $module . '_' . $key;
  135. $configuration = $this->configFactory->get('system.mail')->get('interface');
  136. // Look for overrides for the default mail plugin, starting from the most
  137. // specific message_id, and falling back to the module name.
  138. if (isset($configuration[$message_id])) {
  139. $plugin_id = $configuration[$message_id];
  140. }
  141. elseif (isset($configuration[$module])) {
  142. $plugin_id = $configuration[$module];
  143. }
  144. else {
  145. $plugin_id = $configuration['default'];
  146. }
  147. if (empty($this->instances[$plugin_id])) {
  148. $this->instances[$plugin_id] = $this->createInstance($plugin_id);
  149. }
  150. return $this->instances[$plugin_id];
  151. }
  152. /**
  153. * {@inheritdoc}
  154. */
  155. public function mail($module, $key, $to, $langcode, $params = [], $reply = NULL, $send = TRUE) {
  156. // Mailing can invoke rendering (e.g., generating URLs, replacing tokens),
  157. // but e-mails are not HTTP responses: they're not cached, they don't have
  158. // attachments. Therefore we perform mailing inside its own render context,
  159. // to ensure it doesn't leak into the render context for the HTTP response
  160. // to the current request.
  161. return $this->renderer->executeInRenderContext(new RenderContext(), function () use ($module, $key, $to, $langcode, $params, $reply, $send) {
  162. return $this->doMail($module, $key, $to, $langcode, $params, $reply, $send);
  163. });
  164. }
  165. /**
  166. * Composes and optionally sends an email message.
  167. *
  168. * @param string $module
  169. * A module name to invoke hook_mail() on. The {$module}_mail() hook will be
  170. * called to complete the $message structure which will already contain
  171. * common defaults.
  172. * @param string $key
  173. * A key to identify the email sent. The final message ID for email altering
  174. * will be {$module}_{$key}.
  175. * @param string $to
  176. * The email address or addresses where the message will be sent to. The
  177. * formatting of this string will be validated with the
  178. * @link http://php.net/manual/filter.filters.validate.php PHP email validation filter. @endlink
  179. * Some examples are:
  180. * - user@example.com
  181. * - user@example.com, anotheruser@example.com
  182. * - User <user@example.com>
  183. * - User <user@example.com>, Another User <anotheruser@example.com>
  184. * @param string $langcode
  185. * Language code to use to compose the email.
  186. * @param array $params
  187. * (optional) Parameters to build the email.
  188. * @param string|null $reply
  189. * Optional email address to be used to answer.
  190. * @param bool $send
  191. * If TRUE, call an implementation of
  192. * \Drupal\Core\Mail\MailInterface->mail() to deliver the message, and
  193. * store the result in $message['result']. Modules implementing
  194. * hook_mail_alter() may cancel sending by setting $message['send'] to
  195. * FALSE.
  196. *
  197. * @return array
  198. * The $message array structure containing all details of the message. If
  199. * already sent ($send = TRUE), then the 'result' element will contain the
  200. * success indicator of the email, failure being already written to the
  201. * watchdog. (Success means nothing more than the message being accepted at
  202. * php-level, which still doesn't guarantee it to be delivered.)
  203. *
  204. * @see \Drupal\Core\Mail\MailManagerInterface::mail()
  205. */
  206. public function doMail($module, $key, $to, $langcode, $params = [], $reply = NULL, $send = TRUE) {
  207. $site_config = $this->configFactory->get('system.site');
  208. $site_mail = $site_config->get('mail');
  209. if (empty($site_mail)) {
  210. $site_mail = ini_get('sendmail_from');
  211. }
  212. // Bundle up the variables into a structured array for altering.
  213. $message = [
  214. 'id' => $module . '_' . $key,
  215. 'module' => $module,
  216. 'key' => $key,
  217. 'to' => $to,
  218. 'from' => $site_mail,
  219. 'reply-to' => $reply,
  220. 'langcode' => $langcode,
  221. 'params' => $params,
  222. 'send' => TRUE,
  223. 'subject' => '',
  224. 'body' => [],
  225. ];
  226. // Build the default headers.
  227. $headers = [
  228. 'MIME-Version' => '1.0',
  229. 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
  230. 'Content-Transfer-Encoding' => '8Bit',
  231. 'X-Mailer' => 'Drupal',
  232. ];
  233. // To prevent email from looking like spam, the addresses in the Sender and
  234. // Return-Path headers should have a domain authorized to use the
  235. // originating SMTP server.
  236. $headers['Sender'] = $headers['Return-Path'] = $site_mail;
  237. // Headers are usually encoded in the mail plugin that implements
  238. // \Drupal\Core\Mail\MailInterface::mail(), for example,
  239. // \Drupal\Core\Mail\Plugin\Mail\PhpMail::mail(). The site name must be
  240. // encoded here to prevent mail plugins from encoding the email address,
  241. // which would break the header.
  242. $headers['From'] = Unicode::mimeHeaderEncode($site_config->get('name'), TRUE) . ' <' . $site_mail . '>';
  243. if ($reply) {
  244. $headers['Reply-to'] = $reply;
  245. }
  246. $message['headers'] = $headers;
  247. // Build the email (get subject and body, allow additional headers) by
  248. // invoking hook_mail() on this module. We cannot use
  249. // moduleHandler()->invoke() as we need to have $message by reference in
  250. // hook_mail().
  251. if (function_exists($function = $module . '_mail')) {
  252. $function($key, $message, $params);
  253. }
  254. // Invoke hook_mail_alter() to allow all modules to alter the resulting
  255. // email.
  256. $this->moduleHandler->alter('mail', $message);
  257. // Retrieve the responsible implementation for this message.
  258. $system = $this->getInstance(['module' => $module, 'key' => $key]);
  259. // Format the message body.
  260. $message = $system->format($message);
  261. // Optionally send email.
  262. if ($send) {
  263. // The original caller requested sending. Sending was canceled by one or
  264. // more hook_mail_alter() implementations. We set 'result' to NULL,
  265. // because FALSE indicates an error in sending.
  266. if (empty($message['send'])) {
  267. $message['result'] = NULL;
  268. }
  269. // Sending was originally requested and was not canceled.
  270. else {
  271. // Ensure that subject is plain text. By default translated and
  272. // formatted strings are prepared for the HTML context and email
  273. // subjects are plain strings.
  274. if ($message['subject']) {
  275. $message['subject'] = PlainTextOutput::renderFromHtml($message['subject']);
  276. }
  277. $message['result'] = $system->mail($message);
  278. // Log errors.
  279. if (!$message['result']) {
  280. $this->loggerFactory->get('mail')
  281. ->error('Error sending email (from %from to %to with reply-to %reply).', [
  282. '%from' => $message['from'],
  283. '%to' => $message['to'],
  284. '%reply' => $message['reply-to'] ? $message['reply-to'] : $this->t('not set'),
  285. ]);
  286. $this->messenger()->addError($this->t('Unable to send email. Contact the site administrator if the problem persists.'));
  287. }
  288. }
  289. }
  290. return $message;
  291. }
  292. }