Mailer.php 9.4 KB

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