1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace ByJG\Mail\Wrapper; |
4
|
|
|
|
5
|
|
|
use ByJG\Mail\Envelope; |
6
|
|
|
use ByJG\Mail\Exception\MailApiException; |
7
|
|
|
use ByJG\Util\MultiPartItem; |
8
|
|
|
use ByJG\Util\WebRequest; |
9
|
|
|
|
10
|
|
|
class MailgunApiWrapper extends PHPMailerWrapper |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* @return \ByJG\Util\WebRequest |
14
|
|
|
*/ |
15
|
1 |
|
public function getRequestObject() |
16
|
|
|
{ |
17
|
1 |
|
$domainName = $this->uri->getHost(); |
18
|
1 |
|
$request = new WebRequest("https://api.mailgun.net/v3/$domainName/messages"); |
19
|
1 |
|
$request->setCredentials('api', $this->uri->getUsername()); |
20
|
|
|
|
21
|
1 |
|
return $request; |
22
|
|
|
} |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* malgun://api:APIKEY@DOMAINNAME |
26
|
|
|
* |
27
|
|
|
* @param Envelope $envelope |
28
|
|
|
* @return bool |
29
|
|
|
* @throws \ByJG\Mail\Exception\MailApiException |
30
|
|
|
*/ |
31
|
4 |
|
public function send(Envelope $envelope) |
32
|
|
|
{ |
33
|
4 |
|
$this->validate($envelope); |
34
|
|
|
|
35
|
|
|
$message = [ |
36
|
4 |
|
new MultiPartItem('from', $envelope->getFrom()), |
37
|
4 |
|
new MultiPartItem('subject', $envelope->getSubject()), |
38
|
4 |
|
new MultiPartItem('html', $envelope->getBody()), |
39
|
4 |
|
new MultiPartItem('text', $envelope->getBodyText()), |
40
|
4 |
|
]; |
41
|
|
|
|
42
|
|
|
|
43
|
4 |
|
foreach ((array)$envelope->getTo() as $to) { |
44
|
4 |
|
$message[] = new MultiPartItem('to', $to); |
45
|
4 |
|
} |
46
|
|
|
|
47
|
4 |
|
foreach ((array)$envelope->getBCC() as $bcc) { |
48
|
3 |
|
$message[] = new MultiPartItem('bcc', $bcc); |
49
|
4 |
|
} |
50
|
|
|
|
51
|
4 |
|
if (!empty($envelope->getReplyTo())) { |
52
|
4 |
|
$message[] = new MultiPartItem('h:Reply-To', $envelope->getReplyTo()); |
53
|
4 |
|
} |
54
|
|
|
|
55
|
4 |
|
foreach ((array)$envelope->getCC() as $cc) { |
56
|
3 |
|
$message[] = new MultiPartItem('cc', $cc); |
57
|
4 |
|
} |
58
|
|
|
|
59
|
4 |
|
foreach ((array)$envelope->getAttachments() as $name => $attachment) { |
60
|
2 |
|
$message[] = new MultiPartItem( |
61
|
2 |
|
$attachment['disposition'], |
62
|
2 |
|
file_get_contents($attachment['content']), |
63
|
2 |
|
$name, |
64
|
2 |
|
$attachment['content-type'] |
65
|
2 |
|
); |
66
|
4 |
|
} |
67
|
|
|
|
68
|
4 |
|
$request = $this->getRequestObject(); |
69
|
4 |
|
$result = $request->postMultiPartForm($message); |
70
|
4 |
|
$resultJson = json_decode($result, true); |
71
|
4 |
|
if (!isset($resultJson['id'])) { |
72
|
|
|
throw new MailApiException('Mailgun: ' . $resultJson['message']); |
73
|
|
|
} |
74
|
|
|
|
75
|
4 |
|
return true; |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|