如何将PHP邮件发送到通过MySQL查询接收的多个电子邮件地址 [英] How to send PHP mailer to multiple email addresses received via MySQL query

查看:210
本文介绍了如何将PHP邮件发送到通过MySQL查询接收的多个电子邮件地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我运行MySQL查询从notify设置为YES的表中获取名字,姓氏和电子邮件,如下所示。而在while循环中,我创建了所有的信息,然后将它放入一个数组:

  $ sql =SELECT firstname,lastname,email,notify FROM guesses 
WHERE poolid ='$ poolid'
AND notify ='yes';
$ getnotify = mysqli_query($ connection,$ sql);
if(!$ getnotify){
die(数据库查询失败:mysqli_error());
} else {
while($ row = mysqli_fetch_array($ getnotify)){
$ notifyemailscontent。='$ row ['email']。 '=>'。 $ row ['firstname']。 。 $行[姓氏]。 ,;
}
}

$ notifyemails = array($ notifyemailscontent);

然后在PHP邮件程序代码中,我总是发送到我的地址,如下所示:

  $ mail-> addAddress(myemail@myemail.com,'Me'); 

但是,我还要添加我在mysql查询中获得的电子邮件(是否有1或100)作为CC或BCC(或者是罚款)。根据我在网上找到的东西,我尝试像下面这样做,但它不像我想要的那样行事。

  foreach($ notifyemails as $ email => $ name)
{
$ mail-> ; AddBCC($ email,$ name);
}

注意:它发送电子邮件到ME,但不发送电子邮件给BCC人。当我打印$ notifyemails数组时,我得到以下(在这种情况下只有一个BCC电子邮件):



Array([0] =>'bjones@bobscompany.com '=>'鲍勃·琼斯',)



再次,我收到电子邮件,但鲍勃不是在它上面。所以我认为在上面的for循环中或者可能在顶部的mysql查询循环中有一些错误?任何见解/方向将不胜感激。

解决方案

鉴于其他答案,我提交了以下内容。



正如我在评论中所说,从他们的例子中提取了以下内容,稍作修改,也可以显示该人的姓名。
$ b

您还可以添加它,并为其分配一个变量时使用不同的列。



https://github.com/PHPMailer/PHPMailer/blob/master/examples/mailing_list.phps



注意:由于您没有发布完整的代码,因此您需要稍微修改查询/列名称,可能需要修改一些代码



以下是我使用的一个工作示例,希望能为您服务。

 <?php 

