Mailer.php 11 KB

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