1: <?php
2:
3: namespace Fabian\Mandrill;
4:
5: 6: 7: 8: 9:
10: class MandrillMailer implements \Nette\Mail\IMailer {
11: 12: 13: 14:
15: private $apiKey;
16:
17: 18: 19: 20:
21: private $apiEndpoint = "https://mandrillapp.com/api/1.0";
22:
23: 24: 25: 26: 27:
28: private $apiFormat = 'json';
29:
30: public function __construct($apiKey)
31: {
32: $this->apiKey = $apiKey;
33: }
34:
35: 36: 37: 38:
39: public function send(\Nette\Mail\Message $message)
40: {
41: if ($message instanceof Message) {
42: $params = $message->getMandrillParams();
43: } else {
44: $params = $this->parseNetteMessage($message);
45: }
46:
47: $this->callApi($params);
48: }
49:
50: 51: 52: 53: 54:
55: private function parseNetteMessage(\Nette\Mail\Message $message)
56: {
57: $params = array();
58:
59: $params['subject'] = $message->getSubject();
60: $params['text'] = $message->getBody();
61: $params['html'] = $message->getHtmlBody();
62: $from = $message->getFrom();
63: $params['from_email'] = key($from);
64: $params['from_name'] = $from[$params['from_email']];
65: $recipients = $message->getHeader('To');
66: $params['to'] = array();
67: foreach ($recipients as $email => $name) {
68: $recipient = array('email' => $email);
69: if (!empty($name)) {
70: $recipient['name'] = $name;
71: }
72: $params['to'][] = $recipient;
73: }
74:
75: return $params;
76: }
77:
78: 79: 80: 81: 82: 83:
84: private function callApi(array $params)
85: {
86: $params = array('message' => $params);
87: $params['key'] = $this->apiKey;
88: $params = json_encode($params);
89:
90: $method = '/messages/send';
91:
92: $ch = curl_init();
93: curl_setopt($ch, CURLOPT_USERAGENT, 'Mandrill-Nette-PHP/0.2');
94: curl_setopt($ch, CURLOPT_POST, true);
95: curl_setopt($ch, CURLOPT_HEADER, false);
96: curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
97: curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
98: curl_setopt($ch, CURLOPT_TIMEOUT, 600);
99: curl_setopt($ch, CURLOPT_URL, $this->apiEndpoint.$method.'.'
100: .$this->apiFormat);
101: curl_setopt($ch, CURLOPT_HTTPHEADER, array(
102: 'Content-Type: application/'.$this->apiFormat)
103: );
104: curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
105:
106: if (curl_error($ch)) {
107: throw new MandrillException(
108: 'curl error while calling '.$method.': '. curl_error($ch)
109: );
110: }
111:
112: $response = curl_exec($ch);
113: $info = curl_getinfo($ch);
114: $result = json_decode($response, true);
115: if ($result === NULL) {
116: throw new MandrillException('Unable to parse JSON response');
117: }
118: if ($info['http_code'] != 200) {
119: throw new MandrillException('Error '.$info['http_code']);
120: }
121:
122: curl_close($ch);
123:
124: return $result;
125: }
126: }