1
0

Mailer.php 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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 OCP\Defaults;
  28. use OCP\IConfig;
  29. use OCP\IL10N;
  30. use OCP\IURLGenerator;
  31. use OCP\Mail\IAttachment;
  32. use OCP\Mail\IEMailTemplate;
  33. use OCP\Mail\IMailer;
  34. use OCP\ILogger;
  35. use OCP\Mail\IMessage;
  36. /**
  37. * Class Mailer provides some basic functions to create a mail message that can be used in combination with
  38. * \OC\Mail\Message.
  39. *
  40. * Example usage:
  41. *
  42. * $mailer = \OC::$server->getMailer();
  43. * $message = $mailer->createMessage();
  44. * $message->setSubject('Your Subject');
  45. * $message->setFrom(array('cloud@domain.org' => 'ownCloud Notifier');
  46. * $message->setTo(array('recipient@domain.org' => 'Recipient');
  47. * $message->setBody('The message text');
  48. * $mailer->send($message);
  49. *
  50. * This message can then be passed to send() of \OC\Mail\Mailer
  51. *
  52. * @package OC\Mail
  53. */
  54. class Mailer implements IMailer {
  55. /** @var \Swift_SmtpTransport|\Swift_SendmailTransport|\Swift_MailTransport Cached transport */
  56. private $instance = null;
  57. /** @var IConfig */
  58. private $config;
  59. /** @var ILogger */
  60. private $logger;
  61. /** @var Defaults */
  62. private $defaults;
  63. /** @var IURLGenerator */
  64. private $urlGenerator;
  65. /** @var IL10N */
  66. private $l10n;
  67. /**
  68. * @param IConfig $config
  69. * @param ILogger $logger
  70. * @param Defaults $defaults
  71. * @param IURLGenerator $urlGenerator
  72. * @param IL10N $l10n
  73. */
  74. public function __construct(IConfig $config,
  75. ILogger $logger,
  76. Defaults $defaults,
  77. IURLGenerator $urlGenerator,
  78. IL10N $l10n) {
  79. $this->config = $config;
  80. $this->logger = $logger;
  81. $this->defaults = $defaults;
  82. $this->urlGenerator = $urlGenerator;
  83. $this->l10n = $l10n;
  84. }
  85. /**
  86. * Creates a new message object that can be passed to send()
  87. *
  88. * @return IMessage
  89. */
  90. public function createMessage(): IMessage {
  91. return new Message(new \Swift_Message());
  92. }
  93. /**
  94. * @param string|null $data
  95. * @param string|null $filename
  96. * @param string|null $contentType
  97. * @return IAttachment
  98. * @since 13.0.0
  99. */
  100. public function createAttachment($data = null, $filename = null, $contentType = null): IAttachment {
  101. return new Attachment(\Swift_Attachment::newInstance($data, $filename, $contentType));
  102. }
  103. /**
  104. * @param string $path
  105. * @param string|null $contentType
  106. * @return IAttachment
  107. * @since 13.0.0
  108. */
  109. public function createAttachmentFromPath(string $path, $contentType = null): IAttachment {
  110. return new Attachment(\Swift_Attachment::fromPath($path, $contentType));
  111. }
  112. /**
  113. * Creates a new email template object
  114. *
  115. * @param string $emailId
  116. * @param array $data
  117. * @return IEMailTemplate
  118. * @since 12.0.0
  119. */
  120. public function createEMailTemplate(string $emailId, array $data = []): IEMailTemplate {
  121. $class = $this->config->getSystemValue('mail_template_class', '');
  122. if ($class !== '' && class_exists($class) && is_a($class, EMailTemplate::class, true)) {
  123. return new $class(
  124. $this->defaults,
  125. $this->urlGenerator,
  126. $this->l10n,
  127. $emailId,
  128. $data
  129. );
  130. }
  131. return new EMailTemplate(
  132. $this->defaults,
  133. $this->urlGenerator,
  134. $this->l10n,
  135. $emailId,
  136. $data
  137. );
  138. }
  139. /**
  140. * Send the specified message. Also sets the from address to the value defined in config.php
  141. * if no-one has been passed.
  142. *
  143. * @param IMessage|Message $message Message to send
  144. * @return string[] Array with failed recipients. Be aware that this depends on the used mail backend and
  145. * therefore should be considered
  146. * @throws \Exception In case it was not possible to send the message. (for example if an invalid mail address
  147. * has been supplied.)
  148. */
  149. public function send(IMessage $message): array {
  150. $debugMode = $this->config->getSystemValue('mail_smtpdebug', false);
  151. if (empty($message->getFrom())) {
  152. $message->setFrom([\OCP\Util::getDefaultEmailAddress($this->defaults->getName()) => $this->defaults->getName()]);
  153. }
  154. $failedRecipients = [];
  155. $mailer = $this->getInstance();
  156. // Enable logger if debug mode is enabled
  157. if($debugMode) {
  158. $mailLogger = new \Swift_Plugins_Loggers_ArrayLogger();
  159. $mailer->registerPlugin(new \Swift_Plugins_LoggerPlugin($mailLogger));
  160. }
  161. $mailer->send($message->getSwiftMessage(), $failedRecipients);
  162. // Debugging logging
  163. $logMessage = sprintf('Sent mail to "%s" with subject "%s"', print_r($message->getTo(), true), $message->getSubject());
  164. $this->logger->debug($logMessage, ['app' => 'core']);
  165. if($debugMode && isset($mailLogger)) {
  166. $this->logger->debug($mailLogger->dump(), ['app' => 'core']);
  167. }
  168. return $failedRecipients;
  169. }
  170. /**
  171. * Checks if an e-mail address is valid
  172. *
  173. * @param string $email Email address to be validated
  174. * @return bool True if the mail address is valid, false otherwise
  175. */
  176. public function validateMailAddress(string $email): bool {
  177. return \Swift_Validate::email($this->convertEmail($email));
  178. }
  179. /**
  180. * SwiftMailer does currently not work with IDN domains, this function therefore converts the domains
  181. *
  182. * FIXME: Remove this once SwiftMailer supports IDN
  183. *
  184. * @param string $email
  185. * @return string Converted mail address if `idn_to_ascii` exists
  186. */
  187. protected function convertEmail(string $email): string {
  188. if (!function_exists('idn_to_ascii') || strpos($email, '@') === false) {
  189. return $email;
  190. }
  191. list($name, $domain) = explode('@', $email, 2);
  192. $domain = idn_to_ascii($domain, 0,INTL_IDNA_VARIANT_UTS46);
  193. return $name.'@'.$domain;
  194. }
  195. /**
  196. * Returns whatever transport is configured within the config
  197. *
  198. * @return \Swift_SmtpTransport|\Swift_SendmailTransport|\Swift_MailTransport
  199. */
  200. protected function getInstance() {
  201. if (!is_null($this->instance)) {
  202. return $this->instance;
  203. }
  204. switch ($this->config->getSystemValue('mail_smtpmode', 'php')) {
  205. case 'smtp':
  206. $this->instance = $this->getSmtpInstance();
  207. break;
  208. case 'sendmail':
  209. // FIXME: Move into the return statement but requires proper testing
  210. // for SMTP and mail as well. Thus not really doable for a
  211. // minor release.
  212. $this->instance = \Swift_Mailer::newInstance($this->getSendMailInstance());
  213. break;
  214. default:
  215. $this->instance = $this->getMailInstance();
  216. break;
  217. }
  218. return $this->instance;
  219. }
  220. /**
  221. * Returns the SMTP transport
  222. *
  223. * @return \Swift_SmtpTransport
  224. */
  225. protected function getSmtpInstance(): \Swift_SmtpTransport {
  226. $transport = \Swift_SmtpTransport::newInstance();
  227. $transport->setTimeout($this->config->getSystemValue('mail_smtptimeout', 10));
  228. $transport->setHost($this->config->getSystemValue('mail_smtphost', '127.0.0.1'));
  229. $transport->setPort($this->config->getSystemValue('mail_smtpport', 25));
  230. if ($this->config->getSystemValue('mail_smtpauth', false)) {
  231. $transport->setUsername($this->config->getSystemValue('mail_smtpname', ''));
  232. $transport->setPassword($this->config->getSystemValue('mail_smtppassword', ''));
  233. $transport->setAuthMode($this->config->getSystemValue('mail_smtpauthtype', 'LOGIN'));
  234. }
  235. $smtpSecurity = $this->config->getSystemValue('mail_smtpsecure', '');
  236. if (!empty($smtpSecurity)) {
  237. $transport->setEncryption($smtpSecurity);
  238. }
  239. $transport->start();
  240. return $transport;
  241. }
  242. /**
  243. * Returns the sendmail transport
  244. *
  245. * @return \Swift_SendmailTransport
  246. */
  247. protected function getSendMailInstance(): \Swift_SendmailTransport {
  248. switch ($this->config->getSystemValue('mail_smtpmode', 'php')) {
  249. case 'qmail':
  250. $binaryPath = '/var/qmail/bin/sendmail';
  251. break;
  252. default:
  253. $binaryPath = '/usr/sbin/sendmail';
  254. break;
  255. }
  256. return \Swift_SendmailTransport::newInstance($binaryPath . ' -bs');
  257. }
  258. /**
  259. * Returns the mail transport
  260. *
  261. * @return \Swift_MailTransport
  262. */
  263. protected function getMailInstance(): \Swift_MailTransport {
  264. return \Swift_MailTransport::newInstance();
  265. }
  266. }