Mailer.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  6. * SPDX-License-Identifier: AGPL-3.0-only
  7. */
  8. namespace OC\Mail;
  9. use Egulias\EmailValidator\EmailValidator;
  10. use Egulias\EmailValidator\Validation\NoRFCWarningsValidation;
  11. use Egulias\EmailValidator\Validation\RFCValidation;
  12. use OCP\Defaults;
  13. use OCP\EventDispatcher\IEventDispatcher;
  14. use OCP\IBinaryFinder;
  15. use OCP\IConfig;
  16. use OCP\IL10N;
  17. use OCP\IURLGenerator;
  18. use OCP\L10N\IFactory;
  19. use OCP\Mail\Events\BeforeMessageSent;
  20. use OCP\Mail\IAttachment;
  21. use OCP\Mail\IEMailTemplate;
  22. use OCP\Mail\IMailer;
  23. use OCP\Mail\IMessage;
  24. use Psr\Log\LoggerInterface;
  25. use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
  26. use Symfony\Component\Mailer\Mailer as SymfonyMailer;
  27. use Symfony\Component\Mailer\MailerInterface;
  28. use Symfony\Component\Mailer\Transport\SendmailTransport;
  29. use Symfony\Component\Mailer\Transport\Smtp\EsmtpTransport;
  30. use Symfony\Component\Mailer\Transport\Smtp\Stream\SocketStream;
  31. use Symfony\Component\Mime\Email;
  32. use Symfony\Component\Mime\Exception\RfcComplianceException;
  33. /**
  34. * Class Mailer provides some basic functions to create a mail message that can be used in combination with
  35. * \OC\Mail\Message.
  36. *
  37. * Example usage:
  38. *
  39. * $mailer = \OC::$server->get(\OCP\Mail\IMailer::class);
  40. * $message = $mailer->createMessage();
  41. * $message->setSubject('Your Subject');
  42. * $message->setFrom(array('cloud@domain.org' => 'ownCloud Notifier'));
  43. * $message->setTo(array('recipient@domain.org' => 'Recipient'));
  44. * $message->setBody('The message text', 'text/html');
  45. * $mailer->send($message);
  46. *
  47. * This message can then be passed to send() of \OC\Mail\Mailer
  48. *
  49. * @package OC\Mail
  50. */
  51. class Mailer implements IMailer {
  52. private ?MailerInterface $instance = null;
  53. public function __construct(
  54. private IConfig $config,
  55. private LoggerInterface $logger,
  56. private Defaults $defaults,
  57. private IURLGenerator $urlGenerator,
  58. private IL10N $l10n,
  59. private IEventDispatcher $dispatcher,
  60. private IFactory $l10nFactory,
  61. ) {
  62. }
  63. /**
  64. * Creates a new message object that can be passed to send()
  65. */
  66. public function createMessage(): Message {
  67. $plainTextOnly = $this->config->getSystemValueBool('mail_send_plaintext_only', false);
  68. return new Message(new Email(), $plainTextOnly);
  69. }
  70. /**
  71. * @param string|null $data
  72. * @param string|null $filename
  73. * @param string|null $contentType
  74. * @since 13.0.0
  75. */
  76. public function createAttachment($data = null, $filename = null, $contentType = null): IAttachment {
  77. return new Attachment($data, $filename, $contentType);
  78. }
  79. /**
  80. * @param string|null $contentType
  81. * @since 13.0.0
  82. */
  83. public function createAttachmentFromPath(string $path, $contentType = null): IAttachment {
  84. return new Attachment(null, null, $contentType, $path);
  85. }
  86. /**
  87. * Creates a new email template object
  88. *
  89. * @since 12.0.0
  90. */
  91. public function createEMailTemplate(string $emailId, array $data = []): IEMailTemplate {
  92. $class = $this->config->getSystemValueString('mail_template_class', '');
  93. if ($class !== '' && class_exists($class) && is_a($class, EMailTemplate::class, true)) {
  94. return new $class(
  95. $this->defaults,
  96. $this->urlGenerator,
  97. $this->l10nFactory,
  98. $emailId,
  99. $data
  100. );
  101. }
  102. return new EMailTemplate(
  103. $this->defaults,
  104. $this->urlGenerator,
  105. $this->l10nFactory,
  106. $emailId,
  107. $data
  108. );
  109. }
  110. /**
  111. * Send the specified message. Also sets the from address to the value defined in config.php
  112. * if no-one has been passed.
  113. *
  114. * If sending failed, the recipients that failed will be returned (to, cc and bcc).
  115. * Will output additional debug info if 'mail_smtpdebug' => 'true' is set in config.php
  116. *
  117. * @param IMessage $message Message to send
  118. * @return string[] $failedRecipients
  119. */
  120. public function send(IMessage $message): array {
  121. $debugMode = $this->config->getSystemValueBool('mail_smtpdebug', false);
  122. if (!($message instanceof Message)) {
  123. throw new \InvalidArgumentException('Object not of type ' . Message::class);
  124. }
  125. if (empty($message->getFrom())) {
  126. $message->setFrom([\OCP\Util::getDefaultEmailAddress('no-reply') => $this->defaults->getName()]);
  127. }
  128. $mailer = $this->getInstance();
  129. $this->dispatcher->dispatchTyped(new BeforeMessageSent($message));
  130. try {
  131. $message->setRecipients();
  132. } catch (\InvalidArgumentException|RfcComplianceException $e) {
  133. $logMessage = sprintf(
  134. 'Could not send mail to "%s" with subject "%s" as validation for address failed',
  135. print_r(array_merge($message->getTo(), $message->getCc(), $message->getBcc()), true),
  136. $message->getSubject()
  137. );
  138. $this->logger->debug($logMessage, ['app' => 'core', 'exception' => $e]);
  139. $recipients = array_merge($message->getTo(), $message->getCc(), $message->getBcc());
  140. $failedRecipients = [];
  141. array_walk($recipients, function ($value, $key) use (&$failedRecipients) {
  142. if (is_numeric($key)) {
  143. $failedRecipients[] = $value;
  144. } else {
  145. $failedRecipients[] = $key;
  146. }
  147. });
  148. return $failedRecipients;
  149. }
  150. try {
  151. $mailer->send($message->getSymfonyEmail());
  152. } catch (TransportExceptionInterface $e) {
  153. $logMessage = sprintf('Sending mail to "%s" with subject "%s" failed', print_r($message->getTo(), true), $message->getSubject());
  154. $this->logger->debug($logMessage, ['app' => 'core', 'exception' => $e]);
  155. if ($debugMode) {
  156. $this->logger->debug($e->getDebug(), ['app' => 'core']);
  157. }
  158. $recipients = array_merge($message->getTo(), $message->getCc(), $message->getBcc());
  159. $failedRecipients = [];
  160. array_walk($recipients, function ($value, $key) use (&$failedRecipients) {
  161. if (is_numeric($key)) {
  162. $failedRecipients[] = $value;
  163. } else {
  164. $failedRecipients[] = $key;
  165. }
  166. });
  167. return $failedRecipients;
  168. }
  169. // Debugging logging
  170. $logMessage = sprintf('Sent mail to "%s" with subject "%s"', print_r($message->getTo(), true), $message->getSubject());
  171. $this->logger->debug($logMessage, ['app' => 'core']);
  172. return [];
  173. }
  174. /**
  175. * @deprecated 26.0.0 Implicit validation is done in \OC\Mail\Message::setRecipients
  176. * via \Symfony\Component\Mime\Address::__construct
  177. *
  178. * @param string $email Email address to be validated
  179. * @return bool True if the mail address is valid, false otherwise
  180. */
  181. public function validateMailAddress(string $email): bool {
  182. if ($email === '') {
  183. // Shortcut: empty addresses are never valid
  184. return false;
  185. }
  186. $strictMailCheck = $this->config->getAppValue('core', 'enforce_strict_email_check', 'yes') === 'yes';
  187. $validator = new EmailValidator();
  188. $validation = $strictMailCheck ? new NoRFCWarningsValidation() : new RFCValidation();
  189. return $validator->isValid($email, $validation);
  190. }
  191. protected function getInstance(): MailerInterface {
  192. if (!is_null($this->instance)) {
  193. return $this->instance;
  194. }
  195. $transport = null;
  196. switch ($this->config->getSystemValueString('mail_smtpmode', 'smtp')) {
  197. case 'sendmail':
  198. $transport = $this->getSendMailInstance();
  199. break;
  200. case 'smtp':
  201. default:
  202. $transport = $this->getSmtpInstance();
  203. break;
  204. }
  205. return new SymfonyMailer($transport);
  206. }
  207. /**
  208. * Returns the SMTP transport
  209. *
  210. * Only supports ssl/tls
  211. * starttls is not enforcable with Symfony Mailer but might be available
  212. * via the automatic config (Symfony Mailer internal)
  213. *
  214. * @return EsmtpTransport
  215. */
  216. protected function getSmtpInstance(): EsmtpTransport {
  217. // either null or true - if nothing is passed, let the symfony mailer figure out the configuration by itself
  218. $mailSmtpsecure = ($this->config->getSystemValue('mail_smtpsecure', null) === 'ssl') ? true : null;
  219. $transport = new EsmtpTransport(
  220. $this->config->getSystemValueString('mail_smtphost', '127.0.0.1'),
  221. $this->config->getSystemValueInt('mail_smtpport', 25),
  222. $mailSmtpsecure,
  223. null,
  224. $this->logger
  225. );
  226. /** @var SocketStream $stream */
  227. $stream = $transport->getStream();
  228. /** @psalm-suppress InternalMethod */
  229. $stream->setTimeout($this->config->getSystemValueInt('mail_smtptimeout', 10));
  230. if ($this->config->getSystemValueBool('mail_smtpauth', false)) {
  231. $transport->setUsername($this->config->getSystemValueString('mail_smtpname', ''));
  232. $transport->setPassword($this->config->getSystemValueString('mail_smtppassword', ''));
  233. }
  234. $streamingOptions = $this->config->getSystemValue('mail_smtpstreamoptions', []);
  235. if (is_array($streamingOptions) && !empty($streamingOptions)) {
  236. /** @psalm-suppress InternalMethod */
  237. $currentStreamingOptions = $stream->getStreamOptions();
  238. $currentStreamingOptions = array_merge_recursive($currentStreamingOptions, $streamingOptions);
  239. /** @psalm-suppress InternalMethod */
  240. $stream->setStreamOptions($currentStreamingOptions);
  241. }
  242. $overwriteCliUrl = parse_url(
  243. $this->config->getSystemValueString('overwrite.cli.url', ''),
  244. PHP_URL_HOST
  245. );
  246. if (!empty($overwriteCliUrl)) {
  247. $transport->setLocalDomain($overwriteCliUrl);
  248. }
  249. return $transport;
  250. }
  251. /**
  252. * Returns the sendmail transport
  253. *
  254. * @return SendmailTransport
  255. */
  256. protected function getSendMailInstance(): SendmailTransport {
  257. switch ($this->config->getSystemValueString('mail_smtpmode', 'smtp')) {
  258. case 'qmail':
  259. $binaryPath = '/var/qmail/bin/sendmail';
  260. break;
  261. default:
  262. $sendmail = \OCP\Server::get(IBinaryFinder::class)->findBinaryPath('sendmail');
  263. if ($sendmail === null) {
  264. $sendmail = '/usr/sbin/sendmail';
  265. }
  266. $binaryPath = $sendmail;
  267. break;
  268. }
  269. $binaryParam = match ($this->config->getSystemValueString('mail_sendmailmode', 'smtp')) {
  270. 'pipe' => ' -t -i',
  271. default => ' -bs',
  272. };
  273. return new SendmailTransport($binaryPath . $binaryParam, null, $this->logger);
  274. }
  275. }