fastest way to send mails using phpmailer smtp? - php

i am using following phpmailer function to send 1000+ mails
<?php
function sendMail($sendTo,$Subject,$Body){
require_once 'PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = 'smtp.example.com;smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'newsletter#example.com';
$mail->Password = 'password';
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
$mail->From = 'newsletter#example.com';
$mail->FromName = 'xyz';
$mail->WordWrap = 50;
$mail->isHTML(true);
$mail->addAddress($sendTo);
$mail->Subject = $Subject;
$mail->Body = ( stripslashes( $Body ) );
$mail->AltBody = 'Please Use a Html email Client To view This Message!!';
if(!$mail->send()) {
$return = 'Message could not be sent.';
// echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
$return = 'Message has been sent!';
}
return $return;
}
and this is the code i am using to call function
foreach ($emails as $email) {
$subject = "sample subject";
$body = "sample body";
sendMail($email, $subject, $body);
}
size of $emails array is 1000+
is there any faster and better way to do this?

You should start by reading the docs provided with PHPMailer where you will find this example.
Of particular note in there, make sure you use SMTPKeepAlive - you may find benefit in sorting your list by domain to maximise connection re-use.
As zerkms said, you should submit to a local mail server for best performance, though surprisingly using mail or sendmail options in PHPMailer is not always faster than SMTP to localhost, largely because postfix' sendmail binary opens a synchronous SMTP connection to localhost anyway - postfix' docs recommend SMTP to localhost for best performance for this reason.
If you are sending to localhost, don't use auth or encryption as the overhead doesn't gain you anything, but if you are using a remote server, use tls on port 587 in preference to the obsolete ssl on port 465.
Generally sending directly to end users is to be avoided - the SMTP client in PHPMailer is somewhat dumb - it does not handle queuing at all, so any domains with greylisting or delivery deferrals for traffic control will fail to be delivered. the best approach is to use SMTP to a nearby MTA and leave the queue handling to that. You can get bounces back from that as well so you can remove bad addresses from your list.

Untested, but this should work.
Basically, it reuses the original object (thus reducing memory allocations).
require_once 'PHPMailer/PHPMailerAutoload.php';
class BatchMailer {
var $mail;
function __construct () {
$this->mail = new PHPMailer;
$this->mail->isSMTP();
$this->mail->Host = 'smtp.example.com;smtp.example.com';
$this->mail->SMTPAuth = true;
$this->mail->Username = 'newsletter#example.com';
$this->mail->Password = 'password';
$this->mail->SMTPSecure = 'ssl';
$this->mail->SMTPKeepAlive = true;
$this->mail->Port = 465;
$this->mail->From = 'newsletter#example.com';
$this->mail->FromName = 'xyz';
$this->mail->WordWrap = 50;
$this->mail->isHTML(true);
$this->mail->AltBody = 'Please use an HTML-enabled email client to view this message.';
}
function setSubject ($subject) {
$this->mail->Subject = $subject;
}
function setBody ($body) {
$this->mail->Body = stripslashes($body);
}
function sendTo ($to) {
$this->mail->clearAddresses();
$this->mail->addAddress($to);
if (!$this->mail->send()) {
// echo 'Mailer Error: ' . $this->mail->ErrorInfo;
return false;
} else {
return true;
}
}
}
$batch = new BatchMailer;
$batch->setSubject('sample subject');
$batch->setBody('sample body');
foreach ($emails as $email) {
$batch->sendTo($email);
}

Drop the function into c++ via cgi. A c++ mailer would be far more robust than hitting the entire http framework first. http://www.cplusplus.com/forum/windows/86562/
But PhP already uses hash table for it's associative array, so you won't pick up anymore speed with a hash table. So you really are sort of maxed out in your web framework.
Drop it to a system level function and c is your fastest/leanest choice.
Unless you are really talented with assembly language.

Related

PhpMailer ~30 seconds delay on send

