Athirah Hazira
Athirah Hazira

Reputation: 473

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?

Upvotes: 3

Views: 3360

Answers (2)

Casper
Casper

Reputation: 1435

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

Upvotes: 3

Sanjeev Chauhan
Sanjeev Chauhan

Reputation: 4097

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.';
}

Upvotes: 1

Related Questions