PHP Sendmail - 使用PHP变量的HTML邮件

时间:2018-05-08 23:31:26

标签: php html phpmailer

每次用户在我们的应用上发布作业时,我都会尝试发送一封html电子邮件。

下面是我们的php函数,它接受一个参数'job_title',我们希望将其包含在发送的HTML电子邮件中:

require('phpmailer/PHPMailer.php');
require('phpmailer/Exception.php');
require('phpmailer/SMTP.php');
require('phpmailer/POP3.php');
require('phpmailer/OAuth.php');

function sendJobPostedEmail($to, $job_title) {

$mail = new PHPMailer\PHPMailer\PHPMailer();
$mail->isSMTP();
$mail->Host       = 'smtp.gmail.com';
$mail->Port       = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth   = true;
$mail->Username   = 'xxxxxx';
$mail->Password   = 'xxxxxx';
$mail->SetFrom('xxxxxx', 'xxxxxx');
$mail->addAddress($to, 'ToEmail');
$mail->IsHTML(true);

$mail->Subject = 'Your job has been posted!';
$mail->Body    = file_get_contents("jobposted-email.php");

$mail->send();

return true;

}

以下是发送的电子邮件中的html片段:

<p class="lead tm"><?php echo $job_title; ?></p>

电子邮件发送正常,但不打印变量$ job_title。为什么我的变量没有被传递到包含的'jobposted_email.php'?

1 个答案:

答案 0 :(得分:0)

尝试在邮件功能之前放置 ob_start(); ,然后使用 include&#39; jobposted-email.php&#39;;

之后,将内容存储在 $ body = ob_get_contents(); 发送电子邮件时,执行 ob_end_Clean();

使用您的代码的示例。让我知道它是否有帮助:

require('phpmailer/PHPMailer.php');
require('phpmailer/Exception.php');
require('phpmailer/SMTP.php');
require('phpmailer/POP3.php');
require('phpmailer/OAuth.php');

ob_start();
include 'jobposted-email.php';
$body = ob_get_contents();

function sendJobPostedEmail($to, $job_title) {

$mail = new PHPMailer\PHPMailer\PHPMailer();
$mail->isSMTP();
$mail->Host       = 'smtp.gmail.com';
$mail->Port       = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth   = true;
$mail->Username   = 'xxxxxx';
$mail->Password   = 'xxxxxx';
$mail->SetFrom('xxxxxx', 'xxxxxx');
$mail->addAddress($to, 'ToEmail');
$mail->IsHTML(true);

$mail->Subject = 'Your job has been posted!';
$mail->Body    = $body;

$mail->send();

ob_end_Clean();

return true;

}