Ok so I have few problems with PhpMailer.
There is a delay of about 30 seconds before $mail->send is being executed.
2019-07-23 13:43:55 Connection: opening to
smtp.gmail.com:587, timeout=300, options=array() 2019-07-23
13:44:16 Connection: opened 2019-07-23 13:44:16 SERVER
etc...(some list of parameters).
The code being used for registering users. I instantiated Mail class inside model method and then called that method inside Controller following by function that redirects after successful login. I also get headers already sent error.
2019-07-23 13:44:17 Connection: closed Message has
been sent Warning: Cannot modify header information - headers
already sent by (output started at
C:\xampp\htdocs\log\vendor\phpmailer\phpmailer\src\SMTP.php:257) in
C:\xampp\htdocs\log\App\Core\Controller.php on line 43
My code:
Mail class:
class Mail
{
public function sendMail($to, $subject, $text, $html)
{
$mail = new PHPMailer(true);
try {
//Server settings
$mail->SMTPDebug = 3;
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'wuwu5431#gmail.com';
$mail->Password = 'Password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
//Recipients
$mail->setFrom('wuwu5431#gmail.com', 'John Smith');
$mail->addAddress($to, '');
$mail->addReplyTo('wuwu5431#gmail.com', 'Information($mail->addReplyTo)');
//Content
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = $text;
$mail->AltBody = $html . ' $html . This is the body in plain text for non-HTML mail clients';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}
}//end of method
}// end of class
Model(method):
public function sendActivationEmail($email)
{
$url = 'url';
$text = 'text';
$html = 'html';
$mail = new \App\Mail;
$mail->sendMail($email, 'Account activation', $text, $html);
}
Controller(method):
public function register()
{
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
foreach($_POST as $key => $value){
$data[$key] = htmlspecialchars(strip_tags(trim($value)));
}
$this->userModel = new \App\Models\UserM;
if ($this->userModel->Register($data)) {
Flash::addMessage('Thank you for Registering with us');
$this->userModel->sendActivationEmail($data['email']);
$this->redirect('User/UserC/success');
}
}
}
Enviroment: win 7, xampp, localhost.
This is entirely normal - welcome to the world of SMTP.
SMTP can impose delays of up to 10 minutes at multiple points within a transaction, and for that reason it's not well suited use during page submission processing, though it's still very common to do that.
The way to handle it is to make it asynchronous (as far as your page is concerned), and there are multiple ways of doing that, for example stash your message in a queue that's picked up and sent by a separate process later (i.e. not holding up your page submission processing), or submit it directly to a local mail server, which will typically accept a submission in a few milliseconds, and deal with onward delivery for you.
Separate from this, these lines are probably wrong:
$mail->setFrom('wuwu5431#gmail.com', 'John Smith');
$mail->addAddress($to, '');
$mail->addReplyTo('wuwu5431#gmail.com', 'Information($mail->addReplyTo)');
If your from and reply-to address are the same, the reply-to will be ignored. If you don't have a name to go with the to address, just leave it off. Single-quoted strings do not do variable interpolation in PHP. You probably want just:
$mail->setFrom('wuwu5431#gmail.com', 'John Smith');
$mail->addAddress($to);

PHPMailer function to send without SMTP if SMTP fails

