Skip to content

Commit

Permalink
Ability to send html mails
Browse files Browse the repository at this point in the history
  • Loading branch information
eluhr committed Feb 1, 2022
1 parent a433c28 commit c9ee32a
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
2 changes: 2 additions & 0 deletions src/Module.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
* @property string $defaultRoute
* @property string $frontendLayout
* @property string $backendLayout
* @property bool $sendHtmlMails
*/
class Module extends \yii\base\Module
{
Expand All @@ -19,6 +20,7 @@ class Module extends \yii\base\Module
public $defaultRoute = 'backend';
public $frontendLayout = '//main';
public $backendLayout = '@backend/views/layouts/box';
public $sendHtmlMails = false;

public function beforeAction($action)
{
Expand Down
37 changes: 36 additions & 1 deletion src/models/ContactLog.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
class ContactLog extends BaseContactLog
{

public static $moduleId = 'contact';

public function behaviors()
{
$behaviors = parent::behaviors();
Expand Down Expand Up @@ -64,6 +66,9 @@ public function sendMessage()
$message->setTo($to);
$message->setSubject($this->emailSubject);
$message->setTextBody($this->dataValue2txt(Json::decode($this->json)));
if (Yii::$app->getModule(self::$moduleId)->sendHtmlMails) {
$message->setHtmlBody($this->dataValue2Html(Json::decode($this->json)));
}

return $message->send();
}
Expand Down Expand Up @@ -94,11 +99,41 @@ private function dataValue2txt($data, $level = 0)
} else {
$valueText = trim($value);
}
$text .= $prefix . trim($key) . ': ' . $valueText . "\n";
$text .= $prefix . trim($this->labelFromAttribute($key)) . ': ' . $valueText . "\n";

}

return $text;

}

/**
* @param array $data
* @return void
*/
private function dataValue2Html(array $data = []): string
{
if (!is_array($data)) {
return '';
}
$rows = '';
foreach ($data as $attribute => $value) {
if (is_array($value)) {
$row = $this->dataValue2Html($value);
} else {
$row = '<tr><td><b>' . $this->labelFromAttribute($attribute) . '</b></td><td>' . $value . '</td></tr>';
}
$rows .= $row;
}
return '<table>' . $rows . '</table>';
}

private static $_schemaCache = [];
private function labelFromAttribute(string $attribute)
{
if (empty(static::$_schemaCache)) {
static::$_schemaCache = Json::decode($this->contactTemplate->form_schema);
}
return static::$_schemaCache['properties'][$attribute]['title'] ?? $attribute;
}
}

0 comments on commit c9ee32a

Please sign in to comment.