include('/ path / to / database_connecti on.php);

error_reporting(E_STRICT | E_ALL);
date_default_timezone_set('Etc / UTC');

需要PHPMailerAutoload.php;

$ mail = new PHPMailer;

$ mail-> isSMTP();
$ mail-> Host ='xxx';
$ mail-> SMTPAuth = true;
$ mail-> SMTPKeepAlive = true; // SMTP连接不会关闭每个邮件发送后,减少SMTP开销

$ mail-> SMTPSecure ='tls'; // if required
$ mail-> Port = 587; //或使用您选择的首选端口
$ mail->用户名='xxx';
$ mail-> Password ='xxx';

$ mail-> addAddress('your_email@example.com','John');
$ mail-> setFrom('email@example.com','List manager');
$ mail-> addReplyTo('email@example.com','List manager');
$ mail-> Subject =PHPMailer简单数据库邮件列表测试;
//所有消息都相同,所以在发送循环之前设置这个
//如果你为每个收件人生成一个不同的主体(例如你使用的模板系统),
/ /将其设置在循环

// msgHTML也设置AltBody,但是如果你想要一个自定义的,然后设置它
$ mail-> AltBody ='要查看消息,请使用HTML兼容的电子邮件查看器!

$ result = mysqli_query($ connection,SELECT user,email FROM table WHERE col ='x');

foreach($ result as $ row){//此迭代器语法仅适用于PHP 5.4+

$ user = $ row ['user'];

$ body =Hello $ user,< br>< br>这是黑体中的HTML消息正文< b>< / b>;

$ mail-> msgHTML($ body);

$ mail-> addBCC($ row ['email'],$ row ['user']);

/ *
if(!empty($ row ['photo'])){
$ mail-> addStringAttachment($ row ['photo'],'YourPhoto .JPG'); //假设图像数据存储在DB
}
* /

if(!$ mail-> send()){
echoMailer错误(。str_replace(@,&#64;,$ row [email])。')'。 $ mail-> ErrorInfo。 '< br />';
break; //放弃发送
} else {
echo将消息发送到:。 $ row ['user']。 '('。str_replace(@,&#64;,$ row ['email'])。')< br />';
//标记为发送在DB

/ *如果需要更新表
mysqli_query(
$连接,
UPDATE邮件列表SET发送= true WHERE email ='
mysqli_real_escape_string($ connection,$ row ['email'])。'
);
* /

}
//清除下一个循环的所有地址和附件
$ mail-> clearAddresses();
$ mail-> clearAttachments();
}


I run a MySQL query to get firstname, lastname and email from a table where 'notify' is set to YES, like this below. And in the while loop, I create all the info which I then put into an array right after:

$sql = "SELECT firstname, lastname, email, notify FROM guesses
WHERE poolid = '$poolid'
AND notify = 'yes'";
$getnotify = mysqli_query($connection, $sql);
if (!$getnotify) {
die("Database query failed: " . mysqli_error());
} else {
    while ($row = mysqli_fetch_array($getnotify)) {
        $notifyemailscontent.="'".$row['email'] . "' => '" . $row['firstname'] . " " . $row['lastname']. "',";
    }
}

$notifyemails=array($notifyemailscontent);

Then in PHP mailer code, I always send to my address, like this:

$mail->addAddress(myemail@myemail.com, 'Me');

But then I also want to add the emails I get in the mysql query (whether there are 1 or 100) as CC or BCC (either is fine). I tried doing it like this below, based on something I found online, but it's not behaving as I would like.

foreach($notifyemails as $email => $name)
    {
       $mail->AddBCC($email, $name);
    }

NOTE: It IS sending the email to ME, but it's not sending the email to the BCC people. When I print the $notifyemails array, I get the following (only one BCC email in this case):

Array ( [0] => 'bjones@bobscompany.com' => 'Bob Jones', )

Again, I get the email, but Bob is NOT BCC'd on it. So I think something has to be wrong in the for loop above or possibly in the mysql query loop at the top??? Any insight/direction would be appreciated.

解决方案

Given the other answers, am submitting the following.

As I stated in comments, have pulled from their example the following and slightly modified to also show the person's name should you want to use that.

You can add to it also, using different columns while assigning a variable to them.

Borrowed from https://github.com/PHPMailer/PHPMailer/blob/master/examples/mailing_list.phps

N.B.: You will need to modify the query/column names slightly and possibly some of the code since you did not post your full code.

The following is a working example of what I used, and hope it serves you well.

<?php 

include ('/path/to/database_connection.php');

error_reporting(E_STRICT | E_ALL);
date_default_timezone_set('Etc/UTC');

require 'PHPMailerAutoload.php';

$mail = new PHPMailer;

$mail->isSMTP();
$mail->Host = 'xxx';
$mail->SMTPAuth = true;
$mail->SMTPKeepAlive = true; // SMTP connection will not close after each email sent, reduces SMTP overhead

$mail->SMTPSecure = 'tls'; // if required
$mail->Port = 587; // or use the preferred port of your choice
$mail->Username = 'xxx';
$mail->Password = 'xxx';

$mail->addAddress('your_email@example.com', 'John');
$mail->setFrom('email@example.com', 'List manager');
$mail->addReplyTo('email@example.com', 'List manager');
$mail->Subject = "PHPMailer Simple database mailing list test";
//Same body for all messages, so set this before the sending loop
//If you generate a different body for each recipient (e.g. you're using a templating system),
//set it inside the loop

//msgHTML also sets AltBody, but if you want a custom one, set it afterwards
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';

$result = mysqli_query($connection, "SELECT user, email FROM table WHERE col = 'x'");

    foreach ($result as $row) { //This iterator syntax only works in PHP 5.4+

        $user = $row['user'];

        $body = "Hello $user, <br><br>This is the HTML message body <b>in bold!</b>";

        $mail->msgHTML($body);

        $mail->addBCC($row['email'], $row['user']);

    /*
        if (!empty($row['photo'])) {
            $mail->addStringAttachment($row['photo'], 'YourPhoto.jpg'); //Assumes the image data is stored in the DB
        }
    */

        if (!$mail->send()) {
            echo "Mailer Error (" . str_replace("@", "&#64;", $row["email"]) . ') ' . $mail->ErrorInfo . '<br />';
            break; //Abandon sending
        } else {
            echo "Message sent to:" . $row['user'] . ' (' . str_replace("@", "&#64;", $row['email']) . ')<br />';
            //Mark it as sent in the DB

    /* UPDATE the table if needed
            mysqli_query(
                $connection,
                "UPDATE mailinglist SET sent = true WHERE email = '" .
                mysqli_real_escape_string($connection, $row['email']) . "'"
            );
    */

        }
        // Clear all addresses and attachments for next loop
        $mail->clearAddresses();
        $mail->clearAttachments();
    }

这篇关于如何将PHP邮件发送到通过MySQL查询接收的多个电子邮件地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