Mailer.php 11 KB

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