php - 获取邮件正文的数据:phpmailer
问题描述
我想通过 phpmailer 发送邮件,我想从数据库中获取带有循环的邮件正文的名称,但我的代码不起作用。它不断为每封邮件获取相同的名称。这是我的代码:
<?php //Library require("phpmailer/classes/class.phpmailer.php");
//Database
$server = "localhost";
$username = "mydatabase_admin";
$password = "localadmin123";
$database = "mydatabase";
//Connect to database
$dbConnection = mysqli_connect($server, $username, $password, $database);
//Check connection
if ($dbConnection -> connect_error) {
echo "Connection Failed";
die ($dbConnection -> connect_error);
}
//Select database and data
$sql = "SELECT * FROM userdata";
$result = $dbConnection -> query($sql);
//Mailing
//Sender information
$mail = new PHPMailer();
$mail->SMTPDebug = 0;
//Use SMTP
$mail->IsSMTP();
$mail->SMTPAuth = true;
//SMTP Server
$mail->Host = "ssl://smtp.gmail.com";
$mail->Port = 465;
//SMTP Account
$mail->Username = "my_mail@gmail.com";
$mail->Password = "********";
//Automated Mail
$mail->SetFrom('tphp43598@gmail.com', 'Admin');
//Recipient info
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc())
{
$mail->AddAddress($row["Email"]);
$mail->Subject = "Product Review Reminder";
$mail->Body = "Hi ". $row["Full Name"] .",". "\n \nJust a reminder that you need to review the product coded ". $row["Product Handled"] . ".\n" . "Thank You";
}
}
//Output shown if(!$mail->Send()) {
echo 'Message was not sent.';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo "\n" . 'Message has been sent.';
} ?>
解决方案
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc())
{
$mail->AddAddress($row["Email"]);
$mail->Subject = "Product Review Reminder";
$mail->Body = "Hi ". $row["Full Name"] .",". "\n \nJust a reminder that you need to review the product coded ". $row["Product Handled"] . ".\n" . "Thank You";
if(!$mail->Send()) {
echo 'Message was not sent.';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo "\n" . 'Message has been sent.';
}
}
}
您在 while 循环外调用 sendmail() 函数,您将获取 name 变量,以最后一条记录为准。保持在while循环内。
或者,如果您需要跟踪每个单独的邮件发送状态,则保留状态数组。继续将消息推送到状态数组中。
推荐阅读
- c# - 如何在 node.js 或 C#/.NET 中发送消息处理通知电子邮件?
- javascript - 从表格中出来的附加 div
- javascript - 单击新的 Collapsible 后关闭其他打开的 Collapsible
- bash - 为什么新行最后添加到变量中?
- xml - 如何使 Azure API 管理(API 网关)CORS 策略动态化?
- android - 如何在颤动中阅读“旧”sqlite?
- node.js - Swagger Express 续集
- javascript - 如何指定 cookie 在整个站点上显示直到关闭?
- java - "No Metrics " in Flink webUI
- c# - 函数式语言中中介模式的等价物是什么?