I've written the following code to send email using PHPMailer. But what i'm trying to get working is first attempt a send via SMTP TLS and if that fails then send the mail without SMTP. But the code seems to fail because it doesn't like to run the PHPMailer function twice. If I run the function once either calling it to send via SMTP or not both work. But it doesn't work if SMTP fails.
function processEmail($to, $message, $skip_smtp){
date_default_timezone_set('Europe/London');
require 'PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
if (!isset($skip_smtp) || empty($skip_smtp)){
$mail->isSMTP();
}
$mail->SMTPDebug = 0;
$mail->Debugoutput = 'html';
$mail->Host = 'smtp.domain.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = "my_smtp_username";
$mail->Password = "my_smtp_password";
$mail->setFrom('from#myemail.com', 'From Name');
$mail->addAddress($to, $to);
$mail->msgHTML($message);
if (!$mail->send()) {
return false;
} else {
return 1;
}
}
$smtp_result = processEmail($to, $message);
if ($smtp_result>=1){
echo "Sent using secure TLS SMTP";
} else {
processEmail($to, $message, 1);
echo "SMTP Failed - Attempted to send without SMTP ";
}
Looking at your existing code, I've gathered that your relaying mail over another SMTP server so unsure why your testing if TLS is available. Does your relaying server sometimes fail on TLS? The below solution would be best suited using OOP as this function is a bit excessive. I've heavily commented so my logic should be pretty straight forward. Some of the key points is that the function is Recursive meaning it will call it self if TLS fails keeping the code running inside one function. Secondly, re-using PHP Mailer with the same execution will have issues so I have unset() the initial $mail object on second call as well as setting the include to require_once. As noted, you will need to check with your SMTP provider on the TLS port used and SMTP port (if any) to ensure it works. I've tested with my provider and this works with no issues.
function sendEmail($to, $message, $skip_smtp=1) {
date_default_timezone_set('Europe/London');
require_once 'PHPMailer/PHPMailerAutoload.php';
//You will need to check your provider for these settings
if ($skip_smtp === 0) {
$port = 25; //Usual port for non TLS/SSL
} else {
$port = 465; //Port for relay server - likely to be 25, 465 or 587
$mail->SMTPSecure = 'tls'; //Send via TLS Encryption - SSL or TLS (Dependent on Relay Server)
}
$mail = new PHPMailer();
$mail->SMTPDebug = 3; //Enabled this so you can see what's happening - Dont forget to set to 0 in production
$mail->Debugoutput = 'html';
//SMTP Relay Server Settings
$mail->isSMTP(); //Send as SMTP - Should always be set unless you would like to use another method like sendmail()
$mail->Host = 'smtp.relay.com';
$mail->Port = $port;
$mail->Timeout = 5; //Set your Timeout in Seconds - Default is 5mins which is abit excessive when testing
$mail->SMTPAuth = true; //Relay Server Auth Details
$mail->Username = "SMTP RELAY USERNAME";
$mail->Password = "SMTP RELAY PASSWORD";
//Email Details
$mail->setFrom('test#test.com');
$mail->addAddress($to);
$mail->Subject = 'My Subject';
//Email Content
$mail->isHTML(true); //Set HTML
$mail->Body = $message; //HTML Body
$mail->AltBody = $message; //Failover for Non-HTML
switch ($mail->send()) {
case false:
if ($skip_smtp === 0) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Error Sending TLS...trying Non TLS';
unset($mail); //Unset Object
sendEmail($to, $message, $skip_smtp=0); //Recursive function -> passing 0 to skip TLS
}
break;
case true :
echo 'Message has been sent';
break;
default :
echo 'Error';
}
}
//Your Function
sendEmail('test#test.com', 'Test Body');
?>

PHPMailer - Could not authenticate

I've been running PHPMailer for a year now on a php server. Everything was fine until 3 days ago when I started getting the following error:
SMTP Error: Could not authenticate.
Allow less secure apps is ON
Here is the code:
function SendEmail($to,$cc,$bcc,$subject,$body) {
require 'PHPMailerAutoload.php';
$mail = new PHPMailer(true);
$mail->SMTPDebug = 1;
try {
$addresses = explode(',', $to);
foreach ($addresses as $address) {
$mail->AddAddress($address);
}
if($cc!=''){
$mail->addCustomHeader("CC: " . $cc);
}
if($bcc!=''){
$mail->addCustomHeader("BCC: " . $bcc);
}
$mail->IsSMTP();
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->SMTPSecure = "tls"; // sets the prefix to the servier
$mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
$mail->Port = 587;
$mail->Username = "myemail#gmail.com"; // SMTP username
$mail->Password = "myemailpass"; // SMTP password
$webmaster_email = "myemail#gmail.com"; //Reply to this email ID
$name=$email;
$mail->From = $webmaster_email;
$mail->FromName = "Service";
//$mail->AddReplyTo($webmaster_email, "DiFractal Customer Service");
$mail->WordWrap = 50; // set word wrap
$mail->IsHTML(true); // send as HTML
$mail->Subject = $subject;
$mail->Body = $body;
return $mail->Send();
} catch (phpmailerException $e) {
$myfile = fopen("debug_email.txt", "w");
fwrite($myfile,$e->errorMessage() . "\n" . $mail->ErrorInfo);
fclose($myfile);//Pretty error messages from PHPMailer
} catch (Exception $e) {
$myfile = fopen("debug_email_stp.txt", "w");
fwrite($myfile,$e->getMessage());
fclose($myfile);//Pretty error messages from PHPMailer
}
}
Note I just updated PHPMailer to the latest version to try to remedy the problem but nothing has changed! The old version 5.2.2 was still having the same problem!
EDIT: I just had one successful email go through to google and sent properly. Which now makes me question if it's lag issue or something of that sort. Does anyone know how phpmailer functions under high loads or if high loads can cause the above error?
Try going to:
myaccount.google.com -> "connected apps & sites", and turn "Allow less secure apps" to "ON".
Alternative:
Try changing SMTP Port to: 465 (gmail also).
I was having similar issues and needed to set the from address
$mail->setFrom('myemail#gmail.com', 'Webmaster');
Make sure you check google's usage limits! PHPMailer will not tell you particulars it will just give you the Could not authenticate error but the reason why can be because of your limits.
# https://support.google.com/a/answer/166852?hl=en
Upgraded to a new account with google business and switched to that account. Issue resolved.

