如何将while循环添加到电子邮件模板中

时间:2016-05-27 21:28:39

标签: php email phpmailer email-integration

我有一个看起来像这样的电子邮件模板 - >它只是一个例子

require 'PHPMailerAutoload.php';

$mail = new PHPMailer;

$mail->isSMTP();                                      // Set mailer to use SMTP
$mail->Host = 'support.example.com';  // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = 'support@example.com';                 // SMTP username
$mail->Password = '******';                           // SMTP password
$mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
$mail->Port = 25;                                    // TCP port to connect to

$mail->setFrom('support@example.com', 'example Inc.');
$mail->addAddress($to);     // Add a recipient
$mail->addReplyTo('support@example.com', 'Support');
$mail->addCC($to);
$mail->addBCC($to);

$mail->isHTML(true);                                 

$mail->Subject = "$name has sent you a request";
$mail->Body    = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns:v="urn:schemas-microsoft-com:vml" style="width: 100%;min-width: 100%;">
    <head> Head content here</head>

    <body>
  body content goes here
</body>
</html>'; 

$mail->AltBody = 'Please Upgrade Your Browser to view this email';

if(!$mail->send()) {
    header('location:https://www.example.com/404.shtml?error-in-sending-email');
}

现在我想要的是使用php while循环来显示数据库中的一些数据到电子邮件&amp;将其发送给用户

我尝试使用这样'.while($fetch = mysqli_fetch_array($content)){.' '.}.' 但这给了我错误什么是最好的方式?

1 个答案:

答案 0 :(得分:0)

你不能在字符串文字中有一个循环。您需要逐个循环并生成HTML字符串。例如:

$html = '
    <html>
        <head>
            <!-- head stuff -->
        </head>
        <body>';

while ( $row = mysql_fetch_assoc( $res ) ) {
    $html .= '<p>' . $row['something'] . '</p>';
}

$html .= '
        </body>
    </html>';

但很明显,代码很难看,难以理解,也是维护或修改的噩梦。您可能希望切换到alternative control structure syntax和一些output buffering

ob_start();

?>
<html>
    <head>
        <!-- head stuff -->
    </head>
    <body>
        <?php while ( $row = mysql_fetch_assoc( $res ) ): ?>
            <p><?php echo $res['something']; ?></p>
        <?php endwhile; ?>
    </body>
</html>
<?php

$html = ob_get_clean();