Mailer.php 11 KB

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