-
Notifications
You must be signed in to change notification settings - Fork 0
/
Mailer.php
102 lines (90 loc) · 2.23 KB
/
Mailer.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
<?php
namespace bsadnu\mailgunmailer;
use Yii;
use yii\base\InvalidConfigException;
use yii\mail\BaseMailer;
use \Mailgun\Mailgun;
/**
* Mailer implements a mailer based on Mailgun.
*
* To use Mailer, you should configure it in the application configuration like the following,
*
* ~~~
* 'components' => [
* ...
* 'mailer' => [
* 'class' => 'bsadnu\mailgunmailer\Mailer',
* 'key' => 'key-example',
* 'domain' => 'mg.example.com',
* ],
* ...
* ],
* ~~~
*
* To send an email, you may use the following code:
*
* ~~~
* Yii::$app->mailer->compose('contact/html', ['contactForm' => $form])
* ->setFrom('from@domain.com')
* ->setTo($form->email)
* ->setSubject($form->subject)
* ->send();
* ~~~
* @author Stanislav Bannikov <bsadnu@gmail.com>
*/
class Mailer extends BaseMailer
{
/**
* @var string message default class name.
*/
public $messageClass = 'bsadnu\mailgunmailer\Message';
/**
* @var string Mailgun API credentials.
*/
public $key;
/**
* @var string Mailgun domain.
*/
public $domain;
/**
* @var Mailgun Mailgun instance.
*/
private $_mailgun;
/**
* @return Mailgun Mailgun instance.
*/
public function getMailgun()
{
if (!is_object($this->_mailgun)) {
$this->_mailgun = $this->createMailgun();
}
return $this->_mailgun;
}
/**
* @inheritdoc
*/
protected function sendMessage($message)
{
Yii::info('Sending email', __METHOD__);
$this->getMailgun()->post("{$this->domain}/messages",
$message->getMessageBuilder()->getMessage(),
$message->getMessageBuilder()->getFiles());
return true;
}
/**
* Creates Mailgun instance.
*
* @return Mailgun Mailgun instance.
* @throws InvalidConfigException if required params are not set.
*/
protected function createMailgun()
{
if (!$this->key) {
throw new InvalidConfigException('Mailer::key must be set.');
}
if (!$this->domain) {
throw new InvalidConfigException('Mailer::domain must be set.');
}
return new Mailgun($this->key);
}
}