PHPMailer: Mass Emails - Send all variable messages at once, instead of individually

i'm currently trying to figure out the best way to do this.
The current system i've made sends email one by one and fills in the information for each entry as in the array, such as email, first name and last name.
The problem here is if i send alot of messages it takes forever to run through as it's calling a function everytime, instead i want it to send them all at once through one single function.
I know you can add multiple to's but then the body of the email won't send the correct information relative to each email. If anyone can help me with this i'd really appreciate it, as i've searched all over for a solution.
<?php
require '../phpmailer/PHPMailerAutoload.php';?>
<?php
/* Block List */
$blocklist = array('emailblocked#gmail.com', 'emailblocked2#gmail.com');
$emaillist = array(
array(
'Email'=>'example#gmail.com',
'First Name'=>'John',
'Last Name'=>'Doe'
),
array(
'Email'=>'example2#gmail.com',
'First Name'=>'Joe',
'Last Name'=>'Doe'
),
array(
'Email'=>'example3#gmail.com',
'First Name'=>'Jane',
'Last Name'=>'Doe'
),
);
foreach($emaillist as $emailkey){
if (in_array($emailkey['Email'], $blocklist)) {
echo 'Message has been been blocked for '.$emailkey['Email'].'<br>';
}else{
$mail = new PHPMailer;
// $mail->SMTPDebug = 3; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.mandrillapp.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'username#example.com'; // SMTP username
$mail->Password = 'passwordgoeshere'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
$mail->From = 'noreply#example.com';
$mail->FromName = 'Example';
$mail->addAddress($emailkey['Email'], $emailkey['First Name'].' '.$emailkey['Last Name']); // Add a recipient
$mail->addReplyTo('info#example.com', 'Information');
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $emailkey['First Name'].' '.$emailkey['Last Name'];
$emailtemp = file_get_contents('templates/temp-1.html');
$emailtempfilteremail = str_replace("[[email]]", $emailkey['Email'], $emailtemp);
$emailtempfilterfirstname = str_replace("[[firstname]]", $emailkey['First Name'], $emailtempfilteremail);
$emailtempfilterlastname = str_replace("[[lastname]]", $emailkey['Last Name'], $emailtempfilterfirstname);
$mail->Body = $emailtempfilterlastname;
$mail->AltBody = 'This is a spicy email!';
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent to '.$emailkey['Email'].'<br>';
}
$mail->ClearAllRecipients();
}
}
?>
Thank you
There's an example of how to send to a list from a database efficiently in the examples bundled with PHPMailer. There's nothing inherently likely to get you blacklisted by using PHPMailer for sending large volumes, but you do need to tread carefully. Mandrill isn't magic - it's as vulnerable as anything else to being blocked if you send spam through it.
If you want to send 50 simultaneously from PHP, fire up multiple processes with the pcntl extension, but it won't actually help you very much as you'll be increasing overhead enormously. You can set SMTPKeepAlive = true in PHPMailer which will reduce overhead a lot (it avoids making a new connection for every message), but it still won't send simultaneous messages - nothing will. There isn't an option in SMTP to send multiple messages with different bodies simultaneously on the same connection.
Sending to a big list during a page load in a browser is very unreliable; use a cron script or background process to do your actual sending and just set it up through your web interface. One tip if you are waiting for a page load - call ignore_user_abort() early on so that it won't stop sending if your browser closes the connection - and beware the page refresh! If you want to send much faster, install a local mail server like postfix and use that to relay - it will be far faster and more reliable than sending directly.
Yes, it is possible with a modification of your code, the problem is not with the PHPMailer itself, but with your approach. You should avoid using an new instance of the class inside a loop (this leads to memory exhaustion with large lists), instead, only invoke $mail->addAddress(...) or $mail->Subject(...) inside the foreach loop.
If you read the source code of the PHPMailer, you will notice how exactly the functions addAddress(), Subject() or Body() works.
Your code should look something like this:
<?php
/*Move your "generic" initialization outside the loop*/
$mail = new PHPMailer;
// $mail->SMTPDebug = 3; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.mandrillapp.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'username#example.com'; // SMTP username
$mail->Password = 'passwordgoeshere'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
$mail->From = 'noreply#example.com';
$mail->FromName = 'Bet Monkey';
$mail->isHTML(true); // Set email format to HTML
$mail->addReplyTo('info#example.com', 'Information');
$emailtemp = file_get_contents('templates/temp-1.html');
$mail->AltBody = 'This is a spicy email!';
/*Start the loop by adding email addresses*/
foreach($emaillist as $emailkey){
if (in_array($emailkey['Email'], $blocklist)) {
echo 'Message has been been blocked for '.$emailkey['Email'].'<br>';
}else{
$mail->addAddress($emailkey['Email'], $emailkey['First Name'].' '.$emailkey['Last Name']); // Add a recipient
$mail->Subject = $emailkey['First Name'].' '.$emailkey['Last Name'];
$emailtempfilteremail = str_replace("[[email]]", $emailkey['Email'], $emailtemp);
$emailtempfilterfirstname = str_replace("[[firstname]]", $emailkey['First Name'], $emailtempfilteremail);
$emailtempfilterlastname = str_replace("[[lastname]]", $emailkey['Last Name'], $emailtempfilterfirstname);
$mail->Body = $emailtempfilterlastname;
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent to '.$emailkey['Email'].'<br>';
}
$mail->ClearAllRecipients();
}
}
Using the above approach I personally have send hundreds of thousands emails, but, as they say in the comments - you'll risking to be blacklisted (you can check here or here for details).

