1
0

Mailer.php 10 KB

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