使用PHPMailer和html模板发送HTML电子邮件

Gre*_*reg 1 html php phpmailer

我正在尝试从我的联系人(使用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);

?>
Run Code Online (Sandbox Code Playgroud)

Oni*_*sha 7

使用ob_start

ob_start();
include 'htmlemail.php';
$body = ob_get_clean();
Run Code Online (Sandbox Code Playgroud)

要么

您还可以使用模板方法生成多个用途的电子邮件正文.

例如

在您的html模板中,让变量分配如下:

感谢您{NAME}与我们联系.

您的电话号码是{PHONE}

然后在调用phpmailer之前,创建一个数组来处理电子邮件正文:

$email_vars = array(
    'name' => $_POST['name'],
    'phone' => $_POST['phone'],
);
Run Code Online (Sandbox Code Playgroud)

最后,用phpmailer ...

$body = file_get_contents('htmlemail.phtml');

if(isset($email_vars)){
    foreach($email_vars as $k=>$v){
        $body = str_replace('{'.strtoupper($k).'}', $v, $body);
    }
}
Run Code Online (Sandbox Code Playgroud)

这样,您的电子邮件将包含您在正文中所需的所有动态内容.