Mailer.php 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2016, ownCloud, Inc.
  5. *
  6. * @author Joas Schilling <coding@schilljs.com>
  7. * @author Lukas Reschke <lukas@statuscode.ch>
  8. * @author Morris Jobke <hey@morrisjobke.de>
  9. * @author Roeland Jago Douma <roeland@famdouma.nl>
  10. *
  11. * @license AGPL-3.0
  12. *
  13. * This code is free software: you can redistribute it and/or modify
  14. * it under the terms of the GNU Affero General Public License, version 3,
  15. * as published by the Free Software Foundation.
  16. *
  17. * This program is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. * GNU Affero General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU Affero General Public License, version 3,
  23. * along with this program. If not, see <http://www.gnu.org/licenses/>
  24. *
  25. */
  26. namespace OC\Mail;
  27. use Egulias\EmailValidator\EmailValidator;
  28. use Egulias\EmailValidator\Validation\RFCValidation;
  29. use OCP\Defaults;
  30. use OCP\IConfig;
  31. use OCP\IL10N;
  32. use OCP\IURLGenerator;
  33. use OCP\Mail\IAttachment;
  34. use OCP\Mail\IEMailTemplate;
  35. use OCP\Mail\IMailer;
  36. use OCP\ILogger;
  37. use OCP\Mail\IMessage;
  38. /**
  39. * Class Mailer provides some basic functions to create a mail message that can be used in combination with
  40. * \OC\Mail\Message.
  41. *
  42. * Example usage:
  43. *
  44. * $mailer = \OC::$server->getMailer();
  45. * $message = $mailer->createMessage();
  46. * $message->setSubject('Your Subject');
  47. * $message->setFrom(array('cloud@domain.org' => 'ownCloud Notifier');
  48. * $message->setTo(array('recipient@domain.org' => 'Recipient');
  49. * $message->setBody('The message text');
  50. * $mailer->send($message);
  51. *
  52. * This message can then be passed to send() of \OC\Mail\Mailer
  53. *
  54. * @package OC\Mail
  55. */
  56. class Mailer implements IMailer {
  57. /** @var \Swift_Mailer Cached mailer */
  58. private $instance = null;
  59. /** @var IConfig */
  60. private $config;
  61. /** @var ILogger */
  62. private $logger;
  63. /** @var Defaults */
  64. private $defaults;
  65. /** @var IURLGenerator */
  66. private $urlGenerator;
  67. /** @var IL10N */
  68. private $l10n;
  69. /**
  70. * @param IConfig $config
  71. * @param ILogger $logger
  72. * @param Defaults $defaults
  73. * @param IURLGenerator $urlGenerator
  74. * @param IL10N $l10n
  75. */
  76. public function __construct(IConfig $config,
  77. ILogger $logger,
  78. Defaults $defaults,
  79. IURLGenerator $urlGenerator,
  80. IL10N $l10n) {
  81. $this->config = $config;
  82. $this->logger = $logger;
  83. $this->defaults = $defaults;
  84. $this->urlGenerator = $urlGenerator;
  85. $this->l10n = $l10n;
  86. }
  87. /**
  88. * Creates a new message object that can be passed to send()
  89. *
  90. * @return IMessage
  91. */
  92. public function createMessage(): IMessage {
  93. $plainTextOnly = $this->config->getSystemValue('mail_send_plaintext_only', false);
  94. return new Message(new \Swift_Message(), $plainTextOnly);
  95. }
  96. /**
  97. * @param string|null $data
  98. * @param string|null $filename
  99. * @param string|null $contentType
  100. * @return IAttachment
  101. * @since 13.0.0
  102. */
  103. public function createAttachment($data = null, $filename = null, $contentType = null): IAttachment {
  104. return new Attachment(new \Swift_Attachment($data, $filename, $contentType));
  105. }
  106. /**
  107. * @param string $path
  108. * @param string|null $contentType
  109. * @return IAttachment
  110. * @since 13.0.0
  111. */
  112. public function createAttachmentFromPath(string $path, $contentType = null): IAttachment {
  113. return new Attachment(\Swift_Attachment::fromPath($path, $contentType));
  114. }
  115. /**
  116. * Creates a new email template object
  117. *
  118. * @param string $emailId
  119. * @param array $data
  120. * @return IEMailTemplate
  121. * @since 12.0.0
  122. */
  123. public function createEMailTemplate(string $emailId, array $data = []): IEMailTemplate {
  124. $class = $this->config->getSystemValue('mail_template_class', '');
  125. if ($class !== '' && class_exists($class) && is_a($class, EMailTemplate::class, true)) {
  126. return new $class(
  127. $this->defaults,
  128. $this->urlGenerator,
  129. $this->l10n,
  130. $emailId,
  131. $data
  132. );
  133. }
  134. return new EMailTemplate(
  135. $this->defaults,
  136. $this->urlGenerator,
  137. $this->l10n,
  138. $emailId,
  139. $data
  140. );
  141. }
  142. /**
  143. * Send the specified message. Also sets the from address to the value defined in config.php
  144. * if no-one has been passed.
  145. *
  146. * @param IMessage|Message $message Message to send
  147. * @return string[] Array with failed recipients. Be aware that this depends on the used mail backend and
  148. * therefore should be considered
  149. * @throws \Exception In case it was not possible to send the message. (for example if an invalid mail address
  150. * has been supplied.)
  151. */
  152. public function send(IMessage $message): array {
  153. $debugMode = $this->config->getSystemValue('mail_smtpdebug', false);
  154. if (empty($message->getFrom())) {
  155. $message->setFrom([\OCP\Util::getDefaultEmailAddress($this->defaults->getName()) => $this->defaults->getName()]);
  156. }
  157. $failedRecipients = [];
  158. $mailer = $this->getInstance();
  159. // Enable logger if debug mode is enabled
  160. if($debugMode) {
  161. $mailLogger = new \Swift_Plugins_Loggers_ArrayLogger();
  162. $mailer->registerPlugin(new \Swift_Plugins_LoggerPlugin($mailLogger));
  163. }
  164. $mailer->send($message->getSwiftMessage(), $failedRecipients);
  165. // Debugging logging
  166. $logMessage = sprintf('Sent mail to "%s" with subject "%s"', print_r($message->getTo(), true), $message->getSubject());
  167. $this->logger->debug($logMessage, ['app' => 'core']);
  168. if($debugMode && isset($mailLogger)) {
  169. $this->logger->debug($mailLogger->dump(), ['app' => 'core']);
  170. }
  171. return $failedRecipients;
  172. }
  173. /**
  174. * Checks if an e-mail address is valid
  175. *
  176. * @param string $email Email address to be validated
  177. * @return bool True if the mail address is valid, false otherwise
  178. */
  179. public function validateMailAddress(string $email): bool {
  180. $validator = new EmailValidator();
  181. $validation = new RFCValidation();
  182. return $validator->isValid($this->convertEmail($email), $validation);
  183. }
  184. /**
  185. * SwiftMailer does currently not work with IDN domains, this function therefore converts the domains
  186. *
  187. * FIXME: Remove this once SwiftMailer supports IDN
  188. *
  189. * @param string $email
  190. * @return string Converted mail address if `idn_to_ascii` exists
  191. */
  192. protected function convertEmail(string $email): string {
  193. if (!function_exists('idn_to_ascii') || !defined('INTL_IDNA_VARIANT_UTS46') || strpos($email, '@') === false) {
  194. return $email;
  195. }
  196. list($name, $domain) = explode('@', $email, 2);
  197. $domain = idn_to_ascii($domain, 0,INTL_IDNA_VARIANT_UTS46);
  198. return $name.'@'.$domain;
  199. }
  200. protected function getInstance(): \Swift_Mailer {
  201. if (!is_null($this->instance)) {
  202. return $this->instance;
  203. }
  204. $transport = null;
  205. switch ($this->config->getSystemValue('mail_smtpmode', 'smtp')) {
  206. case 'sendmail':
  207. $transport = $this->getSendMailInstance();
  208. break;
  209. case 'smtp':
  210. default:
  211. $transport = $this->getSmtpInstance();
  212. break;
  213. }
  214. return new \Swift_Mailer($transport);
  215. }
  216. /**
  217. * Returns the SMTP transport
  218. *
  219. * @return \Swift_SmtpTransport
  220. */
  221. protected function getSmtpInstance(): \Swift_SmtpTransport {
  222. $transport = new \Swift_SmtpTransport();
  223. $transport->setTimeout($this->config->getSystemValue('mail_smtptimeout', 10));
  224. $transport->setHost($this->config->getSystemValue('mail_smtphost', '127.0.0.1'));
  225. $transport->setPort($this->config->getSystemValue('mail_smtpport', 25));
  226. if ($this->config->getSystemValue('mail_smtpauth', false)) {
  227. $transport->setUsername($this->config->getSystemValue('mail_smtpname', ''));
  228. $transport->setPassword($this->config->getSystemValue('mail_smtppassword', ''));
  229. $transport->setAuthMode($this->config->getSystemValue('mail_smtpauthtype', 'LOGIN'));
  230. }
  231. $smtpSecurity = $this->config->getSystemValue('mail_smtpsecure', '');
  232. if (!empty($smtpSecurity)) {
  233. $transport->setEncryption($smtpSecurity);
  234. }
  235. return $transport;
  236. }
  237. /**
  238. * Returns the sendmail transport
  239. *
  240. * @return \Swift_SendmailTransport
  241. */
  242. protected function getSendMailInstance(): \Swift_SendmailTransport {
  243. switch ($this->config->getSystemValue('mail_smtpmode', 'smtp')) {
  244. case 'qmail':
  245. $binaryPath = '/var/qmail/bin/sendmail';
  246. break;
  247. default:
  248. $sendmail = \OC_Helper::findBinaryPath('sendmail');
  249. if ($sendmail === null) {
  250. $sendmail = '/usr/sbin/sendmail';
  251. }
  252. $binaryPath = $sendmail;
  253. break;
  254. }
  255. switch ($this->config->getSystemValue('mail_sendmailmode', 'smtp')) {
  256. case 'pipe':
  257. $binaryParam = ' -t';
  258. break;
  259. default:
  260. $binaryParam = ' -bs';
  261. break;
  262. }
  263. return new \Swift_SendmailTransport($binaryPath . $binaryParam);
  264. }
  265. }