1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Tylercd100\Monolog\Handler; |
4
|
|
|
|
5
|
|
|
use Exception; |
6
|
|
|
use Monolog\Logger; |
7
|
|
|
use Monolog\Handler\MailHandler; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* MailgunHandler uses cURL to send the emails to the Mailgun API |
11
|
|
|
* |
12
|
|
|
* @author Tyler Arbon <[email protected]> |
13
|
|
|
*/ |
14
|
|
|
class MailgunHandler extends MailHandler |
15
|
|
|
{ |
16
|
|
|
protected $message; |
17
|
|
|
protected $apiKey; |
18
|
|
|
|
19
|
6 |
|
public function __construct($to, $subject, $from, $token, $domain, $level = Logger::CRITICAL, $bubble = true, $host = 'api.mailgun.net', $version = 'v3') |
20
|
|
|
{ |
21
|
6 |
|
if ($version !== 'v3') { |
22
|
3 |
|
throw new Exception("Version '{$version}' is not supported"); |
23
|
|
|
} |
24
|
|
|
|
25
|
3 |
|
$this->to = $to; |
|
|
|
|
26
|
3 |
|
$this->subject = $subject; |
|
|
|
|
27
|
3 |
|
$this->from = $from; |
|
|
|
|
28
|
3 |
|
$this->host = $host; |
|
|
|
|
29
|
3 |
|
$this->version = $version; |
|
|
|
|
30
|
3 |
|
$this->domain = $domain; |
|
|
|
|
31
|
3 |
|
$this->token = $token; |
|
|
|
|
32
|
|
|
|
33
|
3 |
|
parent::__construct($level, $bubble); |
34
|
3 |
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* {@inheritdoc} |
38
|
|
|
*/ |
39
|
|
|
protected function send($content, array $records) |
40
|
|
|
{ |
41
|
|
|
$auth = base64_encode("api:".$this->token); |
42
|
|
|
|
43
|
|
|
$fields = http_build_query([ |
44
|
|
|
'from' => $this->from, |
45
|
|
|
'to' => $this->to, |
46
|
|
|
'subject' => $this->subject, |
47
|
|
|
'text' => $content |
48
|
|
|
]); |
49
|
|
|
|
50
|
|
|
$ch = curl_init(); |
51
|
|
|
|
52
|
|
|
curl_setopt($ch, CURLOPT_URL, "https://{$this->host}/{$this->version}/{$this->domain}/messages"); |
53
|
|
|
curl_setopt($ch, CURLOPT_POST, 1); |
54
|
|
|
curl_setopt($ch, CURLOPT_HTTPHEADER, [ |
55
|
|
|
"Authorization: Basic ".$auth |
56
|
|
|
]); |
57
|
|
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); |
58
|
|
|
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); |
59
|
|
|
|
60
|
|
|
curl_exec($ch); |
61
|
|
|
curl_close($ch); |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
|
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: