我试图让我的联系人发送的电子邮件(使用 PHPMailer)以一个漂亮的 html 模板(实际上是 phtml)发送。
什么有效:我收到了 html 模板,所以传输没有问题
什么 不起作用:变量(消息、电话号码等)没有反映在我的 html 模板的正文中。我在 html 模板中尝试了几件事,但没有成功: <?= htmlspecialchars($message) ?>
和 #message#
和 <?php echo$_POST['message'] ?>
问题是什么?
谢谢,
这是 PHPMailer 代码:
<?php
require 'PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->CharSet = 'utf-8';
$body = file_get_contents('htmlemail.phtml');
//Enable SMTP debugging.
$mail->SMTPDebug = false;
//Set PHPMailer to use SMTP.
$mail->isSMTP();
//Set SMTP host name
$mail->Host = "smtp.sendgrid.net";
//Set this to true if SMTP host requires authentication to send email
$mail->SMTPAuth = true;
//Provide username and password
$mail->Username = "";
$mail->Password = "";
//If SMTP requires TLS encryption then set it
$mail->SMTPSecure = "tls";
//Set TCP port to connect to
$mail->Port = 587;
$mail->From = $_POST['email'];
$mail->FromName = $_POST['first_name'] . " " . $_POST['last_name'];
$mail->addAddress("@gmail.com");
//CC and BCC
$mail->addCC("");
$mail->addBCC("");
$mail->isHTML(true);
$mail->Subject = "Nouveau message depuis ";
$mail->MsgHTML($body);
$response = array();
if(!$mail->send()) {
$response = array('message'=>"Mailer Error: " . $mail->ErrorInfo, 'status'=> 0);
} else {
$response = array('message'=>"Message has been sent successfully", 'status'=> 1);
}
/* send content type header */
header('Content-Type: application/json');
/* send response as json */
echo json_encode($response);
?>
原文由 Greg 发布,翻译遵循 CC BY-SA 4.0 许可协议
使用 ob_start
要么
您还可以使用模板方法生成电子邮件正文以供多次使用。
例如
在您的 html 模板中,像这样分配变量:
然后在调用您的 phpmailer 之前,创建一个数组来处理电子邮件正文:
最后,使用 phpmailer …
这样您的电子邮件将在正文中包含您需要的所有动态内容。