PHP Mailer sends email 2 times

2

I've been looking for this problem here in the forum, but I have not found it. If there is a link and someone can send me, I am grateful. The problem is this:

This my form, sends 2 emails to the recipient that I set. I looked at the code again and again, but I did not understand why.

PHP

$nome = $_POST['nome'];
$texto = $_POST['texto'];
$enviar= $_POST['enviar'];
if(isset($enviar)){
$corpoMSG = "Oi, meu nome é: ".$nome."<br /><br />".$texto;
$assunto = "Teste para envio de email";
require_once('phpmailer/class.phpmailer.php');
 $mail   = new PHPMailer();
 $mail->CharSet = 'UTF-8';
 $mail->SetFrom('[email protected]', 'Orçamento');
 $address = "[email protected]";
 $mail->AddAddress($address, "destinatario");
 $mail->Subject = $assunto;
 $mail->MsgHTML($corpoMSG);
 if(!$mail->Send()) {
echo "<div class='alert alert-danger'><p style='padding: 0; margin: 0;'>Email não enviado.</p></div>"; 
  } else {
echo "<div class='alert alert-success'><p style='padding: 0; margin: 0;'>
Email enviado com sucesso!</p></div>";  }}
    
asked by anonymous 03.11.2015 / 19:44

1 answer

4

Assuming the php code is in the same form file:

This error occurs because a check is not being made whether the form was posted or not (whether the user clicked the submit or not). That way every time the page loads the email is sent and when the form is posted the form is sent again.

You can fix your code by putting an if to check if the request is a post:

     if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $nome = $_POST['nome'];
$texto = $_POST['texto'];

$enviar= $_POST['enviar'];
if(isset($enviar)){
$corpoMSG = "Oi, meu nome é: ".$nome."<br /><br />".$texto;
$assunto = "Teste para envio de email";
require_once('phpmailer/class.phpmailer.php');
 $mail   = new PHPMailer();
 $mail->CharSet = 'UTF-8';
 $mail->SetFrom('[email protected]', 'Orçamento');
 $address = "[email protected]";
 $mail->AddAddress($address, "destinatario");
 $mail->Subject = $assunto;
 $mail->MsgHTML($corpoMSG);
 if(!$mail->Send()) {
echo "<div class='alert alert-danger'><p style='padding: 0; margin: 0;'>Email não enviado.</p></div>"; 
  } else {
echo "<div class='alert alert-success'><p style='padding: 0; margin: 0;'>
Email enviado com sucesso!</p></div>";  }}
}
    
03.11.2015 / 20:28