首页 > 解决方案 > 获取邮件正文的数据: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.';
} ?>

标签: phpemailphpmailer

解决方案


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循环内。

或者,如果您需要跟踪每个单独的邮件发送状态,则保留状态数组。继续将消息推送到状态数组中。


推荐阅读