MailManager.php 12 KB

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