Mailer.php 7.6 KB

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