Email.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. <?php
  2. namespace Grav\Plugin\Email;
  3. use Grav\Common\Config\Config;
  4. use Grav\Common\Grav;
  5. use Grav\Common\Utils;
  6. use Grav\Common\Language\Language;
  7. use Grav\Common\Markdown\Parsedown;
  8. use Grav\Common\Twig\Twig;
  9. use Grav\Framework\Form\Interfaces\FormInterface;
  10. use \Monolog\Logger;
  11. use \Monolog\Handler\StreamHandler;
  12. use RocketTheme\Toolbox\Event\Event;
  13. use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
  14. use Symfony\Component\Mailer\Envelope;
  15. use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
  16. use Symfony\Component\Mailer\Header\MetadataHeader;
  17. use Symfony\Component\Mailer\Header\TagHeader;
  18. use Symfony\Component\Mailer\Mailer;
  19. use Symfony\Component\Mailer\Transport;
  20. use Symfony\Component\Mailer\Transport\TransportInterface;
  21. use Symfony\Component\Mime\Address;
  22. class Email
  23. {
  24. /** @var Mailer */
  25. protected $mailer;
  26. /** @var TransportInterface */
  27. protected $transport;
  28. protected $log;
  29. public function __construct()
  30. {
  31. $this->initMailer();
  32. $this->initLog();
  33. }
  34. /**
  35. * Returns true if emails have been enabled in the system.
  36. *
  37. * @return bool
  38. */
  39. public static function enabled(): bool
  40. {
  41. return Grav::instance()['config']->get('plugins.email.mailer.engine') !== 'none';
  42. }
  43. /**
  44. * Returns true if debugging on emails has been enabled.
  45. *
  46. * @return bool
  47. */
  48. public static function debug(): bool
  49. {
  50. return Grav::instance()['config']->get('plugins.email.debug') == 'true';
  51. }
  52. /**
  53. * Creates an email message.
  54. *
  55. * @param string|null $subject
  56. * @param string|null $body
  57. * @param string|null $contentType
  58. * @param string|null $charset @deprecated
  59. * @return Message
  60. */
  61. public function message(string $subject = null, string $body = null, string $contentType = null, string $charset = null): Message
  62. {
  63. $message = new Message();
  64. $message->subject($subject);
  65. if ($contentType === 'text/html') {
  66. $message->html($body);
  67. } else {
  68. $message->text($body);
  69. }
  70. return $message;
  71. }
  72. /**
  73. * Send email.
  74. *
  75. * @param Message $message
  76. * @param Envelope|null $envelope
  77. * @return int
  78. */
  79. public function send(Message $message, Envelope $envelope = null): int
  80. {
  81. $status = '🛑 ';
  82. $sent_msg = null;
  83. $debug = null;
  84. try {
  85. $sent_msg = $this->transport->send($message->getEmail(), $envelope);
  86. $return = 1;
  87. $status = '✅';
  88. $debug = $sent_msg->getDebug();
  89. } catch (TransportExceptionInterface $e) {
  90. $return = 0;
  91. $status .= $e->getMessage();
  92. $debug = $e->getDebug();
  93. }
  94. if ($this->debug()) {
  95. $log_msg = "Email sent to %s at %s -> %s\n%s";
  96. $to = $this->jsonifyRecipients($message->getEmail()->getTo());
  97. $msg = sprintf($log_msg, $to, date('Y-m-d H:i:s'), $status, $debug);
  98. $this->log->addInfo($msg);
  99. }
  100. return $return;
  101. }
  102. /**
  103. * Build e-mail message.
  104. *
  105. * @param array $params
  106. * @param array $vars
  107. * @return Message
  108. */
  109. public function buildMessage(array $params, array $vars = []): Message
  110. {
  111. /** @var Twig $twig */
  112. $twig = Grav::instance()['twig'];
  113. $twig->init();
  114. /** @var Config $config */
  115. $config = Grav::instance()['config'];
  116. /** @var Language $language */
  117. $language = Grav::instance()['language'];
  118. // Create message object.
  119. $message = new Message();
  120. $headers = $message->getEmail()->getHeaders();
  121. $email = $message->getEmail();
  122. // Extend parameters with defaults.
  123. $params += [
  124. 'bcc' => $config->get('plugins.email.bcc', []),
  125. 'body' => $config->get('plugins.email.body', '{% include "forms/data.html.twig" %}'),
  126. 'cc' => $config->get('plugins.email.cc', []),
  127. 'cc_name' => $config->get('plugins.email.cc_name'),
  128. 'charset' => $config->get('plugins.email.charset', 'utf-8'),
  129. 'from' => $config->get('plugins.email.from'),
  130. 'from_name' => $config->get('plugins.email.from_name'),
  131. 'content_type' => $config->get('plugins.email.content_type', 'text/html'),
  132. 'reply_to' => $config->get('plugins.email.reply_to', []),
  133. 'reply_to_name' => $config->get('plugins.email.reply_to_name'),
  134. 'subject' => !empty($vars['form']) && $vars['form'] instanceof FormInterface ? $vars['form']->page()->title() : null,
  135. 'to' => $config->get('plugins.email.to'),
  136. 'to_name' => $config->get('plugins.email.to_name'),
  137. 'process_markdown' => false,
  138. 'template' => false,
  139. 'message' => $message
  140. ];
  141. if (!$params['to']) {
  142. throw new \RuntimeException($language->translate('PLUGIN_EMAIL.PLEASE_CONFIGURE_A_TO_ADDRESS'));
  143. }
  144. if (!$params['from']) {
  145. throw new \RuntimeException($language->translate('PLUGIN_EMAIL.PLEASE_CONFIGURE_A_FROM_ADDRESS'));
  146. }
  147. // make email configuration available to templates
  148. $vars += [
  149. 'email' => $params,
  150. ];
  151. $params = $this->processParams($params, $vars);
  152. // Process parameters.
  153. foreach ($params as $key => $value) {
  154. switch ($key) {
  155. case 'body':
  156. if (is_string($value)) {
  157. $this->processBody($message, $params, $vars, $twig, $value);
  158. } elseif (is_array($value)) {
  159. foreach ($value as $body_part) {
  160. $params_part = $params;
  161. if (isset($body_part['content_type'])) {
  162. $params_part['content_type'] = $body_part['content_type'];
  163. }
  164. if (isset($body_part['template'])) {
  165. $params_part['template'] = $body_part['template'];
  166. }
  167. if (isset($body_part['body'])) {
  168. $this->processBody($message, $params_part, $vars, $twig, $body_part['body']);
  169. }
  170. }
  171. }
  172. break;
  173. case 'subject':
  174. if ($value) {
  175. $message->subject($language->translate($value));
  176. }
  177. break;
  178. case 'to':
  179. case 'from':
  180. case 'cc':
  181. case 'bcc':
  182. case 'reply_to':
  183. if ($recipients = $this->processRecipients($key, $params)) {
  184. $key = $key === 'reply_to' ? 'replyTo' : $key;
  185. $email->$key(...$recipients);
  186. }
  187. break;
  188. case 'tags':
  189. foreach ((array) $value as $tag) {
  190. if (is_string($tag)) {
  191. $headers->add(new TagHeader($tag));
  192. }
  193. }
  194. break;
  195. case 'metadata':
  196. foreach ((array) $value as $k => $v) {
  197. if (is_string($k) && is_string($v)) {
  198. $headers->add(new MetadataHeader($k, $v));
  199. }
  200. }
  201. break;
  202. }
  203. }
  204. return $message;
  205. }
  206. /**
  207. * @param string $type
  208. * @param array $params
  209. * @return array
  210. */
  211. protected function processRecipients(string $type, array $params): array
  212. {
  213. $recipients = $params[$type] ?? Grav::instance()['config']->get('plugins.email.'.$type) ?? [];
  214. $list = [];
  215. if (!empty($recipients)) {
  216. if (is_array($recipients) && Utils::isAssoc($recipients)) {
  217. $list[] = $this->createAddress($recipients);
  218. } else {
  219. if (is_array($recipients)) {
  220. if (count($recipients) ===2 && $this->isValidEmail($recipients[0]) && is_string($recipients[1])) {
  221. $list[] = $this->createAddress($recipients);
  222. } else {
  223. foreach ($recipients as $recipient) {
  224. $list[] = $this->createAddress($recipient);
  225. }
  226. }
  227. } else {
  228. if (is_string($recipients) && Utils::contains($recipients, ',')) {
  229. $recipients = array_map('trim', explode(',', $recipients));
  230. foreach ($recipients as $recipient) {
  231. $list[] = $this->createAddress($recipient);
  232. }
  233. } else {
  234. if (!Utils::contains($recipients, ['<','>']) && ($params[$type."_name"])) {
  235. $recipients = [$recipients, $params[$type."_name"]];
  236. }
  237. $list[] = $this->createAddress($recipients);
  238. }
  239. }
  240. }
  241. }
  242. return $list;
  243. }
  244. /**
  245. * @param $data
  246. * @return Address
  247. */
  248. protected function createAddress($data): Address
  249. {
  250. if (is_string($data)) {
  251. preg_match('/^(.*)\<(.*)\>$/', $data, $matches);
  252. if (isset($matches[2])) {
  253. $email = trim($matches[2]);
  254. $name = trim($matches[1]);
  255. } else {
  256. $email = $data;
  257. $name = '';
  258. }
  259. } elseif (Utils::isAssoc($data)) {
  260. $first_key = array_key_first($data);
  261. if (filter_var($first_key, FILTER_VALIDATE_EMAIL)) {
  262. $email = $first_key;
  263. $name = $data[$first_key];
  264. } else {
  265. $email = $data['email'] ?? $data['mail'] ?? $data['address'] ?? '';
  266. $name = $data['name'] ?? $data['fullname'] ?? '';
  267. }
  268. } else {
  269. $email = $data[0] ?? '';
  270. $name = $data[1] ?? '';
  271. }
  272. return new Address($email, $name);
  273. }
  274. /**
  275. * @return null|Mailer
  276. * @internal
  277. */
  278. protected function initMailer(): ?Mailer
  279. {
  280. if (!$this->enabled()) {
  281. return null;
  282. }
  283. if (!$this->mailer) {
  284. $this->transport = $this->getTransport();
  285. // Create the Mailer using your created Transport
  286. $this->mailer = new Mailer($this->transport);
  287. }
  288. return $this->mailer;
  289. }
  290. /**
  291. * @return void
  292. * @throws \Exception
  293. */
  294. protected function initLog()
  295. {
  296. $log_file = Grav::instance()['locator']->findResource('log://email.log', true, true);
  297. $this->log = new Logger('email');
  298. /** @var UniformResourceLocator $locator */
  299. $this->log->pushHandler(new StreamHandler($log_file, Logger::DEBUG));
  300. }
  301. /**
  302. * @param array $params
  303. * @param array $vars
  304. * @return array
  305. */
  306. protected function processParams(array $params, array $vars = []): array
  307. {
  308. $twig = Grav::instance()['twig'];
  309. array_walk_recursive($params, function(&$value) use ($twig, $vars) {
  310. if (is_string($value)) {
  311. $value = $twig->processString($value, $vars);
  312. }
  313. });
  314. return $params;
  315. }
  316. /**
  317. * @param $message
  318. * @param $params
  319. * @param $vars
  320. * @param $twig
  321. * @param $body
  322. * @return void
  323. */
  324. protected function processBody($message, $params, $vars, $twig, $body)
  325. {
  326. if ($params['process_markdown'] && $params['content_type'] === 'text/html') {
  327. $body = (new Parsedown())->text($body);
  328. }
  329. if ($params['template']) {
  330. $body = $twig->processTemplate($params['template'], ['content' => $body] + $vars);
  331. }
  332. $content_type = !empty($params['content_type']) ? $twig->processString($params['content_type'], $vars) : null;
  333. if ($content_type === 'text/html') {
  334. $message->html($body);
  335. } else {
  336. $message->text($body);
  337. }
  338. }
  339. /**
  340. * @return TransportInterface
  341. */
  342. protected static function getTransport(): Transport\TransportInterface
  343. {
  344. /** @var Config $config */
  345. $config = Grav::instance()['config'];
  346. $engine = $config->get('plugins.email.mailer.engine');
  347. $dsn = 'null://default';
  348. // Create the Transport and initialize it.
  349. switch ($engine) {
  350. case 'smtps':
  351. case 'smtp':
  352. $options = $config->get('plugins.email.mailer.smtp');
  353. $dsn = $engine . '://';
  354. $auth = '';
  355. if (isset($options['encryption']) && $options['encryption'] === 'none') {
  356. $options['options']['verify_peer'] = 0;
  357. }
  358. if (isset($options['user'])) {
  359. $auth .= urlencode($options['user']);
  360. }
  361. if (isset($options['password'])) {
  362. $auth .= ':'. urlencode($options['password']);
  363. }
  364. if (!empty($auth)) {
  365. $dsn .= "$auth@";
  366. }
  367. if (isset($options['server'])) {
  368. $dsn .= urlencode($options['server']);
  369. }
  370. if (isset($options['port'])) {
  371. $dsn .= ":{$options['port']}";
  372. }
  373. if (isset($options['options'])) {
  374. $dsn .= '?' . http_build_query($options['options']);
  375. }
  376. break;
  377. case 'mail':
  378. case 'native':
  379. $dsn = 'native://default';
  380. break;
  381. case 'sendmail':
  382. $dsn = 'sendmail://default';
  383. $bin = $config->get('plugins.email.mailer.sendmail.bin');
  384. if (isset($bin)) {
  385. $dsn .= '?command=' . urlencode($bin);
  386. }
  387. break;
  388. default:
  389. $e = new Event(['engine' => $engine, ]);
  390. Grav::instance()->fireEvent('onEmailTransportDsn', $e);
  391. if (isset($e['dsn'])) {
  392. $dsn = $e['dsn'];
  393. }
  394. break;
  395. }
  396. if ($dsn instanceof TransportInterface) {
  397. $transport = $dsn;
  398. } else {
  399. $transport = Transport::fromDsn($dsn) ;
  400. }
  401. return $transport;
  402. }
  403. /**
  404. * @param array $recipients
  405. * @return string
  406. */
  407. protected function jsonifyRecipients(array $recipients): string
  408. {
  409. $json = [];
  410. foreach ($recipients as $recipient) {
  411. $json[] = str_replace('"', "", $recipient->toString());
  412. }
  413. return json_encode($json);
  414. }
  415. protected function isValidEmail($email): bool
  416. {
  417. return is_string($email) && filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
  418. }
  419. /**
  420. * @return void
  421. * @deprecated 4.0 Switched from Swiftmailer to Symfony/Mailer - No longer supported
  422. */
  423. public static function flushQueue() {}
  424. /**
  425. * @return void
  426. * @deprecated 4.0 Switched from Swiftmailer to Symfony/Mailer - No longer supported
  427. */
  428. public static function clearQueueFailures() {}
  429. /**
  430. * Creates an attachment.
  431. *
  432. * @param string $data
  433. * @param string $filename
  434. * @param string $contentType
  435. * @deprecated 4.0 Switched from Swiftmailer to Symfony/Mailer - No longer supported
  436. * @return void
  437. */
  438. public function attachment($data = null, $filename = null, $contentType = null) {}
  439. /**
  440. * Creates an embedded attachment.
  441. *
  442. * @param string $data
  443. * @param string $filename
  444. * @param string $contentType
  445. * @deprecated 4.0 Switched from Swiftmailer to Symfony/Mailer - No longer supported
  446. * @return void
  447. */
  448. public function embedded($data = null, $filename = null, $contentType = null) {}
  449. /**
  450. * Creates an image attachment.
  451. *
  452. * @param string $data
  453. * @param string $filename
  454. * @param string $contentType
  455. * @deprecated 4.0 Switched from Swiftmailer to Symfony/Mailer - No longer supported
  456. * @return void
  457. */
  458. public function image($data = null, $filename = null, $contentType = null) {}
  459. }