MailManager.php 12 KB

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