E-mail being sent in duplicate to each contact

Asked

Viewed 225 times

1

I am sending a newsletter to the emails I have registered in my bank. Sending is being done, but wrongly. Each contact receives a copy of another person’s email.

This is my code, connection values have been deleted:

<?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();

?>

3 answers

2


The problem is you’re giving a 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 only serves to add emails to the mailing list, NAY to send. After having the mailing list defined, run the method send, out of the loop.

However, as @rray said, this way, all emails will appear to the recipients. One way to resolve this is by sending the message inside the loop as you did before, but by clearing the mailing list. Also, 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 (...);
  • 1

    This will then send a single email with all the addresses exposed, every turn of the while the first and the following will receive the emails. I believe the idea is to send an email per customer, just give a clearAddress at the end loop.

  • Hello @rray is exactly what is happening, the clearAddress would be out of the loop?

1

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

Let’s say it’s three clients, Maria, João and Joana. In the first loop, maria will receive the email, as the address (sender) was not reset/deleted, in the second loop maria plus joão received emails, and in the last, maria and joão received the email again and Joana will only receive one.

Example of the problem:

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 addresses with clearAddress():

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

A suggestion I leave is to create a template file for the email so you separate the html from the code that has the sending logic. You can see this in that reply, that does the processing of the Templete with file_get_contents.

  • Hello @rray, if you do as you told me in the example the remaining content of the email will be aborted, the message I received was this: Message body Empty.

  • I showed what needs to be changed, (sending the email and cleaning the addresses/attachments) the other lines continue. In practice what changed was the order of the oxen(lines of the code) :).

0

Change the appointment:

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

By 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.

...

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.