Skip to content

Commit c9ee32a

Browse files
committed
Ability to send html mails
1 parent a433c28 commit c9ee32a

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

src/Module.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
* @property string $defaultRoute
99
* @property string $frontendLayout
1010
* @property string $backendLayout
11+
* @property bool $sendHtmlMails
1112
*/
1213
class Module extends \yii\base\Module
1314
{
@@ -19,6 +20,7 @@ class Module extends \yii\base\Module
1920
public $defaultRoute = 'backend';
2021
public $frontendLayout = '//main';
2122
public $backendLayout = '@backend/views/layouts/box';
23+
public $sendHtmlMails = false;
2224

2325
public function beforeAction($action)
2426
{

src/models/ContactLog.php

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818
class ContactLog extends BaseContactLog
1919
{
2020

21+
public static $moduleId = 'contact';
22+
2123
public function behaviors()
2224
{
2325
$behaviors = parent::behaviors();
@@ -64,6 +66,9 @@ public function sendMessage()
6466
$message->setTo($to);
6567
$message->setSubject($this->emailSubject);
6668
$message->setTextBody($this->dataValue2txt(Json::decode($this->json)));
69+
if (Yii::$app->getModule(self::$moduleId)->sendHtmlMails) {
70+
$message->setHtmlBody($this->dataValue2Html(Json::decode($this->json)));
71+
}
6772

6873
return $message->send();
6974
}
@@ -94,11 +99,41 @@ private function dataValue2txt($data, $level = 0)
9499
} else {
95100
$valueText = trim($value);
96101
}
97-
$text .= $prefix . trim($key) . ': ' . $valueText . "\n";
102+
$text .= $prefix . trim($this->labelFromAttribute($key)) . ': ' . $valueText . "\n";
98103

99104
}
100105

101106
return $text;
102107

103108
}
109+
110+
/**
111+
* @param array $data
112+
* @return void
113+
*/
114+
private function dataValue2Html(array $data = []): string
115+
{
116+
if (!is_array($data)) {
117+
return '';
118+
}
119+
$rows = '';
120+
foreach ($data as $attribute => $value) {
121+
if (is_array($value)) {
122+
$row = $this->dataValue2Html($value);
123+
} else {
124+
$row = '<tr><td><b>' . $this->labelFromAttribute($attribute) . '</b></td><td>' . $value . '</td></tr>';
125+
}
126+
$rows .= $row;
127+
}
128+
return '<table>' . $rows . '</table>';
129+
}
130+
131+
private static $_schemaCache = [];
132+
private function labelFromAttribute(string $attribute)
133+
{
134+
if (empty(static::$_schemaCache)) {
135+
static::$_schemaCache = Json::decode($this->contactTemplate->form_schema);
136+
}
137+
return static::$_schemaCache['properties'][$attribute]['title'] ?? $attribute;
138+
}
104139
}

0 commit comments

Comments
 (0)