【问题标题】:Get data for mail body: phpmailer获取邮件正文的数据:phpmailer
【发布时间】:2019-10-23 03:03:50
【问题描述】:

我想通过 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.';
} ?>

【问题讨论】:

  • 欢迎来到 SO!当您提出问题时,请尝试添加最少的内容:输入样本、预期输出样本、您尝试了什么、研究以及您在哪里堆叠。你的问题是哪一个?
  • 看看the mailing list example provided with PHPMailer。它可以满足您的要求。

标签: php email phpmailer


【解决方案1】:
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循环内。

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

【讨论】:

  • 与此相关的一个主要问题是,您不会在每次循环中清除任何现有的地址;在send() 之后致电clearAddresses();否则,您最终会发送许多重复邮件并有许多恼火的收件人。设置$mail-&gt;SMTPKeepAlive = true; 会使发送速度更快。
猜你喜欢
  • 1970-01-01
  • 2012-11-28
  • 1970-01-01
  • 2019-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-28
相关资源
最近更新 更多