E-mail being sent in duplicate to each contact

1

I am sending a newsletter to the email addresses that I have registered with my bank. Sending is being done, but erroneously. Each contact receives a copy of someone else's email.

My code is this, connection values have been suppressed:

<?php

require_once('../Connections/conexao.php');
// Inclui o arquivo class.phpmailer.php localizado na pasta phpmailer
include("../phpmailer/class.phpmailer.php");

mysql_select_db($database_conexao, $conexao);
$query_News = "SELECT * FROM 'newsletter' WHERE status = 1 AND fora = 0 ORDER BY id ASC";
$News = mysql_query($query_News, $conexao) or die(mysql_error());
$row_News = mysql_fetch_assoc($News);
$totalRows_News = mysql_num_rows($News);    

// Inicia a classe PHPMailer
$mail = new PHPMailer();

// $mail->SMTPDebug = 2;

// Define os dados do servidor e tipo de conexão
// ---------------------------------------------
$mail->IsSMTP(); // Define que a mensagem será SMTP
$mail->Host = "mail.meusite.com.br"; // Endereço do servidor SMTP
$mail->SMTPAuth = true; // Usa autenticação SMTP? (opcional)
$mail->Username = 'meuemail'; // Usuário do servidor SMTP
$mail->Password = 'minhasenha'; // Senha do servidor SMTP
$mail->Port = 587;  

// Define o remetente
// ------------------
$mail->From = 'meuemail'; // Seu e-mail
$mail->FromName = "Newsletters - Móveis Sao Bento"; // Seu nome

// Loop para envio das mensagens
do {

    $id    = $row_News['id'];
    $email = $row_News['email'];

    // Define os destinatário(s)
    // -------------------------
    $mail->AddAddress($email,$nome); // Cliente

    // Define os dados técnicos da Mensagem
    // ------------------------------------
     // Define e-mail´s que será(ão) enviado como HTML
    $mail->IsHTML(true);
    $mail->CharSet = 'iso-8859-1'; // Charset da mensagem (opcional)    

    // Define a mensagem (Texto e Assunto)
    // -----------------------------------
    $mail->Subject  = "Newsletter"; // Assunto da mensagem
    $mail->Body = "<div align=left>
      <style type='text/css'>
        <!--
        .style1 {
            font-family: Verdana, Arial, Helvetica, sans-serif;
            font-size: 10px;
        }
        -->
        </style>
          <table width=600 border=0>
            <tr>
              <td width='18%' align='left'>
                <div align='left'></div>
              <div align='left'></div></td>
            </tr>
            <tr>
              <td align='left'><p align='left' class='titulos'>
                                   Assunto - Newsletter <br>
                                   E-mail - $email <br />                                  
                                   </p>
                                   <p align='center' class='titulos'>
                                         Esse e-mail foi enviado automaticamete, não responda.<br />
                                        <a href=unsubscribe.php?id=$id>Descadastrar de nossa Newsletter</a>
                                   </p>
                </td>
            </tr>
          </table>
        </div>";


    // Envia o e-mail
    // ---------------
    $status = $mail->Send();

} while ($row_News = mysql_fetch_assoc($News));


if ($status == 1) {
    echo 'Os e-mails foram enviados corretamente ';     
} else {
    echo  'Os e-mails não puderam ser enviados, por favor, tente novamente';
}   

// Limpa os destinatários e os anexos
// ----------------------------------
$mail->ClearAllRecipients();
$mail->ClearAttachments();

? >

    
asked by anonymous 12.02.2015 / 17:09

3 answers

2

The problem is that you are giving send whenever you add an email to the mailing list. You could modify your code to look like this:

do {
    $id    = $row_News['id'];
    $email = $row_News['email'];
    $nome = $row_News['nome'];
    $mail->AddAddress($email, $nome);
} while (...);

$mail->IsHTML(true);
$mail->CharSet = 'iso-8859-1';

$mail->Subject  = "Newsletter";
$mail->Body = "...";

$status = $mail->Send();

In short, the loop is only for adding emails to the mailing list, NOT to send. After the mailing list has been defined, execute the send method, outside the loop.

However, as @rray said, in this way, all emails will appear to the recipient. One way to resolve this is by sending the message inside the loop as you did before, but by clearing the mailing list. In addition, you can set the message, subject, etc ... outside the loop.

$mail->IsHTML(true);
$mail->CharSet = 'iso-8859-1';

$mail->Subject  = "Newsletter";
$mail->Body = "...";

do {
    $id    = $row_News['id'];
    $email = $row_News['email'];
    $nome = $row_News['nome'];
    $mail->AddAddress($email, $nome);

    $status = $mail->Send();

    // limpa lista de emails
    $mail->ClearAllRecipients();
} while (...);
    
12.02.2015 / 17:37
1

The problem is that with each loop loop an email is added, the first person and the next person will receive N times the same copy. If the goal is to send an email per person, clear the addresses at the end of the loop after sending.

Let's say it's 3 customers, Maria, Joao and Joana. In the first round of the tie, María will receive the email, as the address (sender) was not reset, in the second round Maria received more emails, and in the last one, Maria and Joao received the email again, / p>

Problem example:

do {
    $id    = $row_News['id'];
    $email = $row_News['email'];

    //linhas omitidas ....

    $mail->AddAddress($email,$nome); // Cliente
    $status = $mail->Send();

} while ($row_News = mysql_fetch_assoc($News));


//mais linhas omitidas...

$mail->ClearAllRecipients();
$mail->ClearAttachments();

To fix this, clear the addresses with clearAddress ():

while ($row_News = mysql_fetch_assoc($News)){
//linhas omitidas ....
   $status = $mail->Send();
   $mail->ClearAllRecipients();
   $mail->ClearAttachments();       
}

One suggestion I make is to create a template file for the email so you separate the html from the code that has the submission logic. You can see this in this answer , which does the temple processing with file_get_contents .

    
12.02.2015 / 18:10
0

Change the query:

$query_News = "SELECT * FROM newsletter WHERE status = 1 AND fora = 0 ORDER BY id ASC";

For a foreach and leave only this loop. EXAMPLE :

foreach( $wpdb->get_results('SELECT * FROM newsletter WHERE status = 1 AND fora = 0 ORDER BY id ASC') as $key => $row) {

$id   = $row->id;
$email= $row->email;

//SEU CÓDIGO SERÁ RODADO A CADA NOVA CONSULTA.

...

}
    
12.02.2015 / 18:36