MandrillHandler.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php declare(strict_types=1);
  2. /*
  3. * This file is part of the Monolog package.
  4. *
  5. * (c) Jordi Boggiano <j.boggiano@seld.be>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Monolog\Handler;
  11. use Monolog\Logger;
  12. /**
  13. * MandrillHandler uses cURL to send the emails to the Mandrill API
  14. *
  15. * @author Adam Nicholson <adamnicholson10@gmail.com>
  16. */
  17. class MandrillHandler extends MailHandler
  18. {
  19. protected $message;
  20. protected $apiKey;
  21. /**
  22. * @param string $apiKey A valid Mandrill API key
  23. * @param callable|\Swift_Message $message An example message for real messages, only the body will be replaced
  24. * @param int $level The minimum logging level at which this handler will be triggered
  25. * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
  26. */
  27. public function __construct($apiKey, $message, $level = Logger::ERROR, $bubble = true)
  28. {
  29. parent::__construct($level, $bubble);
  30. if (!$message instanceof \Swift_Message && is_callable($message)) {
  31. $message = call_user_func($message);
  32. }
  33. if (!$message instanceof \Swift_Message) {
  34. throw new \InvalidArgumentException('You must provide either a Swift_Message instance or a callable returning it');
  35. }
  36. $this->message = $message;
  37. $this->apiKey = $apiKey;
  38. }
  39. /**
  40. * {@inheritdoc}
  41. */
  42. protected function send(string $content, array $records)
  43. {
  44. $mime = null;
  45. if ($this->isHtmlBody($content)) {
  46. $mime = 'text/html';
  47. }
  48. $message = clone $this->message;
  49. $message->setBody($content, $mime);
  50. $message->setDate(time());
  51. $ch = curl_init();
  52. curl_setopt($ch, CURLOPT_URL, 'https://mandrillapp.com/api/1.0/messages/send-raw.json');
  53. curl_setopt($ch, CURLOPT_POST, 1);
  54. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  55. curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
  56. 'key' => $this->apiKey,
  57. 'raw_message' => (string) $message,
  58. 'async' => false,
  59. ]));
  60. Curl\Util::execute($ch);
  61. }
  62. }