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
<?php
namespace yii\debug\panels;
use Yii;
use yii\base\Event;
use yii\debug\models\search\Mail;
use yii\debug\Panel;
use yii\mail\BaseMailer;
use yii\helpers\FileHelper;
/**
* Debugger panel that collects and displays the generated emails.
*/
class MailPanel extends Panel
{
/**
* @var string path where all emails will be saved. should be an alias.
*/
public $mailPath = '@runtime/debug/mail';
/**
* @var array current request sent messages
*/
private $_messages = [];
public function init()
{
parent::init();
Event::on(BaseMailer::className(), BaseMailer::EVENT_AFTER_SEND, function ($event) {
$message = $event->message->getSwiftMessage();
$textBody = $message->getBody();
$fileName = $event->sender->generateMessageFileName();
FileHelper::createDirectory(Yii::getAlias($this->mailPath));
file_put_contents(Yii::getAlias($this->mailPath) . '/' . $fileName, $message->toString());
$this->_messages[] = [
'isSuccessful' => $event->isSuccessful,
'time' => $message->getDate(),
'headers' => $message->getHeaders(),
'from' => $this->convertParams($message->getFrom()),
'to' => $this->convertParams($message->getTo()),
'reply' => $this->convertParams($message->getReplyTo()),
'cc' => $this->convertParams($message->getCc()),
'bcc' => $this->convertParams($message->getBcc()),
'subject' => $message->getSubject(),
'body' => $textBody,
'charset' => $message->getCharset(),
'file' => $fileName,
];
});
}
public function getName()
{
return 'Mail';
}
public function getSummary()
{
return Yii::$app->view->render('panels/mail/summary', ['panel' => $this, 'mailCount' => count($this->data)]);
}
public function getDetail()
{
$searchModel = new Mail();
$dataProvider = $searchModel->search(Yii::$app->request->get(), $this->data);
return Yii::$app->view->render('panels/mail/detail', [
'panel' => $this,
'dataProvider' => $dataProvider,
'searchModel' => $searchModel
]);
}
public function save()
{
return $this->getMessages();
}
/**
* Returns info about messages of current request. Each element is array holding
* message info, such as: time, reply, bc, cc, from, to and other.
* @return array messages
*/
public function getMessages()
{
return $this->_messages;
}
private function convertParams($attr)
{
if (is_array($attr)) {
$attr = implode(', ', array_keys($attr));
}
return $attr;
}
}