I'm trying to send an email to multiple recipients using phpmailer and getting the emails list from my table in the database, however, whenever I make a request only one recipient, the first one on the list gets the email. *I know this might be marked as duplicate but I couldn't find a similar example using mysql
<?php
if (isset($_POST['submit'])) {
if (empty($errors)) {
$thisType = mysql_prep($_POST["partner_type"]);
$content = $_POST["content"];
$header = $_POST["header"];
$query = "SELECT * FROM partners_list WHERE partner_type = '$thisType' ";
$result = mysqli_query($connection, $query);
$count = mysqli_num_rows($result);
while($row = mysqli_fetch_assoc($result)){
require_once("phpMailer/class.phpmailer.php");
require_once("phpMailer/class.smtp.php");
require_once("phpMailer/language/phpmailer.lang-uk.php");
$to_name = "Order";
$subject = $header;
$message = $content;
$message = wordwrap($message,70);
$from_name = "thisCompany";
$from = "noreply#thicCompany.com";
$mail = new PHPMailer();
$mail->AddAddress($row['email'], "Test Message"); // add each DB entry to list of recipients
$mail->FromName = $from_name;
$mail->From = $from;
$mail->Subject = $subject;
$mail->Body = $message;
$result = $mail->Send();
// Success
$_SESSION["message"] = "e-mail successfully sent.";
redirect_to("successpage.php");
}
}
} else {
}
?>
Related
I've been trying many different ways to prevent PHP Mailer from appending every email address coming from my DB to every single email.
I feel it doesn't look right for every user to receive an email from my website and being able to see a few other thousand emails appended to that same email as well.
Here's my code, I already tried to many diferent things:
$query_select = "SELECT * FROM users";
$query = mysqli_query($connection, $query_select);
if($select_to == 'all'){
while($row = mysqli_fetch_assoc($query)) {
$user_email = $row['user_email'];
$send_to = $user_email;
$mail->setFrom('example#gmail.com', 'My website');
$mail->addAddress($send_to);
$mail->isHTML(true);
$mail->Subject = $subject_email;
$mail->Body = $content_email;
$mail->AltBody = $content_email;
}
} else {
if($select_to == 'single'){
$send_to = $to_single_email;
}
}
if($mail->send()){
$confirm = 'Sent.';
$send = array(
'confirm'=>$confirm
);
echo json_encode($send);
} else {
$confirm = 'There was en error while sending this email.';
$send = array(
'confirm'=>$confirm
);
echo json_encode($send);
}
$mail->send() will send to all addresses via a single message. Instead you need to send one message per recipient.
The while() loop would be refactored similar to:
while($row = mysqli_fetch_assoc($query)) {
$user_email = $row['user_email'];
$send_to = $user_email;
$mail->setFrom('example#gmail.com', 'My website');
$mail->addAddress($send_to);
$mail->isHTML(true);
$mail->Subject = $subject_email;
$mail->Body = $content_email;
$mail->AltBody = $content_email;
$mail->send();
$mail->clearAllRecipients();
}
The call to clearAllRecipients() will clear out the previous addresses that would otherwise accumulate via addAddress()
You'll also need to add the error checking within the loop for each call of send()
I am having issues with my phpMailer script. I can email from the script, I can even send attachments from the script. However, it only works SOMETIMES and not at other times. I tried changing servers and I have the same issues so I am assuming that it is a coding issue.
when It does not work, the emails still go thorough but it is stripped from any attachments.
The attachments are definitely making it onto the server in the same location and then this script is sent an array of attachments which it then adds onto the message.
In one instance the same code and same files will send and not send! Very confusing! Usually some will send for awhile and then some will not for awhile.
Here is the code:
<?php
include('connection.php');
require_once('PHPMailer/PHPMailerAutoload.php');
class Mailer extends PHPMailer {
public function copyToFolder($folderPath) {
$message = $this->MIMEHeader . $this->MIMEBody;
$path = "INBOX" . (isset($folderPath) && !is_null($folderPath) ? ".".$folderPath : ""); // Location to save the email
$imapStream = imap_open("{mail.server.com:143/novalidate-cert}" . $path , $this->Username, $this->Password) or die(mysql_error());
imap_append($imapStream, "{mail.server.com:143/novalidate-cert}" . $path, $message)or die(mysql_error());
}
imap_close($imapStream);
}
}
$from = $_POST['from'];
$username = $from;
$grabPassword = mysql_query("SELECT * FROM `email_pw_db` WHERE `emailaddress` = '$from'");
$fetchPassword = mysql_fetch_assoc($grabPassword);
$password = $fetchPassword['password'];
$company = $_POST['to'];
$toemail = $_POST['toemail'];
$from = $username;
$namefrom = $_POST['from'];
$subject = $_POST['subject'];
$cc = trim($_POST['cc']);
$bcc = trim($_POST['bcc']);
$message = $_POST['body'];;
$attachments = $_POST['attachments'];
$mail = new Mailer();
$body = $message;
/*Create a new email*/
$mail = new Mailer();
$mail->isSMTP();
$mail->Host = 'mail.server.com';
$mail->Username = $username;
$mail->Password = $password;
$mail->From = $from;
$mail->AddReplyTo($from,$namefrom);
$mail->SMTPKeepAlive = true; // SMTP connection will not close after each email sent, reduces SMTP overhead
$mail->SetFrom($from, $namefrom);
$mail->AddReplyTo($from,$namefrom);
$address = $toemail;
$mail->AddAddress($address, $company);
$mail->Subject = $subject;
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!";
$mail->MsgHTML($body);
if($cc!=''){
$mail->addCC($cc);
}
//CC EMAILS//
$breakOutCC = explode(',', $cc);
$countBreakOut = count($breakOutCC);
$i = 0;
while($i <$countBreakOut)
{
$mail->addCC($breakOutCC[$i]);
$i++;
}
$breakOutBCC = explode(',', $bcc);
$countBreakOutBCC = count($breakOutBCC);
$i = 0;
while($i <$countBreakOutBCC)
{
$mail->addBCC($breakOutBCC[$i]);
$i++;
}
$breakoutAttachments = explode(',', $attachments);
$countAttachments = count($breakoutAttachments);
$i = 0;
while($i <$countAttachments)
{
$mail->AddAttachment("attachments/email_attachments/".$breakoutAttachments[$i]);
$i++;
}
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
$errorMessage = $mail->ErrorInfo;
header( 'Location: email-software.php?dialog=Whoops Something Happened- '.$errorMessage ) ;
} else {
//$mail->copyToFolder(); //save email
$mail->copyToFolder("Sent"); // Will save into Sent folder
$attachments = $_POST['attachments'];
$breakoutAttachments = explode(',', $attachments);
$countAttachments = count($breakoutAttachments);
$i = 0;
while($i <$countAttachments)
{
unlink("attachments/email_attachments/".$breakoutAttachments[$i]);
$i++;
}
header( 'Location: email-software.php?dialog=email sent' ) ;
}
?>
I'm trying to use phpmailer to send out emails to each email address found in the database, but as a unique email. For some reason, it's sending duplicate emails, and it sends it out in as many copies as my query returns rows. So, if my query returns 5 rows, each recipient will receive 5 email (total emails sent is 25). I can't use the same email for multiple recipients because the email content is personalized.
What am I doing wrong with my code? Please help...
Here's my code:
$customers_query = "SELECT customer_name, customer_email, customer_id FROM customers";
$customers = mysql_query($customers_query);
if (!$customers) {
$message = 'Error notice: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
require_once('class.phpmailer.php');
// create an instance
while ($row = mysql_fetch_array($customers)) {
$email = $row['customer_email'];
$name = $row['customers_name'];
$id = $row['customer_id'];
$mail = new PHPMailer();
// use sendmail for the mailer
$mail->IsSendmail();
$mail->SingleTo = true;
$mail->IsHTML(true);
$mail->From = "noreply#domain.com";
$mail->FromName = "MyWebsite";
$mail->Subject = "Welcome to MyWebsite";
$mail->AddAddress($email);
$mail->Body = "Dear ".$name.", welcome to MyWebsite. Your ID is: ".$id.". Enjoy your stay.";
$mail->Send();
}
So, what am missing here? Why does it send that many emails?
Try this:
$mail->ClearAddresses(); after $mail->Send();
Try something like is below, you need to be counting your rows somehow so that it doesn't re-process them. Also, the AddAddress(); function is used to keep adding email addresses to the TO: field, so you need to call ClearAddresses(); in order to restart with a fresh set of recipients.
$customers_query = "SELECT customer_name, customer_email, customer_id FROM customers";
$customers = mysql_query($customers_query);
$count = mysql_num_rows($customers);
$result = mysql_fetch_array($customers);
$i = 0;
if (!$customers) {
$message = 'Error notice: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
require_once('class.phpmailer.php');
// create an instance
while ($i < $count) {
$email = mysql_result($result,$i,"customer_email");
$name = mysql_result($result,$i,"customers_name");
$id = mysql_result($result,$i,"customer_id");
$mail = new PHPMailer();
// use sendmail for the mailer
$mail->IsSendmail();
$mail->SingleTo = true;
$mail->IsHTML(true);
$mail->From = "noreply#domain.com";
$mail->FromName = "MyWebsite";
$mail->Subject = "Welcome to MyWebsite";
$mail->AddAddress($email);
$mail->Body = "Dear ".$name.", welcome to MyWebsite. Your ID is: ".$id.". Enjoy your stay.";
$mail->Send();
$mail->ClearAddresses();
$i++;
}
You can do one more thing, add one more extra field in the customer table, like is_email_sent, yes or no. Once sent email you can update specific row using primary key. so it will not send the same email to multiple time..
This question already has answers here:
PHP send email foreach - send to
(2 answers)
Closed 8 years ago.
I would like to know how to make a loop to make it send email to each checked row from php table.
Here's the table row for checkboxes:
echo "<input name=\"approve[]\" type=\"checkbox\" value='".$row["id"]."' >";
Approve php:
$pfw_header .= "MIME-Version: 1.0\r\n";
$pfw_header .= "Content-type: text/html; charset=utf-8\r\n";
$fromName = "HP EG NPI - Registracija";
$fromEmail = "hp_eg_npi#eventregistration.rs";
$toEmail = "$email";
$subject = "Prijava prihvacena";
function sendEmail ($fromName, $fromEmail, $toEmail, $subject, $emailBody, $pfw_header) {
$mail = new PHPMailer();
$mail->FromName = $fromName;
$mail->From = $fromEmail;
$mail->AddAddress("$toEmail");
$mail->Subject = $subject;
$mail->Body = $emailBody;
$mail->isHTML(true);
$mail->WordWrap = 150;
if(!$mail->Send()) {
return false;
} else {
return true;
}
}
function readTemplateFile($FileName) {
$fp = fopen($FileName,"r") or exit("Unable to open File ".$FileName);
$str = "";
while(!feof($fp)) {
$str .= fread($fp,1024);
}
return $str;
}
//Data to be sent (Ideally fetched from Database)
$name = "$first_name";
$lastname = "$last_name";
$UserEmail = "$email";
//Send email to user containing username and password
//Read Template File
$emailBody = readTemplateFile("../html-email/mail2.html");
//Replace all the variables in template file
$emailBody = str_replace("#username#",$fnames,$emailBody);
$emailBody = str_replace("#password#",$lnames,$emailBody);
//Send email
$emailStatus = sendEmail ($fromName, $fromEmail, $UserEmail, $subject, $emailBody, $headers);
}
}
}
I have tried searching around the internet, but couldn't manage to find a solution.
Thanks in advance!
You could just do:
$mail = new PHPMailer();
$mail->FromName = $fromName;
$mail->From = $fromEmail;
foreach($emails as $email) {
$mail->AddAddress("$email");
}
$mail->Subject = $subject;
$mail->Body = $emailBody;
$mail->isHTML(true);
$mail->WordWrap = 150;
if(!$mail->Send()) {
return false;
} else {
return true;
}
You don't need the sendEmail function.
So I'm trying to use PHPMailer to handle the email form on my website.
I wrote the code here based on a tutorial I found.
<?php
error_reporting(E_ALL);
require_once("class.phpmailer.php");
include("class.smtp.php");
$email = new PHPMailer();
//
// Set server details for send
//
$email->IsSMTP();
$email->Host = "mail.loganyoung.za.net";
$email->Port = 25;
$email-SMTPAuth = true;
$email->Username = "<my email>";
$email->Password = "<my password>";
//
// Send mail from the contact form
//
$to = "<my email>";
$from = $_POST["from"];
$name = $_POST["name"];
$subject = "From web: ".$_POST["subject"];
$message = $_POST["message"];
$body = "<p>Hi Logan,</p>";
$body .= "<p>You have received a new query on your website.<br />Please see below:</p>";
$body .= "<p>";
$body .= str_replace("\r\n", "<br />", $message);
$body .= "</p>";
$email->SetFrom($from, $name);
$email->AddReplyTo($from, $name);
$email->AddAddress($to, "LoganYoung.za.net");
$email->Subject = $subject;
$email->Body = $body;
$email->IsHTML = true;
session_start();
if(!$email->Send()) {
$_SESSION["mailresult"] = "success";
echo "success";
} else {
echo "<p>Failed:</p><p>".$email->ErrorInfo."</p>";
$_SESSION["mailresult"] = "failed";
$_SESSION["mailerror"] = $email->ErrorInfo;
}
?>
I figure possible reasons for it not sending could be...
Incorrect SMTP details (possibly send without SMTP auth to resolve?)
Handler isn't getting POST data (the ajax that sends it seems to work fine though)
Some problem with this code that I'm not able to identify...
As a means of eliminating possibilities, can anyone spot anything wrong with the code here? If so, what's wrong, and how do I fix it?
Thanks in advance!
$email-SMTPAuth = true;
Isn't that supposed to be:
$email->SMTPAuth = true;