How to send messages at time intervals to a batch of emails

Asked

Viewed 1,036 times

0

How do I get the loop to send every 10 emails or every X seconds? I want to prevent emails from falling into the spam list.

And how can I get the code to read a file . txt with the listed emails and in the future a database?

<?PHP

require_once('class.phpmailer.php');

//$email[] = "[email protected]";

foreach($email as $e){

  $mail = new PHPMailer();
  $body = file_get_contents('a.html');

  $mail->AddReplyTo("[email protected]","EREA SSA");
  $mail->SetFrom('[email protected]', 'EREA SSA');

  $mail->AddAddress($e, utf8_decode("$nome[$loop] $sobrenome[$loop]"));
  $mail->Subject = utf8_decode("Sua inscrição foi aceita !");
  $mail->MsgHTML($body);
  //$mail->AddAttachment("edital.pdf"); // Arquivos para anexo

  if(!$mail->Send()) {
    echo "Erro: " . $mail->ErrorInfo . "<br/>";
  } else {
    echo "Mensagem enviada !<br/>";
  }
  $mail->clearAllRecipients();
}

?>

1 answer

2


It needs several things, I will summarize in topics:

Problem 1:

Change the PHP.ini:

You need to change to prevent PHP from terminating the process for time, this is only for security, because by default it will be zero, because it will run from the command line!

max_execution_time = 0;

Loop:

Create a while and a sleep within!

while(1  === 1){ // 1 sempre será 1, sempre irá continuar!

// código

sleep(30); // 30 segundos de pausa!
} 

Start this loop:

You must have access to SSH (or similar) and execute, for example, the command nohup

nohup php /caminho/para/o/arquivo.php &

nohup has the function of being able to run in the background, even if your connection to the server falls, this will make the script remain active even if there is an interruption in communication (or if you disconnect your device, for example).

Problem 2:

It lacks data on what the structure would look like, so I’m deducing that it would be an email per line, similar to the database!

<?PHP

require_once('class.phpmailer.php');

$i = 0;
while(1 === 1){ // LOOP

$arquivo = file('arquivo'.$i.'.txt'); 
// Seleciona o arquivo por linha, cada linha uma array. 
// Isso irá selecionar o "arquivo0.txt" ao terminar será "arquivo1.txt", depois "arquivo2.txt", caso queria mante-lo fixo apenas remova o $i.

   $f = 1; // numero de email
foreach($arquivo as $e){

  //nada modificado
  $mail = new PHPMailer();
  $body = file_get_contents('a.html');

  $mail->AddReplyTo("[email protected]","EREA SSA");
  $mail->SetFrom('[email protected]', 'EREA SSA');

  $mail->AddAddress($e, utf8_decode("$nome[$loop] $sobrenome[$loop]"));
  $mail->Subject = utf8_decode("Sua inscrição foi aceita !");
  $mail->MsgHTML($body);
  //$mail->AddAttachment("edital.pdf"); // Arquivos para anexo

  if(!$mail->Send()) {
    echo "Erro: " . $mail->ErrorInfo . "<br/>";
  } else {
    echo "Mensagem enviada !<br/>";
  }
  $mail->clearAllRecipients();
  //modificado para adicionar sleep

  if($f %10 == 0) { // se for divido por 10 da pausa (10, 20, 30...)!
  sleep(30);
  }
$f++; // acrescenta +1 email
}
sleep(30); // por segurança após o foreach
$i++;
}
?>

Logical problem:

What you want is to make a loop in something scarce. That is, there is limit of emails that can be selected, so the "infinite" loop is unreal and is not important and will not be useful, since the files are not infinite.

However this does not seem to have been pointed out in the text or was not this exact question, but it is the great point to consider. But, the "Problem 1" solution is valid, including to prevent PHP from terminating the process before completion (or in case of disconnection of the SSH client).

  • Inkeliz, you again haha :) I liked the first solution ! Regarding problem 2, I will be using a text file where each line will have an email. Or I can go to use the database too, to read the tables, something I still have to create

  • In this case only make changes to the file(), it "converts" all lines into an array item. I made a change to send 10 emails and wait X time, as I said, I didn’t care about it.

  • For some reason, emails are not coming and then an error appears: Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request.&#xA;&#xA;Please contact the server administrator at [email protected] to inform them of the time this error occurred, and the actions you performed just before this error.&#xA;&#xA;More information about this error may be available in the server error log. In this case, if I want it to display the text of "Sent Message" after each upload, it is possible ?

  • This can occur by restriction of the provider, mainly against spam. This is usually common on shared environment servers (mostly free) and VPS. Another problem may be problem in setting in . htaccess, it may also cause this.

  • Just change to if($mail->Send()) echo "Mensagem enviada";instead of ! $mail and then Else. Using nohup all output will be displayed in a file called nohup.out in the same place where you executed php.

Browser other questions tagged

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