2017-01-23 112 views
1

我有這個,而垂耳這給了我已經登錄今天的所有用戶:PHP while循環內容到電子郵件與PHP梅勒

<?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('[email protected]','Hello'); 
$mail->AddReplyTo("[email protected]","Hello"); 
$mail->Subject = $subject; 
$mail->MsgHTML($message); 
$mail->Send(); 
} 

,但我需要知道我怎麼不能打印查詢到該電子郵件的結果是什麼,我有,但不知道下一步去哪裏...

$email = ("[email protected]"); 
$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); 

任何幫助將是偉大的。

回答

2

好,而不是通過使用循環內的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標記,因爲它只會使事情更加複雜。

+0

謝謝,這完美適合我的目的! – PHPNewbie

+0

如何在每行之後添加一個換行符以使其在電子郵件中更易於閱讀? – PHPNewbie

+0

消息中有換行符,你可以看到我添加的'「\ n」。這可能是因爲某些不符合標準的電子郵件客戶端堅持使用MS-Windows樣式的換行符,但這是發送郵件時無法預測的,因此使用'「\ r \ n」相反。更可能你仍然發送HTML格式的電子郵件(爲什麼......)。在這種情況下,請按照您自己的示例進行操作,並在您的消息中添加html樣式線條('
')。 – arkascha