Mailer.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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. // Do not move this block or change it's content without contacting the release crew
  53. public const DEFAULT_DIMENSIONS = '252x120';
  54. // Do not move this block or change it's content without contacting the release crew
  55. public const MAX_LOGO_SIZE = 105;
  56. private ?MailerInterface $instance = null;
  57. public function __construct(
  58. private IConfig $config,
  59. private LoggerInterface $logger,
  60. private Defaults $defaults,
  61. private IURLGenerator $urlGenerator,
  62. private IL10N $l10n,
  63. private IEventDispatcher $dispatcher,
  64. private IFactory $l10nFactory,
  65. ) {
  66. }
  67. /**
  68. * Creates a new message object that can be passed to send()
  69. */
  70. public function createMessage(): Message {
  71. $plainTextOnly = $this->config->getSystemValueBool('mail_send_plaintext_only', false);
  72. return new Message(new Email(), $plainTextOnly);
  73. }
  74. /**
  75. * @param string|null $data
  76. * @param string|null $filename
  77. * @param string|null $contentType
  78. * @since 13.0.0
  79. */
  80. public function createAttachment($data = null, $filename = null, $contentType = null): IAttachment {
  81. return new Attachment($data, $filename, $contentType);
  82. }
  83. /**
  84. * @param string|null $contentType
  85. * @since 13.0.0
  86. */
  87. public function createAttachmentFromPath(string $path, $contentType = null): IAttachment {
  88. return new Attachment(null, null, $contentType, $path);
  89. }
  90. /**
  91. * Creates a new email template object
  92. *
  93. * @since 12.0.0
  94. */
  95. public function createEMailTemplate(string $emailId, array $data = []): IEMailTemplate {
  96. $class = $this->config->getSystemValueString('mail_template_class', '');
  97. if ($class !== '' && class_exists($class) && is_a($class, EMailTemplate::class, true)) {
  98. return new $class(
  99. $this->defaults,
  100. $this->urlGenerator,
  101. $this->l10nFactory,
  102. $emailId,
  103. $data
  104. );
  105. }
  106. $logoDimensions = $this->config->getAppValue('theming', 'logoDimensions', self::DEFAULT_DIMENSIONS);
  107. if (str_contains($logoDimensions, 'x')) {
  108. [$width, $height] = explode('x', $logoDimensions);
  109. $width = (int) $width;
  110. $height = (int) $height;
  111. if ($width > self::MAX_LOGO_SIZE || $height > self::MAX_LOGO_SIZE) {
  112. if ($width === $height) {
  113. $logoWidth = self::MAX_LOGO_SIZE;
  114. $logoHeight = self::MAX_LOGO_SIZE;
  115. } elseif ($width > $height) {
  116. $logoWidth = self::MAX_LOGO_SIZE;
  117. $logoHeight = (int) (($height / $width) * self::MAX_LOGO_SIZE);
  118. } else {
  119. $logoWidth = (int) (($width / $height) * self::MAX_LOGO_SIZE);
  120. $logoHeight = self::MAX_LOGO_SIZE;
  121. }
  122. } else {
  123. $logoWidth = $width;
  124. $logoHeight = $height;
  125. }
  126. } else {
  127. $logoWidth = $logoHeight = null;
  128. }
  129. return new EMailTemplate(
  130. $this->defaults,
  131. $this->urlGenerator,
  132. $this->l10nFactory,
  133. $logoWidth,
  134. $logoHeight,
  135. $emailId,
  136. $data
  137. );
  138. }
  139. /**
  140. * Send the specified message. Also sets the from address to the value defined in config.php
  141. * if no-one has been passed.
  142. *
  143. * If sending failed, the recipients that failed will be returned (to, cc and bcc).
  144. * Will output additional debug info if 'mail_smtpdebug' => 'true' is set in config.php
  145. *
  146. * @param IMessage $message Message to send
  147. * @return string[] $failedRecipients
  148. */
  149. public function send(IMessage $message): array {
  150. $debugMode = $this->config->getSystemValueBool('mail_smtpdebug', false);
  151. if (!($message instanceof Message)) {
  152. throw new \InvalidArgumentException('Object not of type ' . Message::class);
  153. }
  154. if (empty($message->getFrom())) {
  155. $message->setFrom([\OCP\Util::getDefaultEmailAddress('no-reply') => $this->defaults->getName()]);
  156. }
  157. $mailer = $this->getInstance();
  158. $this->dispatcher->dispatchTyped(new BeforeMessageSent($message));
  159. try {
  160. $message->setRecipients();
  161. } catch (\InvalidArgumentException|RfcComplianceException $e) {
  162. $logMessage = sprintf(
  163. 'Could not send mail to "%s" with subject "%s" as validation for address failed',
  164. print_r(array_merge($message->getTo(), $message->getCc(), $message->getBcc()), true),
  165. $message->getSubject()
  166. );
  167. $this->logger->debug($logMessage, ['app' => 'core', 'exception' => $e]);
  168. $recipients = array_merge($message->getTo(), $message->getCc(), $message->getBcc());
  169. $failedRecipients = [];
  170. array_walk($recipients, function ($value, $key) use (&$failedRecipients) {
  171. if (is_numeric($key)) {
  172. $failedRecipients[] = $value;
  173. } else {
  174. $failedRecipients[] = $key;
  175. }
  176. });
  177. return $failedRecipients;
  178. }
  179. try {
  180. $mailer->send($message->getSymfonyEmail());
  181. } catch (TransportExceptionInterface $e) {
  182. $logMessage = sprintf('Sending mail to "%s" with subject "%s" failed', print_r($message->getTo(), true), $message->getSubject());
  183. $this->logger->debug($logMessage, ['app' => 'core', 'exception' => $e]);
  184. if ($debugMode) {
  185. $this->logger->debug($e->getDebug(), ['app' => 'core']);
  186. }
  187. $recipients = array_merge($message->getTo(), $message->getCc(), $message->getBcc());
  188. $failedRecipients = [];
  189. array_walk($recipients, function ($value, $key) use (&$failedRecipients) {
  190. if (is_numeric($key)) {
  191. $failedRecipients[] = $value;
  192. } else {
  193. $failedRecipients[] = $key;
  194. }
  195. });
  196. return $failedRecipients;
  197. }
  198. // Debugging logging
  199. $logMessage = sprintf('Sent mail to "%s" with subject "%s"', print_r($message->getTo(), true), $message->getSubject());
  200. $this->logger->debug($logMessage, ['app' => 'core']);
  201. return [];
  202. }
  203. /**
  204. * @deprecated 26.0.0 Implicit validation is done in \OC\Mail\Message::setRecipients
  205. * via \Symfony\Component\Mime\Address::__construct
  206. *
  207. * @param string $email Email address to be validated
  208. * @return bool True if the mail address is valid, false otherwise
  209. */
  210. public function validateMailAddress(string $email): bool {
  211. if ($email === '') {
  212. // Shortcut: empty addresses are never valid
  213. return false;
  214. }
  215. $strictMailCheck = $this->config->getAppValue('core', 'enforce_strict_email_check', 'yes') === 'yes';
  216. $validator = new EmailValidator();
  217. $validation = $strictMailCheck ? new NoRFCWarningsValidation() : new RFCValidation();
  218. return $validator->isValid($email, $validation);
  219. }
  220. protected function getInstance(): MailerInterface {
  221. if (!is_null($this->instance)) {
  222. return $this->instance;
  223. }
  224. $transport = null;
  225. switch ($this->config->getSystemValueString('mail_smtpmode', 'smtp')) {
  226. case 'sendmail':
  227. $transport = $this->getSendMailInstance();
  228. break;
  229. case 'smtp':
  230. default:
  231. $transport = $this->getSmtpInstance();
  232. break;
  233. }
  234. return new SymfonyMailer($transport);
  235. }
  236. /**
  237. * Returns the SMTP transport
  238. *
  239. * Only supports ssl/tls
  240. * starttls is not enforcable with Symfony Mailer but might be available
  241. * via the automatic config (Symfony Mailer internal)
  242. *
  243. * @return EsmtpTransport
  244. */
  245. protected function getSmtpInstance(): EsmtpTransport {
  246. // either null or true - if nothing is passed, let the symfony mailer figure out the configuration by itself
  247. $mailSmtpsecure = ($this->config->getSystemValue('mail_smtpsecure', null) === 'ssl') ? true : null;
  248. $transport = new EsmtpTransport(
  249. $this->config->getSystemValueString('mail_smtphost', '127.0.0.1'),
  250. $this->config->getSystemValueInt('mail_smtpport', 25),
  251. $mailSmtpsecure,
  252. null,
  253. $this->logger
  254. );
  255. /** @var SocketStream $stream */
  256. $stream = $transport->getStream();
  257. /** @psalm-suppress InternalMethod */
  258. $stream->setTimeout($this->config->getSystemValueInt('mail_smtptimeout', 10));
  259. if ($this->config->getSystemValueBool('mail_smtpauth', false)) {
  260. $transport->setUsername($this->config->getSystemValueString('mail_smtpname', ''));
  261. $transport->setPassword($this->config->getSystemValueString('mail_smtppassword', ''));
  262. }
  263. $streamingOptions = $this->config->getSystemValue('mail_smtpstreamoptions', []);
  264. if (is_array($streamingOptions) && !empty($streamingOptions)) {
  265. /** @psalm-suppress InternalMethod */
  266. $currentStreamingOptions = $stream->getStreamOptions();
  267. $currentStreamingOptions = array_merge_recursive($currentStreamingOptions, $streamingOptions);
  268. /** @psalm-suppress InternalMethod */
  269. $stream->setStreamOptions($currentStreamingOptions);
  270. }
  271. $overwriteCliUrl = parse_url(
  272. $this->config->getSystemValueString('overwrite.cli.url', ''),
  273. PHP_URL_HOST
  274. );
  275. if (!empty($overwriteCliUrl)) {
  276. $transport->setLocalDomain($overwriteCliUrl);
  277. }
  278. return $transport;
  279. }
  280. /**
  281. * Returns the sendmail transport
  282. *
  283. * @return SendmailTransport
  284. */
  285. protected function getSendMailInstance(): SendmailTransport {
  286. switch ($this->config->getSystemValueString('mail_smtpmode', 'smtp')) {
  287. case 'qmail':
  288. $binaryPath = '/var/qmail/bin/sendmail';
  289. break;
  290. default:
  291. $sendmail = \OCP\Server::get(IBinaryFinder::class)->findBinaryPath('sendmail');
  292. if ($sendmail === null) {
  293. $sendmail = '/usr/sbin/sendmail';
  294. }
  295. $binaryPath = $sendmail;
  296. break;
  297. }
  298. $binaryParam = match ($this->config->getSystemValueString('mail_sendmailmode', 'smtp')) {
  299. 'pipe' => ' -t -i',
  300. default => ' -bs',
  301. };
  302. return new SendmailTransport($binaryPath . $binaryParam, null, $this->logger);
  303. }
  304. }