phpmailer loop duplicated email addresses (and possible message) in loop - php

I have the following code sending email shipping confirmations to my customers:
while ($i < count($tracked) ) {
try {
//Server settings
//$mail->SMTPDebug = SMTP::DEBUG_SERVER; // Enable verbose debug output
$mail->isSMTP(); // Send using SMTP
$mail->Host = 'smtp.office365.com'; // Set the SMTP server to send through
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'support#mycompany.com'; // SMTP username
$mail->Password = 'password'; // SMTP password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` also accepted
$mail->Port = 587; // TCP port to connect to
//Recipients
$mail->setFrom('support#mycompany.com', 'mycompany');
$mail->addAddress($tracked[$i]['customers_email_address'], $tracked[$i]['customers_name']); // Add a recipient
$mail->addReplyTo('support#mycompany.com', 'mycompany');
// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = EMAIL_TEXT_SUBJECT;
$mail->Body = $html;
$mail->AltBody = 'Your order with mycompany.com has shipped';
$mail->send();
echo 'order confirmation sent to order#:'.$tracked[$i]['orders_id'].'<br/>';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
$i++;
}
It appears to be sending to multiple emails. What I believe is happening is that in the while loop each new customers address is added to the list without clearing it. What doesnt seem to be happening though is the message does not seem to be duplicated? Wouldn't that duplicate at as well with each pass in the loop?
In any case I think the best thing to do before the try is:
$mail = new PHPMailer(true);
so that with each pass of the while loop the $mail object would be instantiated again. Is that proper? I know that the clearAllRecipients() function exists but i also want to be sure the body is cleaned as well.

it looks like your looping through an array of $tracked. Why not use a foreach loop? Then you don't need to use a counter.
foreach ($tracked as $track ) {
try {
//Server settings
//$mail->SMTPDebug = SMTP::DEBUG_SERVER; // Enable verbose debug output
$mail->isSMTP(); // Send using SMTP
$mail->Host = 'smtp.office365.com'; // Set the SMTP server to send through
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'support#mycompany.com'; // SMTP username
$mail->Password = 'password'; // SMTP password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` also accepted
$mail->Port = 587; // TCP port to connect to
//Recipients
$mail->setFrom('support#mycompany.com', 'mycompany');
$mail->addAddress($track['customers_email_address'], $track['customers_name']); // Add a recipient
$mail->addReplyTo('support#mycompany.com', 'mycompany');
// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = EMAIL_TEXT_SUBJECT;
$mail->Body = $html;
$mail->AltBody = 'Your order with mycompany.com has shipped';
$mail->send();
echo 'order confirmation sent to order#:'.$track['orders_id'].'<br/>';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
}

It's because addAddress() does exactly what its name suggests; it adds an address that a message will be sent to. It doesn't set the addresses a message will be sent to.
Unsurprisingly there is a method that allows you to clear the list of addresses, called clearAddresses(), so just call that at the end of your sending loop after send() and your issue will be solved.
I'd also recommend that you base your code on the mailing list example provided with PHPMailer as it will be much faster than the code you have here. Also read the docs on sending to listshttps://github.com/PHPMailer/PHPMailer/wiki/Sending-to-lists) for furtehr advice.

Related

PHPmailer: Error: You must provide at least one recipient email address

I know there is several similar threads but I have tried all without any success.
$recipient = ($_POST["to"]);
$mail->AddAddress = ($recipient);
This doesn't work. I have tried with many different combinations as well, like this:
$mail->addAddress = ($recipient, 'name');
I am also running the validate address, which returns true
var_dump(PHPMailer::validateAddress($recipient));
Still I am getting Error: You must provide at least one recipient email address
Any suggestions?
Try this one:
$mail = new PHPMailer;
$mail->SMTPDebug = 3; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'mail.mysite.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'info#mysite.nl'; // SMTP username
$mail->Password = 'secure123'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
$mail->setFrom('info#mysite.nl', 'My cool website'); // The email address of your site goes here
$mail->addAddress('customer#hotmail.com', 'Important customer'); //Destination address and name
$mail->Subject = 'Just saying hi!'; //Title of your mail
$mail->Body = '<h1> A test mail </h1>';
$mail->AltBody = 'Mail has been sent!';
if(!$mail->send()) {
$data = array('mailissend' => false, 'message' => $mail->ErrorInfo);
} else {
echo json_encode('Email is sended');
}

PHPMailer, SMTP Error: Could not authenticate

I'm pretty sure that there are many questions out there regarding this problem.I don't seem to get my solution.
I'm using PHPMailer to mail through my php script.It was totally working few days back but today i tried doing it again,it didn't work.
require 'PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer(true);
$message="Hello there";
$mysqli->autocommit(FALSE);
$statement=$mysqli->prepare("INSERT INTO usertable VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)");
$zero=0;
$null=null;
$state='Delhi';
$statement->bind_param("sssssiiissssi",$email,$firstname,$lastname,$name,$password,$zero,$confirmcode,$zero,$null,$null,$null,$state,$zero);
$statement->execute();
try
{
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'ssl://smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'support#mydomain.com'; // SMTP username
$mail->Password = 'mvdctadwzkiibtot'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465; // TCP port to connect to
$mail->setFrom('From #mydomain', 'mydomain');
$mail->addAddress($email); // Name is optional
$mail->addReplyTo('support#mydomain.com', 'For any queries mail back to support#foodquo.com');
// $mail->addCC('cc#example.com');
//$mail->addBCC('bcc#example.com');
$mail->WordWrap = 50;
// $mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
// $mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Confirm your email ID';
$mail->Body = $message;
//$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();
}
catch(Exception $e)
{
$mysqli->rollback();
$response=array(
'status'=>'mailFailed',
'errorer'=>$e->getMessage(),
);
}
echo json_encode($response);
NOTE
I have my domain registered on Hostgator.
The email is present inside the cpanel and i can configure it from there.It doesn't have any password.So $mail->Password should not be an issue.
Given Below is the error that i have been getting , what could be the possible solution? Thanks!
SMPT Error :Could not authenticate.
if u are using gmail smptp service use:
$mail->Username = 'emailid#gmail.com'; // Gmail username
$mail->Password = 'mvdctadwzkiibtot'; //gmail password

How do I delay sending mails with PHPMailer for multiple days?

I'm trying to create a mailing system for our library. People receive an e-mail when they requested a book. However, I want them to receive an e-mail one day before the hand-in date as well.
So I'm not looking for a sleep script code, I'm looking for a code that can maybe store the data on the server until the hand-in date arrived.
I'm using Joomla 3.5.1 for our website, this is the code for the PHPMailer:
jimport('joomla.mail.mail');
try{
$mail = new PHPMailer();
$body = $mailmsgadmin;
$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host = "example.host.com"; // SMTP server
$mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
// 1 = errors and messages
// 2 = messages only
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPSecure = "ssl"; // sets the prefix to the servier
$mail->Host = "example.host.com"; // sets the SMTP server
$mail->Port = 25; // set the SMTP port for the GMAIL server
$mail->Username = "email"; // SMTP account username
$mail->Password = "password"; // SMTP account password
$mail->SetFrom('email', 'First Last');
$mail->AddReplyTo($mailuseremail, $mailusername);
$mail->Subject = $mailsubject;
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!";
$mail->MsgHTML($body);
$mail->AddAddress("Users e-mail","Users name");
if(!$mail->Send()) {
JError::raiseWarning( 'SOME_ERROR_CODE', $mail->ErrorInfo);
}
} catch (Exception $e) {JError::raiseWarning( 'SOME_ERROR_CODE', $e->getMessage());}
Instead of trying to get PHPMailer delay the sending, add your email details to a database table. And then write a cron job that checks the table for emails that need to be sent.

PHPMailer not sending, but no errors

I created a php application at dan.creativeloafing.com. This just takes form data and builds an html page with it, then emails the contents of that page to dan#creativeloafing.com. A couple days ago, it stopped working. I have been trying to figure this out ever since. I was using the mail() php function and have switched it over to the PHPMailer Library. This is supposedly sending the emails and I get confirmation, but nobody ever recieves the email and I get no bounceback or any errors. This is the jist of the code:
//PHPMailer
$mail = new PHPMailer;
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'relay-hosting.secureserver.net'; // Specify main and backup server
$mail->Port = 25;
$mail->SMTPAuth = false; // Enable SMTP authentication
$mail->SMTPSecure = 'tsl'; // Enable encryption, 'ssl' also accepted
$mail->Username = 'dan#omgsurvey.com'; // SMTP username
$mail->Password = '*******'; // SMTP password
$mail->SMTPDebug = 0;
$mail->WordWrap = 50;
$mail->From = 'dan#omgsurvey.com';
$mail->FromName = 'DAN Application';
$mail->addAddress('dan#creativeloafing.com'); // Name is optional
$mail->addReplyTo($repEmail);
$mail->addCC('david.miller#creativeloafing.com');
$mail->isHTML(true);
$mail->Subject = "New DAN Request: ".$campaignName;
$mail->msgHTML(file_get_contents('./tmp/DAN_REQUEST_'.$specialString.$randomNumber.'.html'));
if(!$mail->send()) {
echo '<br />Proposal could not be sent.<br />';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit;
} else {
echo 'Proposal has been sent';
}
The script always reaches 'Proposal has been sent.' too. This is driving me crazy!
So what was happening here is that godaddy was blocking emails that included my domain name in them. I am not sure if this was a spam issue, but they are currently looking into it. I have gotten the emails to send using a simple mail() function and by removing any references to omgsurvey.com in the email. Silly, this mail was only ever sent to two email addresses!
Isn't:
$mail->SMTPSecure = 'tsl';
supposed to be:
$mail->SMTPSecure = 'tls';
Use try...catch and PHPMailer(true); https://github.com/Synchro/PHPMailer/blob/master/examples/exceptions.phps
//Create a new PHPMailer instance
//Passing true to the constructor enables the use of exceptions for error handling
$mail = new PHPMailer(true);
try {
mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'relay-hosting.secureserver.net'; // Specify main and backup server
$mail->Port = 25;
$mail->SMTPAuth = false; // Enable SMTP authentication
$mail->SMTPSecure = 'tsl'; // Enable encryption, 'ssl' also accepted
$mail->Username = 'dan#omgsurvey.com'; // SMTP username
$mail->Password = '*******'; // SMTP password
$mail->SMTPDebug = 0;
$mail->WordWrap = 50;
$mail->From = 'dan#omgsurvey.com';
$mail->FromName = 'DAN Application';
$mail->addAddress('dan#creativeloafing.com'); // Name is optional
$mail->addReplyTo($repEmail);
$mail->addCC('david.miller#creativeloafing.com');
$mail->isHTML(true);
$mail->Subject = "New DAN Request: ".$campaignName;
$mail->msgHTML(file_get_contents('./tmp/DAN_REQUEST_'.$specialString.$randomNumber.'.html'));
$mail->send();
echo 'Proposal has been sent';
} catch (phpmailerException $e) {
echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
echo $e->getMessage(); //Boring error messages from anything else!
}
Thinking send() should be Send()
if(!$mail->Send()) {

Mailer Error: SMTP Error: The following SMTP Error: Data not accepted

The following code gives the message
Mailer Error: SMTP Error: The following SMTP Error: Data not accepted. But when I replace $EmailAdd with a a#yahoo.com. The mail was sent.
What's wrong with my code? I'm kind of new in php, especially in dealing with mail functions.
$sql1 = "SELECT Email_Address FROM participantable where IDno=$studId";
$result1 = mysql_query($sql1);
while ($row1 = mysql_fetch_assoc($result1)){
$EmailADD = $row1["Email_Address"];
}
//error_reporting(E_ALL);
error_reporting(E_STRICT);
date_default_timezone_set('America/Toronto');
include("class.phpmailer.php");
//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
$mail = new PHPMailer();
$body = $mail->getFile('contents.html');
$body = eregi_replace("[\]",'',$body);
$mail->IsSMTP();
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPSecure = "ssl"; // sets the prefix to the servier
$mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
$mail->Port = 465; // set the SMTP port for the GMAIL server
$mail->Username = "jsbadiola#gmail.com"; // GMAIL username
$mail->Password = "********"; // GMAIL password
$mail->AddReplyTo("jsbadiola#gmail.com","Lord Skyhawk");
$mail->From = "jsbadiola#gmail.com";
$mail->FromName = "Update";
$mail->Subject = "PHPMailer Test Subject via gmail";
$mail->Body = "Hi,<br>This is the HTML BODY<br>"; //HTML Body
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->WordWrap = 50; // set word wrap
$mail->MsgHTML($body);
$mail->AddAddress($EmailADD, "Agta ka");
$mail->AddAttachment("images/phpmailer.gif"); // attachment
$mail->IsHTML(true); // send as HTML
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
$status = "Successfully Save!";
header("location: User_retsched.php?IDno=$studId&status=$status&Lname=$Lname&Fname=$Fname&Course=$Course&Year=$Year");
}
Most times I've seen this message the email gets successfully sent anyway, but not always. To debug, set:
$mail->SMTPDebug = true;
You can either echo the debug messages or log them using error_log():
// 'echo' or 'error_log'
$mail->Debugoutput = 'echo';
A likely candidate especially on a heavily loaded server are the SMTP timeouts:
// default is 10
$mail->Timeout = 60;
class.smtp.php also has a Timelimit property used for reads from the server.
It also helps if you have not exceeded your daily sending limit of Googles Spam inforcement.
check you query to the db output & variable value at that point in the script. make sure it's returning the desired value for $EmailADD .
do a var_dump($EmailADD, true);
or try to echo somewhere the output of that query. If your actually receiving an email value from that query, I don't see why it shouldn't work, specially when you mention that assigning a value directly works; without sql query.
Try a different SMTP server? See if that works?
Or just don't use an smtp server, most servers with PHP on also have sendmail/postfix, so can relay email themselves.
remove this bit ...
$mail->IsSMTP();
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPSecure = "ssl"; // sets the prefix to the servier
$mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
$mail->Port = 465; // set the SMTP port for the GMAIL server
$mail->Username = "jsbadiola#gmail.com"; // GMAIL username
$mail->Password = "alucar"; // GMAIL password

Categories