Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPMailer sends duplicate email

PHPMailer

<?php
    $mail = new PHPMailer;
    $mail->IsSMTP();
    $mail->IsHTML(true);
    $mail->SMTPSecure = "tls";
    $mail->Mailer = "smtp";
    $mail->Host = "smtp.office365.com";
    $mail->Port = 587;
    $mail->SMTPAuth = true; // turn on SMTP authentication
    $mail->Username = "xxx";
    $mail->Password = "xxx";
    $mail->setFrom('xxx', 'Website');

    //Send to Admin
    $AdminEmail = '[email protected]';
    $mail->AddAddress($AdminEmail, $AdminName);
    $mail->Subject  = "This is an email";
    $mail2 = clone $mail;
    $body = 'Hi Admin. This is an email';
    $mail->Body = $body;

    if(!$mail->Send()) {
    echo 'Message was not sent.';
    echo 'Mailer error: ' . $mail->ErrorInfo;
    } else {
    echo 'Message has been sent.';
    }

    //Send to User
    $UserEmail = '[email protected]';
    $mail2->AddAddress($UserEmail, $UserName);
    $body2 = 'Hi User. This is an email';
    $mail2->Body = $body2;

    if(!$mail2->Send()) {
    echo 'Message was not sent.';
    echo 'Mailer error: ' . $mail2->ErrorInfo;
    } else {
    echo 'Message has been sent.';
    }
?>

I have an issue where when i send the emails, Admin will receive $mail and $mail2 when they supposed to just receive $mail. While there's no problem with User. Works fine by receiving $mail2. I've tried to put $mail->ClearAddresses(); but it's still the same. By chance, what is the problem?

like image 470
Athirah Hazira Avatar asked Mar 03 '26 09:03

Athirah Hazira


2 Answers

Clone the email variable before adding the address and stuff of the admin. (As suggested in the comments)

like image 149
Casper Avatar answered Mar 04 '26 23:03

Casper


You need to create different-different object for both admin and user email

//Send to Admin
$mail = new PHPMailer;
$mail->IsHTML(true);
$AdminEmail = '[email protected]';
$mail->AddAddress($AdminEmail, $AdminName);
$mail->Subject  = "This is an email";
$mail2 = clone $mail;
$body = 'Hi Admin. This is an email';
$mail->Body = $body;

if(!$mail->Send()) {
echo 'Message was not sent.';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent.';
}

//Send to User
$mail = new PHPMailer;
$mail->IsHTML(true);
$UserEmail = '[email protected]';
$mail->AddAddress($UserEmail, $UserName);
$body2 = 'Hi User. This is an email';
$mail->Body = $body2;

if(!$mail->Send()) {
echo 'Message was not sent.';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent.';
}
like image 34
Sanjeev Chauhan Avatar answered Mar 04 '26 23:03

Sanjeev Chauhan