1
0

Mailer.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2016, ownCloud, Inc.
  5. *
  6. * @author Arne Hamann <kontakt+github@arne.email>
  7. * @author Branko Kokanovic <branko@kokanovic.org>
  8. * @author Carsten Wiedmann <carsten_sttgt@gmx.de>
  9. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  10. * @author Jared Boone <jared.boone@gmail.com>
  11. * @author Joas Schilling <coding@schilljs.com>
  12. * @author Julius Härtl <jus@bitgrid.net>
  13. * @author kevin147147 <kevintamool@gmail.com>
  14. * @author Lukas Reschke <lukas@statuscode.ch>
  15. * @author Morris Jobke <hey@morrisjobke.de>
  16. * @author Roeland Jago Douma <roeland@famdouma.nl>
  17. * @author Tekhnee <info@tekhnee.org>
  18. *
  19. * @license AGPL-3.0
  20. *
  21. * This code is free software: you can redistribute it and/or modify
  22. * it under the terms of the GNU Affero General Public License, version 3,
  23. * as published by the Free Software Foundation.
  24. *
  25. * This program is distributed in the hope that it will be useful,
  26. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  27. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  28. * GNU Affero General Public License for more details.
  29. *
  30. * You should have received a copy of the GNU Affero General Public License, version 3,
  31. * along with this program. If not, see <http://www.gnu.org/licenses/>
  32. *
  33. */
  34. namespace OC\Mail;
  35. use Egulias\EmailValidator\EmailValidator;
  36. use Egulias\EmailValidator\Validation\NoRFCWarningsValidation;
  37. use Egulias\EmailValidator\Validation\RFCValidation;
  38. use OCP\Defaults;
  39. use OCP\EventDispatcher\IEventDispatcher;
  40. use OCP\IBinaryFinder;
  41. use OCP\IConfig;
  42. use OCP\IL10N;
  43. use OCP\IURLGenerator;
  44. use OCP\L10N\IFactory;
  45. use OCP\Mail\Events\BeforeMessageSent;
  46. use OCP\Mail\IAttachment;
  47. use OCP\Mail\IEMailTemplate;
  48. use OCP\Mail\IMailer;
  49. use OCP\Mail\IMessage;
  50. use Psr\Log\LoggerInterface;
  51. use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
  52. use Symfony\Component\Mailer\Mailer as SymfonyMailer;
  53. use Symfony\Component\Mailer\MailerInterface;
  54. use Symfony\Component\Mailer\Transport\SendmailTransport;
  55. use Symfony\Component\Mailer\Transport\Smtp\EsmtpTransport;
  56. use Symfony\Component\Mailer\Transport\Smtp\Stream\SocketStream;
  57. use Symfony\Component\Mime\Email;
  58. use Symfony\Component\Mime\Exception\RfcComplianceException;
  59. /**
  60. * Class Mailer provides some basic functions to create a mail message that can be used in combination with
  61. * \OC\Mail\Message.
  62. *
  63. * Example usage:
  64. *
  65. * $mailer = \OC::$server->getMailer();
  66. * $message = $mailer->createMessage();
  67. * $message->setSubject('Your Subject');
  68. * $message->setFrom(array('cloud@domain.org' => 'ownCloud Notifier'));
  69. * $message->setTo(array('recipient@domain.org' => 'Recipient'));
  70. * $message->setBody('The message text', 'text/html');
  71. * $mailer->send($message);
  72. *
  73. * This message can then be passed to send() of \OC\Mail\Mailer
  74. *
  75. * @package OC\Mail
  76. */
  77. class Mailer implements IMailer {
  78. // Do not move this block or change it's content without contacting the release crew
  79. public const DEFAULT_DIMENSIONS = '252x120';
  80. // Do not move this block or change it's content without contacting the release crew
  81. public const MAX_LOGO_SIZE = 105;
  82. private ?MailerInterface $instance = null;
  83. public function __construct(
  84. private IConfig $config,
  85. private LoggerInterface $logger,
  86. private Defaults $defaults,
  87. private IURLGenerator $urlGenerator,
  88. private IL10N $l10n,
  89. private IEventDispatcher $dispatcher,
  90. private IFactory $l10nFactory,
  91. ) {
  92. }
  93. /**
  94. * Creates a new message object that can be passed to send()
  95. */
  96. public function createMessage(): Message {
  97. $plainTextOnly = $this->config->getSystemValueBool('mail_send_plaintext_only', false);
  98. return new Message(new Email(), $plainTextOnly);
  99. }
  100. /**
  101. * @param string|null $data
  102. * @param string|null $filename
  103. * @param string|null $contentType
  104. * @since 13.0.0
  105. */
  106. public function createAttachment($data = null, $filename = null, $contentType = null): IAttachment {
  107. return new Attachment($data, $filename, $contentType);
  108. }
  109. /**
  110. * @param string|null $contentType
  111. * @since 13.0.0
  112. */
  113. public function createAttachmentFromPath(string $path, $contentType = null): IAttachment {
  114. return new Attachment(null, null, $contentType, $path);
  115. }
  116. /**
  117. * Creates a new email template object
  118. *
  119. * @since 12.0.0
  120. */
  121. public function createEMailTemplate(string $emailId, array $data = []): IEMailTemplate {
  122. $logoDimensions = $this->config->getAppValue('theming', 'logoDimensions', self::DEFAULT_DIMENSIONS);
  123. if (str_contains($logoDimensions, 'x')) {
  124. [$width, $height] = explode('x', $logoDimensions);
  125. $width = (int) $width;
  126. $height = (int) $height;
  127. if ($width > self::MAX_LOGO_SIZE || $height > self::MAX_LOGO_SIZE) {
  128. if ($width === $height) {
  129. $logoWidth = self::MAX_LOGO_SIZE;
  130. $logoHeight = self::MAX_LOGO_SIZE;
  131. } elseif ($width > $height) {
  132. $logoWidth = self::MAX_LOGO_SIZE;
  133. $logoHeight = (int) (($height / $width) * self::MAX_LOGO_SIZE);
  134. } else {
  135. $logoWidth = (int) (($width / $height) * self::MAX_LOGO_SIZE);
  136. $logoHeight = self::MAX_LOGO_SIZE;
  137. }
  138. } else {
  139. $logoWidth = $width;
  140. $logoHeight = $height;
  141. }
  142. } else {
  143. $logoWidth = $logoHeight = null;
  144. }
  145. $class = $this->config->getSystemValueString('mail_template_class', '');
  146. if ($class !== '' && class_exists($class) && is_a($class, EMailTemplate::class, true)) {
  147. return new $class(
  148. $this->defaults,
  149. $this->urlGenerator,
  150. $this->l10nFactory,
  151. $logoWidth,
  152. $logoHeight,
  153. $emailId,
  154. $data
  155. );
  156. }
  157. return new EMailTemplate(
  158. $this->defaults,
  159. $this->urlGenerator,
  160. $this->l10nFactory,
  161. $logoWidth,
  162. $logoHeight,
  163. $emailId,
  164. $data
  165. );
  166. }
  167. /**
  168. * Send the specified message. Also sets the from address to the value defined in config.php
  169. * if no-one has been passed.
  170. *
  171. * If sending failed, the recipients that failed will be returned (to, cc and bcc).
  172. * Will output additional debug info if 'mail_smtpdebug' => 'true' is set in config.php
  173. *
  174. * @param IMessage $message Message to send
  175. * @return string[] $failedRecipients
  176. */
  177. public function send(IMessage $message): array {
  178. $debugMode = $this->config->getSystemValueBool('mail_smtpdebug', false);
  179. if (!($message instanceof Message)) {
  180. throw new \InvalidArgumentException('Object not of type ' . Message::class);
  181. }
  182. if (empty($message->getFrom())) {
  183. $message->setFrom([\OCP\Util::getDefaultEmailAddress('no-reply') => $this->defaults->getName()]);
  184. }
  185. $mailer = $this->getInstance();
  186. $this->dispatcher->dispatchTyped(new BeforeMessageSent($message));
  187. try {
  188. $message->setRecipients();
  189. } catch (\InvalidArgumentException|RfcComplianceException $e) {
  190. $logMessage = sprintf(
  191. 'Could not send mail to "%s" with subject "%s" as validation for address failed',
  192. print_r(array_merge($message->getTo(), $message->getCc(), $message->getBcc()), true),
  193. $message->getSubject()
  194. );
  195. $this->logger->debug($logMessage, ['app' => 'core', 'exception' => $e]);
  196. $recipients = array_merge($message->getTo(), $message->getCc(), $message->getBcc());
  197. $failedRecipients = [];
  198. array_walk($recipients, function ($value, $key) use (&$failedRecipients) {
  199. if (is_numeric($key)) {
  200. $failedRecipients[] = $value;
  201. } else {
  202. $failedRecipients[] = $key;
  203. }
  204. });
  205. return $failedRecipients;
  206. }
  207. try {
  208. $mailer->send($message->getSymfonyEmail());
  209. } catch (TransportExceptionInterface $e) {
  210. $logMessage = sprintf('Sending mail to "%s" with subject "%s" failed', print_r($message->getTo(), true), $message->getSubject());
  211. $this->logger->debug($logMessage, ['app' => 'core', 'exception' => $e]);
  212. if ($debugMode) {
  213. $this->logger->debug($e->getDebug(), ['app' => 'core']);
  214. }
  215. $recipients = array_merge($message->getTo(), $message->getCc(), $message->getBcc());
  216. $failedRecipients = [];
  217. array_walk($recipients, function ($value, $key) use (&$failedRecipients) {
  218. if (is_numeric($key)) {
  219. $failedRecipients[] = $value;
  220. } else {
  221. $failedRecipients[] = $key;
  222. }
  223. });
  224. return $failedRecipients;
  225. }
  226. // Debugging logging
  227. $logMessage = sprintf('Sent mail to "%s" with subject "%s"', print_r($message->getTo(), true), $message->getSubject());
  228. $this->logger->debug($logMessage, ['app' => 'core']);
  229. return [];
  230. }
  231. /**
  232. * @deprecated 26.0.0 Implicit validation is done in \OC\Mail\Message::setRecipients
  233. * via \Symfony\Component\Mime\Address::__construct
  234. *
  235. * @param string $email Email address to be validated
  236. * @return bool True if the mail address is valid, false otherwise
  237. */
  238. public function validateMailAddress(string $email): bool {
  239. if ($email === '') {
  240. // Shortcut: empty addresses are never valid
  241. return false;
  242. }
  243. $strictMailCheck = $this->config->getAppValue('core', 'enforce_strict_email_check', 'no') === 'yes';
  244. $validator = new EmailValidator();
  245. $validation = $strictMailCheck ? new NoRFCWarningsValidation() : new RFCValidation();
  246. return $validator->isValid($email, $validation);
  247. }
  248. protected function getInstance(): MailerInterface {
  249. if (!is_null($this->instance)) {
  250. return $this->instance;
  251. }
  252. $transport = null;
  253. switch ($this->config->getSystemValueString('mail_smtpmode', 'smtp')) {
  254. case 'sendmail':
  255. $transport = $this->getSendMailInstance();
  256. break;
  257. case 'smtp':
  258. default:
  259. $transport = $this->getSmtpInstance();
  260. break;
  261. }
  262. return new SymfonyMailer($transport);
  263. }
  264. /**
  265. * Returns the SMTP transport
  266. *
  267. * Only supports ssl/tls
  268. * starttls is not enforcable with Symfony Mailer but might be available
  269. * via the automatic config (Symfony Mailer internal)
  270. *
  271. * @return EsmtpTransport
  272. */
  273. protected function getSmtpInstance(): EsmtpTransport {
  274. // either null or true - if nothing is passed, let the symfony mailer figure out the configuration by itself
  275. $mailSmtpsecure = ($this->config->getSystemValue('mail_smtpsecure', null) === 'ssl') ? true : null;
  276. $transport = new EsmtpTransport(
  277. $this->config->getSystemValueString('mail_smtphost', '127.0.0.1'),
  278. $this->config->getSystemValueInt('mail_smtpport', 25),
  279. $mailSmtpsecure,
  280. null,
  281. $this->logger
  282. );
  283. /** @var SocketStream $stream */
  284. $stream = $transport->getStream();
  285. /** @psalm-suppress InternalMethod */
  286. $stream->setTimeout($this->config->getSystemValueInt('mail_smtptimeout', 10));
  287. if ($this->config->getSystemValueBool('mail_smtpauth', false)) {
  288. $transport->setUsername($this->config->getSystemValueString('mail_smtpname', ''));
  289. $transport->setPassword($this->config->getSystemValueString('mail_smtppassword', ''));
  290. }
  291. $streamingOptions = $this->config->getSystemValue('mail_smtpstreamoptions', []);
  292. if (is_array($streamingOptions) && !empty($streamingOptions)) {
  293. /** @psalm-suppress InternalMethod */
  294. $currentStreamingOptions = $stream->getStreamOptions();
  295. $currentStreamingOptions = array_merge_recursive($currentStreamingOptions, $streamingOptions);
  296. /** @psalm-suppress InternalMethod */
  297. $stream->setStreamOptions($currentStreamingOptions);
  298. }
  299. $overwriteCliUrl = parse_url(
  300. $this->config->getSystemValueString('overwrite.cli.url', ''),
  301. PHP_URL_HOST
  302. );
  303. if (!empty($overwriteCliUrl)) {
  304. $transport->setLocalDomain($overwriteCliUrl);
  305. }
  306. return $transport;
  307. }
  308. /**
  309. * Returns the sendmail transport
  310. *
  311. * @return SendmailTransport
  312. */
  313. protected function getSendMailInstance(): SendmailTransport {
  314. switch ($this->config->getSystemValueString('mail_smtpmode', 'smtp')) {
  315. case 'qmail':
  316. $binaryPath = '/var/qmail/bin/sendmail';
  317. break;
  318. default:
  319. $sendmail = \OCP\Server::get(IBinaryFinder::class)->findBinaryPath('sendmail');
  320. if ($sendmail === null) {
  321. $sendmail = '/usr/sbin/sendmail';
  322. }
  323. $binaryPath = $sendmail;
  324. break;
  325. }
  326. $binaryParam = match ($this->config->getSystemValueString('mail_sendmailmode', 'smtp')) {
  327. 'pipe' => ' -t -i',
  328. default => ' -bs',
  329. };
  330. return new SendmailTransport($binaryPath . $binaryParam, null, $this->logger);
  331. }
  332. }