You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Mailer.php 11KB

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