Я пытаюсь отправить HTML-шаблон электронной почты с подтверждением заказа (order_confirmation.html.php
) из моего бэкэнда Apache (7.2), в котором присутствуют теги PHP для условного рендеринга, который отправляется с библиотекой phpmailer
(^6.0.2
). Я отправляю это в теле письма, но операторы php if не интерпретируются так, как я ожидал. Например, эти строки из файла шаблона отображаются, даже если ключ $data['order_shipping']
не существует:
<? if ($data['order_shipping']) { ?>
<tr>
<td>
<div style = "color:#808080;font-size:12px;line-height:20px;font-weight:bold;font-family:Arial,sans-serif;">Ship To</div>
<div style = "padding-bottom:3px;font-size:12px;color:#000;font-family:Helvetica,Arial,sans-serif;"><?= stripslashes($data['order_shipping']['address_line_1']); ?></div>
<? if ($data['order_shipping']['address_line_2']) { ?>
<div style = "padding-bottom:3px;font-size:12px;color:#000;font-family:Helvetica,Arial,sans-serif;"><?= stripslashes($data['order_shipping']['address_line_2']); ?></div>
<? } ?>
<div style = "padding-bottom:3px;font-size:12px;color:#000;font-family:Helvetica,Arial,sans-serif;"><?= stripslashes($data['order_shipping']['city']).", ".stripslashes($data['order_shipping']['state'])." ".stripslashes($data['order_shipping']['zip']); ?></div>
<div style = "padding-bottom:3px;font-size:12px;color:#000;font-family:Helvetica,Arial,sans-serif;"><span style = "font-weight:bold;">Phone:</span> <?= stripslashes($data['order_shipping']['phone']); ?></div>
<div style = "padding-bottom:3px;font-size:12px;color:#000;font-family:Helvetica,Arial,sans-serif;"><span style = "font-weight:bold;">Requested ETA:</span> <?= stripslashes($data['order_shipping']['requested_eta']); ?></div>
</td>
</tr>
<? } ?>
Вот отрендеренное письмо:
И мой файл SystemMailer.php
, в котором используется библиотека PHPMailer
:
class SystemMailer extends Controller {
var $container;
function __construct($container) {
$this->container = $container;
parent::__construct($container);
$this->mailer = new \PHPMailer\PHPMailer\PHPMailer;
}
function clearAddresses() {
$this->mailer->clearAddresses();
}
function initEmail($email_config) {
$this->log->debug("SystemMailer", "initEmail");
$this->log->debug("SystemMailer", "adding address");
$this->log->debug("SystemMailer", $email_config['to_email']);
if (is_array($email_config['to_email'])) {
foreach ($email_config['to_email'] AS $email) {
$this->mailer->addAddress($email);
$this->container->log->debug("addAddress", $email);
}
} else {
$this->mailer->addAddress($email_config['to_email']);
}
if (is_array($email_config['bcc_email'])) {
foreach ($email_config['bcc_email'] AS $email) {
$this->mailer->addBCC($email);
}
} else {
$this->mailer->addBCC($email_config['bcc_email']);
}
if ($email_config['from_name'] && $email_config['from_email']) {
$this->mailer->setFrom($email_config['from_email'], $email_config['from_name']);
} elseif ($email_config['from_email']) {
$this->mailer->setFrom($email_config['from_email']);
}
if ($email_config['reply_to_name'] && $email_config['reply_to_email']) {
$this->mailer->addReplyTo($email_config['reply_to_email'], $email_config['reply_to_name']);
} elseif ($email_config['reply_to_email']) {
$this->mailer->addReplyTo($email_config['reply_to_email']);
}
$this->mailer->isHTML(true); // Set email format to HTML
$this->mailer->Subject = $email_config['subject'];
// the following must be done in this order.
// 1) add HTML content to email
// 2) add TEXT content to email
if ($email_config['html_content']) {
$this->mailer->Body = $email_config['html_content'];
}
if ($email_config['text_email']) {
$this->mailer->AltBody = $email_config['text_email'];
}
}
function sendEmail() {
// smtp auth
ob_start();
$this->mailer->SMTPDebug = 2;
$this->mailer->isSMTP(); // Set mailer to use SMTP
$this->mailer->SMTPAuth = true; // Enable SMTP authentication
$this->mailer->Host = $this->config->get_value('smtp_host_1'); // Specify main and backup SMTP servers
$this->mailer->Username = $this->config->get_value('smtp_user_1'); // SMTP username
$this->mailer->Password = $this->config->get_value('smtp_password_1'); // SMTP password
$this->mailer->SMTPSecure = $this->config->get_value('smtp_encryption_1'); // SMTP encryption
$this->mailer->Port = $this->config->get_value('smtp_port_1'); // TCP port to connect to
$success = $this->mailer->send();
$output = ob_get_contents();
ob_end_clean();
if ( ! $success ) {
$this->log->debug("SystemMailer", "Error sending mail");
$this->log->debug("SystemMailer", $this->mailer->ErrorInfo);
$this->log->debug("SystemMailer : output", $output);
return false;
} else {
$this->log->debug("SystemMailer", "Sent mail");
return true;
}
}
}
Есть строки кода php, которые отображаются. Например, для устранения неполадок я добавил эту строку в шаблон электронной почты; который правильно отображается в электронном письме:
Changes: <?= count($data['changes']) ? "true" : "false" ?>
🤔 А знаете ли вы, что...
С PHP можно работать с файлами и директориями на сервере.
Я использую Docker/docker-compose для контейнеризации приложения. Итак, вы хотите добавить эту строку в Dockerfile
, которая используется для создания изображения:
RUN sed -i "s/short_open_tag = Off/short_open_tag = On/" "$PHP_INI_DIR/php.ini"
Используйте эту ссылку GitHub в качестве ссылки