Sending multiple emails with PHPmailer - php

Edit: I forgot I'd created the SendMail(); function myself, which is why the explanation doesn't mention at first what it does.
I'm having some trouble with PHPMailer (https://github.com/PHPMailer/PHPMailer) when attempting to send two emails, one directly after the other.
The script is almost completely 'out of the box', with only a few modifications such as a foreach loop to allow for multiple addresses, and everything still works perfectly.
However, if I attempt to call more than one instance of SendMail(); I get the error message:
Fatal error: Cannot override final method Exception::__clone() in .... online 0
Previously I was using the in-built mail(); function, which allowed me to use it as many times as I liked in quick succession , but it doesn't appear to be that simple with PHPmailer:
$to = me#me.com;
$to2 = me2#me2.com';
$headers = 'php headers etc';
$subject = 'generic subject';
$message = 'generic message';
mail($to, $subject, $message, $headers);
mail($to2, $subject, $message, $headers);
The above would result in two identical emails being sent to different people, however I can't easily replicate this functionality with PHPmailer.
Is there a way of stacking these requests so that I can send successive emails without it failing? Forcing the script to wait until the first email has been sent would also be acceptable, although not preferential.
As I mentioned I know it works when only one instance is called, but I don't seem to be able to re-use the function.
I haven't included the source code, although it is all available on the link provided above.
Thanks in advance
Edit as requested
// First Email
$to = array(
'test#test.com',
'test2#test.com',);
$subject = "Subject";
$message = $message_start.$message_ONE.$message_end;
sendMail();
// Second Email
$to = array(
'test#test.com',
'test2#test.com',);
$subject = "Subject";
$message = $message_start.$message_TWO.$message_end;
sendMail();
The above is how I want this to work, as it would work with mail();. The first email will work fine, the second will not.
SendMail() code
This is from the PHPmailer website, and is what is defined as SendMail();. The only difference from the example is the loop for AddAddress, and the inclusion of $to as a global variable.
$mail = new PHPMailer();
$mail->IsSMTP(); // set mailer to use SMTP
$mail->Host = "smtp1.example.com;smtp2.example.com"; // specify main and backup server
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "jswan"; // SMTP username
$mail->Password = "secret"; // SMTP password
$mail->From = "from#example.com";
$mail->FromName = "Mailer";
foreach($to as $to_add){
$mail->AddAddress($to_add); // name is optional
}
$mail->AddReplyTo("info#example.com", "Information");
$mail->WordWrap = 50; // set word wrap to 50 characters
$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 = "Here is the subject";
$mail->Body = "This is the HTML message body <b>in bold!</b>";
$mail->AltBody = "This is the body in plain text for non-HTML mail clients";
if(!$mail->Send())
{
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
echo "Message has been sent";

You haven't posted this code that lets me make this a complete conclusion, but from the Exception and the way you've defined an overriding class inside a function, you probably have class.phpmailer.php loading every time like this:
require('class.phpmailer.php');
or
include('class.phpmailer.php');
You should change that line to
require_once('class.phpmailer.php');
The reason you need to change it to require_once is so that PHP will not load the class file the second time when you try to create the new/second PHPMailer class. Otherwise, the line class PHPMailer throws the __clone() exception.

Added an example below:
<?php
/**
* This example shows how to send a message to a whole list of recipients efficiently.
*/
//Import the PHPMailer class into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
error_reporting(E_STRICT | E_ALL);
date_default_timezone_set('Etc/UTC');
require '../vendor/autoload.php';
//Passing `true` enables PHPMailer exceptions
$mail = new PHPMailer(true);
$body = file_get_contents('contents.html');
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->SMTPKeepAlive = true; // SMTP connection will not close after each email sent, reduces SMTP overhead
$mail->Port = 25;
$mail->Username = 'yourname#example.com';
$mail->Password = 'yourpassword';
$mail->setFrom('list#example.com', 'List manager');
$mail->addReplyTo('list#example.com', 'List manager');
$mail->Subject = 'PHPMailer Simple database mailing list test';
//Same body for all messages, so set this before the sending loop
//If you generate a different body for each recipient (e.g. you're using a templating system),
//set it inside the loop
$mail->msgHTML($body);
//msgHTML also sets AltBody, but if you want a custom one, set it afterwards
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
//Connect to the database and select the recipients from your mailing list that have not yet been sent to
//You'll need to alter this to match your database
$mysql = mysqli_connect('localhost', 'username', 'password');
mysqli_select_db($mysql, 'mydb');
$result = mysqli_query($mysql, 'SELECT full_name, email, photo FROM mailinglist WHERE sent = FALSE');
foreach ($result as $row) {
try {
$mail->addAddress($row['email'], $row['full_name']);
} catch (Exception $e) {
echo 'Invalid address skipped: ' . htmlspecialchars($row['email']) . '<br>';
continue;
}
if (!empty($row['photo'])) {
//Assumes the image data is stored in the DB
$mail->addStringAttachment($row['photo'], 'YourPhoto.jpg');
}
try {
$mail->send();
echo 'Message sent to :' . htmlspecialchars($row['full_name']) . ' (' . htmlspecialchars($row['email']) . ')<br>';
//Mark it as sent in the DB
mysqli_query(
$mysql,
"UPDATE mailinglist SET sent = TRUE WHERE email = '" .
mysqli_real_escape_string($mysql, $row['email']) . "'"
);
} catch (Exception $e) {
echo 'Mailer Error (' . htmlspecialchars($row['email']) . ') ' . $mail->ErrorInfo . '<br>';
//Reset the connection to abort sending this message
//The loop will continue trying to send to the rest of the list
$mail->getSMTPInstance()->reset();
}
//Clear all addresses and attachments for the next iteration
$mail->clearAddresses();
$mail->clearAttachments();
}

In addition to #Amr most excellent code.
In order to use this in a cron fasion, two adds are useful.
$mail-> SMTPDebug = true;
$mail-> Debugoutput = function( $str, $level ) {_log($str);};
The function _log is up to you. Writing to a file, to a database or wherever. I personally have reduced this to
$mail-> Debugoutput = function( $str, $level ) {if( $level===3 ) {_log( $str ); } };
to only write the more juicier messages

the solution is to reset recipients data like this:
$Mailer->clearAddresses()
use your own variable as an instance of PHPMailer (instead of $Mailer)

$Mailer->clearAddresses()
This is the solution to avoid multiple msj to be send to the same recipient.

Related

Send multiple email address using phpmailer function

I have a problem sending multiple email addresses functions. If I send a single email address, I can work. If I send multiple emails to the receiver, they cannot receive my message. I am using the PHPMailer function to do the email function with XAMPP. I am using the PHP array function to put the receiver's address in the array and use the while function to loop the receiver address to send it.
Below is my coding:
$address = array('st9overfindsolution#gmail','st7overfindsolution#gmail');
require 'class/class.phpmailer.php';
$mail = new PHPMailer(true);
$mail->IsSMTP();
$mail->Host = 'smtp.gmail.com';
// $mail->SMTPDebug = 1;
$mail->Port = 465;
$mail->SMTPAuth = true;
$mail->Username = 'example#gmail.com';
$mail->Password = '1233aqqq';
$mail->SMTPSecure = 'ssl';
$mail->From = $_POST["email"];
$mail->FromName = $_POST["name"];
$mail->AddCC($_POST["email"], $_POST["name"]);
$mail->WordWrap = 50;
$mail->IsHTML(true);
$mail->Subject = $_POST["subject"];
$mail->Body = $_POST["message"];
while(list ($key, $val) = each($address)){
$mail->AddAddress($val);
}
What I've tried?
1.I put all receiver email addresses in the array $address = array('st9overfindsolution#gmail','st7overfindsolution#gmail'); and use below while function code, but cannot work.
2.If send single email address without using while function, just can work, like below coding:
Hope someone can guide me on how to solve this problem. Thanks.
i have created new function named "sendmyemail" and inserted the code inside this function, so you can sent multiple emails by calling this function with email address.
<?php
/**
* This example shows sending a message using a local sendmail binary.
*/
//Import the PHPMailer class into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
require '../vendor/autoload.php';
function sendmyemail($whotoEmail){
//Create a new PHPMailer instance
$mail = new PHPMailer();
//Set PHPMailer to use the sendmail transport
$mail->isSendmail();
//Set who the message is to be sent from
$mail->setFrom('from#example.com', 'First Last');
//Set who the message is to be sent to
$mail->addAddress($whotoEmail);
//Set the subject line
$mail->Subject = 'PHPMailer sendmail test';
//Read an HTML message body from an external file, convert referenced images to
embedded,
//convert HTML into a basic plain-text alternative body
$mail->msgHTML(file_get_contents('contents.html'), __DIR__);
//Replace the plain text body with one created manually
$mail->AltBody = 'This is a plain-text message body';
//Attach an image file
$mail->addAttachment('images/phpmailer_mini.png');
//send the message, check for errors
if (!$mail->send()) {
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message sent to '.$whotoEmail.'!';
}
}
sendmyemail('abcduser#gmail.com');
sendmyemail('efguser#gmail.com');
sendmyemail('hijkuser#gmail.com');
sendmyemail('lmnouser#gmail.com');

What's the right workaround to send DIFFERENT messages to DIFFERENT recipients in PHPMailer

I am trying to send an email to multiple different BCC recipients.
Every recipient gets an identical text body BUT, he also needs to receive his own individual email in it.
I'm looping through a JSON to add emails with the $mail->addBCC() function.
And I need that the $body that is sent to every individual user will contain his own individual address.
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;
require 'src/Exception.php';
require 'src/PHPMailer.php';
require 'src/SMTP.php';
//*** -> $allUsers is a JSON
function sendemails_ex($allUsers, $subject, $body)
{
$emailFrom = "noreply#slandergold.com";
$emailFromName = "slandergold.com";
if ($allUsers=="" || $subject=="" || $body=="")
{
exit();
}
$smtpUsername = "abcdKLARK";
$smtpPassword = "1t%y$R5$4";
$mail = new PHPMailer;
$mail->CharSet = 'UTF-8';
$mail->isSMTP();
$mail->SMTPDebug = 0;
$mail->Host = "mail.slandergold.com";
$mail->Port = 26; //587; // TLS only
$mail->SMTPSecure = false; //'tls'; // ssl is depracated
$mail->SMTPAuth = false; //true;
$mail->Username = $smtpUsername;
$mail->Password = $smtpPassword;
$mail->setFrom($emailFrom, $emailFromName);
$arr = json_decode($allUsers,true);
foreach($arr as $item)
{
$mail->addBCC($item['Email'], $item['Fullname']);
}
$mail->isHTML(true);
$mail->Subject = $subject;
// ***********
// is there a way to make it
// so that every individual BCC recipient
// will get a body with the individual addition of:
// $userEmail = ?
// $body."<br />This is your email: ".$userEmail;
// ***********
$mail->msgHTML($body);
$mail->AltBody = 'HTML messaging not supported';
if(!$mail->send())
{
echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
echo "Message sent!";
}
}
As the comments say, you can’t send different emails to different recipients using BCC. You need to send each message individually, and the definitive way to do that is provided in the mailing list example provided with PHPMailer. There are also notes in the project wiki about how to send to lists efficiently.

Use array of emails and names from database in PHPMailer

I'm using PHPMailer to send an email from a form to all the emails in a MySQL database.
I've managed to get the form to send an email to each email but I'm now trying to use their name in the email sent to them meaning each email woud begin with "Hello, [their-name],".
I'm using an array to loop through the results of my database query and adding each email and name as $mail->addAddress('email#email.com, 'name');
I've tried saving the variable $name = $row['name'}; inside the while loop but it inputs the last name from the database into all the emails.
My question is: Is it possible to access the 'name' part of the function and use it each email. Or is it better to take their name from the database itself? And if so how would I go about doing that?
Also, when the email sends to each recipient, it shows all of the recipients in the "To:" field. This would be pretty bad for privacy. Is there a way to prevent this?
I'm fairly new to PHP and MySQL still so explanatory answers would be greatly appreciated.
Please find my code below.
<?php
// Take message value from form
$message = preg_replace("/\r\n|\r/", "<br />", $_REQUEST['message']);
$message = trim($message);
// Error reporting on
error_reporting(E_STRICT | E_ALL);
date_default_timezone_set('Etc/UTC');
// Require PHPMailer
require 'PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->SMTPKeepAlive = true; // SMTP connection will not close after each email sent, reduces SMTP overhead
$mail->Port = 587;
$mail->Username = 'my#email.com';
$mail->Password = 'mypassword';
$mail->setFrom('myemail#email.com', 'Me');
$mail->addReplyTo('myemail#email.com', 'Me');
$mail->Subject = "Newsletter";
/* ----- Add address function below ----- */
// Require Database connection
require 'dbcon.php';
// SELECT email and name values from database
$query = "SELECT email, name FROM customers";
// Result = the database query
$result = $con->query($query);
// Get array of users email addresses and names.
while($row = $result->fetch_array())
{
// Add recipients from values found in database
$mail->addAddress($row["email"], $row["name"]);
}
/* ----- Add address function above ----- */
$mail->Body ="Hello, <br> <br> $message";
$mail->AltBody = $message;
if(!$mail->Send())
{
echo "Message could not be sent.";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
print 'Sent!';
?>
You are currently setting up to send a single email with several recipients. For security and etiquette, you should address the email to yourself (outside the loop):
$mail->addAddress('myemail#email.com', 'Me');
...and then add all of the recipients as BCC (inside the loop):
$mail->addBCC($row["email"], $row["name"]);
As for the name field. Add a debug line inside your loop and take a look at your output. Is the name field the same each time?
print "Adding recipient: {$row['email']} {$row['name']}";
If you want to sent several emails, one to each recipient, you need to instantiate a new email inside the loop each time.
[UPDATE]
If you want to send a single message to each recipient, then instantiate a new email each time (inside your loop):
<?php
// Take message value from form
$message = preg_replace("/\r\n|\r/", "<br />", $_REQUEST['message']);
$message = trim($message);
// Error reporting on
error_reporting(E_STRICT | E_ALL);
date_default_timezone_set('Etc/UTC');
// Require PHPMailer
require 'PHPMailer/PHPMailerAutoload.php';
// Require Database connection
require 'dbcon.php';
// SELECT email and name values from database
$query = "SELECT email, name FROM customers";
// Result = the database query
$result = $con->query($query);
// Get array of users email addresses and names.
while($row = $result->fetch_array())
{
// Instantiate a NEW email
$mail = new PHPMailer;
// Set the email settings
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->SMTPKeepAlive = true; // SMTP connection will not close after each email sent, reduces SMTP overhead
$mail->Port = 587;
$mail->Username = 'my#email.com';
$mail->Password = 'mypassword';
$mail->setFrom('myemail#email.com', 'Me');
$mail->addReplyTo('myemail#email.com', 'Me');
$mail->Subject = "Newsletter";
// Add recipient from values found in database
$mail->addAddress($row["email"], $row["name"]);
$mail->Body ="Hello, <br> <br> $message";
$mail->AltBody = $message;
if(!$mail->Send())
{
echo "Message could not be sent.";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
print "Sent mail to: {$row["email"]}, {$row["name"]}";
}
?>

Fatal error: Call to undefined method stdClass::AddAddress() in PHP mailer

I'm trying to send an e-mail to multiple e-mail address in my database. Here is my current code.I need to have them query my database and send the e-mail to each e-mail address.It is working but email was send to the first e-mail address only, and got an error "Fatal error: Call to undefined method stdClass::AddAddress()".Where am I going wrong here?
<?php
$elist = $database->getRows("SELECT * FROM `emails`");
foreach($elist as $emails){
$frm = 'test#gmail.com';
$sub = 'Weekly Work Report';
ob_start();
include_once('mail_content.php');
$mail_body = ob_get_contents();
ob_end_clean();
$to = $emails['email'];
$mailstatus = lm_mail('1', '2', $to, '3', $frm, 'HR', $sub, $mail_body);
if ($mailstatus == 'ok') {
$response->redirect('index.php?com_route=user_report');
} else {
echo $mailstatus;
}
}
?>
function lm_mail($head_mid='',$head_mname='',$to_mid ,$to_mname='',$reply_mid,$reply_mname='',$subject,$body,$attachments='')
{
include_once 'phpmailer/mail_config.php';
if(SMTP_mail)
{
// Send SMTP Mails
$mail->From =$head_mid ; // From Mail id
$mail->FromName = $head_mname; // From Name
$mail->AddAddress($to_mid,$to_mname); // To Address
$mail->AddReplyTo($reply_mid,$reply_mname); // From Address
$mail->Subject=$subject;
$mail->Body = $mail_body.$body; //HTML Body
$mail->AltBody = "This is the body when user views in plain text format"; //Text Body
if(!$mail->Send())
{
return $mail->ErrorInfo;
}
else
{
return 'ok';
}
}
else
{
$mail = new PHPMailer(); // defaults to using php "mail()"
$mail->AddReplyTo($reply_mid,$reply_mname); // Sender address
$mail->AddReplyTo($reply_mid,$reply_mname); // replay to address
$address = $to_mid; // to addtesas
$mail->AddAddress($address, $to_mname);
$mail->Subject = $subject;
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($mail_body.$body);
if(!$mail->Send())
{
return $mail->ErrorInfo;
}
else { return 'ok'; }
}
}
In the first conditional of the lm_mail function call there is no object being instantiated.
if(SMTP_mail)
{
// No $mail object?
// Send SMTP Mails
$mail->From =$head_mid ; // From Mail id
Try adding:
if(SMTP_mail)
{
$mail = new PHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP
// Have to manually set language if PHPMailer can't determine
$mail->SetLanguage("en", 'includes/phpMailer/language/');
I'm guessing you are using SMTP, because I don't see where $mail comes from.
Since one email is sending, my guess is that phpmailer/mail_config.php sets up a $mail object and sets the SMTP_mail constant, and then it goes out of scope after the first function call and the file is only included once so it doesn't get defined again.
After that it wasn't defined as a PHPMailer object, so it is cast as a stdClass when you do the object assignment $mail->From = $head_mid.
Try taking the code out of mail_config.php and replicating it in your send function, or add a function to mail_config.php that provides a factory to getting a PHPMailer object that is configured for your needs.

PHP - Query database for pending messages and call PHPmailer without refresh

I am using phpMailer, and i have a database table "list" with columns id|name|email|status.
What i am doing currently is using the phpMailer example
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);
$id = $_GET['id'];
$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host = "smtp1.xample.com;smtp2.xample.com";
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPKeepAlive = true; // SMTP connection will not close after each email sent
$mail->Host = "mail.example.com"; // sets the SMTP server
$mail->Port = 25; // set the SMTP port for the GMAIL server
$mail->Username = "no-reply#example.com"; // SMTP account username
$mail->Password = "password"; // SMTP account password
$mail->SetFrom('no-reply#example.com', 'Honda example');
$mail->AddReplyTo('no-reply#example.com', 'Honda example');
$mail->Subject = "PHPMailer Test Subject via smtp, basic with authentication";
#MYSQL_CONNECT("localhost","root","password");
#mysql_select_db("osher");
$query = "SELECT full_name, email, photo FROM employee WHERE id=$id";
$result = #MYSQL_QUERY($query);
while ($row = mysql_fetch_array ($result)) {
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
$mail->AddAddress($row["email"], $row["full_name"]);
$mail->AddStringAttachment($row["photo"], "YourPhoto.jpg");
if(!$mail->Send()) {
echo "Mailer Error (" . str_replace("#", "#", $row["email"]) . ') ' . $mail->ErrorInfo . '<br />';
} else {
echo "Message sent to :" . $row["full_name"] . ' (' . str_replace("#", "#", $row["email"]) . ')<br />';
}
// Clear all addresses and attachments for next loop
$mail->ClearAddresses();
$mail->ClearAttachments();
}
Now the code above is db-email.php Where in if my table, email has over 100 entries with status as pending, i want to be able to using php. select each rows id and call db-email.php?id=xx (where x is the id) hence the email gets sent.
This works fine, if its done manually.
i needed you guys to help me, how best I can automate this process, that is to be able to push this 100 emails (without having to refresh the page)
assuming, I am on email.php where I can probably hit (a button) and it would simply start processing, each of the row in the email table, (instead of echo'n the result) I will be updating the database with status to = 'sent'
I am not sure if I have been very clear on what I want to ask, Please do help friends.
I believe someone with expertise in jQuery/AJAX or something could help me achieve this task :)
I'm not sure what your trying to do but, you can't do anything with databases or servers via javascript or jquery because there executed in the browser and not on the server.
You could use ajax to call certain .php files on the server with some parameters to do your job !

Categories