PHP使用PHP Mailer将内容循环到电子邮件中

时间:2017-01-23 13:18:19

标签: php phpmailer

我有这个,而lop给了我今天登录的所有用户:

<?php while ($users = $stmt->fetch(PDO::FETCH_ASSOC)) : ?>
    <p><?php echo $users['lastLogIn'];?> - <?php  echo $users['userName']; ?></p>
<?php endwhile; ?>

我想每天通过电子邮件发送一次这样的结果,因此也有发送邮件功能:

function send_mail($email,$message,$subject){                       
require_once('mailer/class.phpmailer.php');
$mail = new PHPMailer();
$mail->IsSMTP(); 
$mail->SMTPDebug  = 0;                     
$mail->SMTPAuth   = false;                  
$mail->SMTPSecure = "";                 
$mail->Host       = "10.10.10.10";      
$mail->Port       = 25;            
$mail->AddAddress($email);
$mail->Username="Anonymous";  
$mail->Password="Anonymous";            
$mail->SetFrom('noreply@email.co.uk','Hello');
$mail->AddReplyTo("noreply@email.co.uk","Hello");
$mail->Subject    = $subject;
$mail->MsgHTML($message);
$mail->Send();
}

但我需要知道如何将查询结果打印到电子邮件中这就是我所拥有的但不知道下一步该去哪...

$email = ("email@email.co.uk");
$message= "        
    Hello, $email
   <br /><br />
   Please find a list of users below who logged in today : 
   <br /><br />
   I want the while loop content here";
$subject = "Daile User Log";

send_mail($email,$message,$subject); 

任何帮助都会很棒。

1 个答案:

答案 0 :(得分:3)

好吧,不是通过在循环中使用echo语句将创建的字符串发送到请求的浏览器,而是将它们连接到一个变量,然后您可以在填充消息内容时使用该变量:

<?php 
$listOfUsers = '';
while ($user = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $listOfUsers .= sprintf("%s - %s\n", $user['lastLogIn'], $user['userName']);
}

$message = <<<EOT
Hello ${email}, 
please find a list of users below who logged in today : 

${listOfUsers}
EOT;

注意:我从消息内容中删除了html标记,因为它只会使事情变得更复杂。