Sending 2 emails with PHP mailer fails

I am rather puzzled with this one.
//SMTP servers details
$mail->IsSMTP();
$mail->Host = "mail.hostserver.com";
$mail->SMTPAuth = false;
$mail->Username = $myEmail; // SMTP usr
$mail->Password = "****"; // SMTP pass
$mail->SMTPKeepAlive = true;
$mail->From = $patrickEmail;
$mail->FromName = "***";
$mail->AddAddress($email, $firstName . " " . $lastName);
$mail->WordWrap = 50;
$mail->IsHTML(true);
$mail->Subject = $client_subject;
$mail->Body = $client_msg;
if($mail->Send())
{
$mail->ClearAllRecipients();
$mail->ClearReplyTos();
$mail->ClearCustomHeaders();
...
$mail->From = "DO_NOT_REPLY#...";
$mail->FromName = "****";
$mail->AddAddress($ToEmail1, "***"); //To: (recipients).
$mail->AddAddress($ToEmail2, "***"); //To: (recipients).
$mail->WordWrap = 50;
$mail->IsHTML(true);
$mail->Subject = $notification_subject;
$mail->Body = $notification_msg;
if($mail->Send())
{
...
The first email sends fine. The second one doesn't. What could be the reason for that behavior? Am I missing some kind of reset?
Update: using a different mail server seems to work so apparently it's a setting of that specific mail server causing problems. Any idea what that could be?
Some providers impose restrictions on the number of messages that can be sent within a specific time span. To determine if your problem depends by a provider "rate limit", you should try to add a pause after the first send. For example:
if ($mail->Send()) {
sleep(10); // Seconds
...
if ($mail->Send()) {
...
}
}
Then, by progressively lowering the sleep time, you should be able to determine which is the rate limit.
Try this:
As #Felipe Alameda A mentioned Remove $mail->SMTPKeepAlive = true;
// for every mail
if(!$mail->Send())
{
echo 'There was a problem sending this mail!';
}
else
{
echo 'Mail sent!';
}
$mail->SmtpClose();
IMHO you need to create new PHPMailer object for every sent email. If you want to share some common setup, use something like this:
$mail = new PHPMailer();
/* Configure common settings */
while ($row = mysql_fetch_array ($result)) {
$mail2 = clone $mail;
$mail2->MsgHTML("Dear ".$row["fname"].",<br>".$cbody);
$mail2->AddAddress($row["email"], $row["fname"]);
$mail2->send();
}
I think your problem is $mail->SMTPAuth = false;
It is hard to believe there are ISP or SMTP providers that don't require authentication, even if they are free.
You may try this to check for errors instead of or in addition to checking for send() true:
if ( $mail->IsError() ) { //
echo ERROR;
}
else {
echo NO ERRORS;
}
//Try adding this too, for debugging:
$mail->SMTPDebug = 2; // enables SMTP debug information
Everything else in your code looks fine. We use PHPMailer a lot and never had any problems with it
The key may lie in the parts you have omitted. Is the domain of the sender of both emails the same? Otherwise the SMTP host may see this as a relay attempt. If you have access to the SMTP server logs, check these; they might offer a clue.
Also, check what $mail->ErrorInfo says... it might tell you what the problem is.
i personally would try to make small steps like sending same email.. so just clear recipients and try to send identical email (this code works for me). If this code passes you can continue to adding back your previous lines and debug where it fails
and maybe $mail->ClearCustomHeaders(); doing problems
//SMTP servers details
$mail->IsSMTP();
$mail->Host = "mail.hostserver.com";
$mail->SMTPAuth = false;
$mail->Username = $myEmail; // SMTP usr
$mail->Password = "****"; // SMTP pass
$mail->SMTPKeepAlive = true;
$mail->From = $patrickEmail;
$mail->FromName = "***";
$mail->AddAddress($email, $firstName . " " . $lastName);
$mail->WordWrap = 50;
$mail->IsHTML(true);
$mail->Subject = $client_subject;
$mail->Body = $client_msg;
// all above is copied
if($mail->Send()) {
sleep(5);
$mail->ClearAllRecipients();
$mail->AddAddress('another#email.com'); //some another email
}
...
Try with the following example.,
<?php
//error_reporting(E_ALL);
error_reporting(E_STRICT);
date_default_timezone_set('America/Toronto');
require_once('../class.phpmailer.php');
//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
$mail = new PHPMailer();
$body = file_get_contents('contents.html');
$body = eregi_replace("[\]",'',$body);
$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host = "mail.yourdomain.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->Host = "mail.yourdomain.com"; // sets the SMTP server
$mail->Port = 26; // set the SMTP port for the GMAIL server
$mail->Username = "yourname#yourdomain"; // SMTP account username
$mail->Password = "yourpassword"; // SMTP account password
$mail->SetFrom('name#yourdomain.com', 'First Last');
$mail->AddReplyTo("name#yourdomain.com","First Last");
$mail->Subject = "PHPMailer Test Subject via smtp, basic with authentication";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
$address1 = "whoto#otherdomain.com";
$address2 = "whoto#otherdomain.com";
$mail->AddAddress($address1, "John Doe");
$mail->AddAddress($address2, "John Peter");
$mail->AddAttachment("images/phpmailer.gif"); // attachment if any
$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment if any
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
?>
Note : Better you can make a multiple user email and name as an ARRAY, like
<?php
$recipients = array(
'person1#domain.com' => 'Person One',
'person2#domain.com' => 'Person Two',
// ..
);
foreach($recipients as $email => $name)
{
$mail->AddCC($email, $name);
}
(or)
foreach($recipients as $email => $name)
{
$mail->AddAddress($email, $name);
}
?>
i think this may help you to resolve your problem.
I think you've got organizational problems here.
I recommend:
Set your settings (SMTP, user, pass)
Create new email object with info from an array holding messages and to addresses
Send email
Goto step 2

Categories