How to stop PHP Mailer from appending all email address on every email? - php

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()

Related

Problem with sending all emails to the same person when sending email with PHPMailer

I am trying to send mail to multiple emails with PHPMailer. First, I listed people's names from the table. Then I used the loop to send emails to those people. but the problem is that everyone's information goes to all emails.
PHPMailer
foreach ($id as $mailId) {
$connect->connect('account where id=:id', array('id' => $mailId), '', 0);
$users = $connect->connect->fetch(PDO::FETCH_ASSOC);
$name = $users['name'];
$mailAdres = $users['mail'];
// ob_start();
// include("PHPMailer/template.php");
// $mail_template = ob_get_clean();
$mail_template = $name;
$mail->addAddress($mailAdres, $name);
// $mail->addBCC($mailAdres, $name);
//Content
$mail->isHTML(true);
$mail->CharSet = 'UTF-8';
$mail->Subject = $odemeType;
$mail->Body = $mail_template;
$mail->AltBody = '';
$mail->send();
}
You need to clear the current address once the mail is sent otherwise you are adding a new email to the existing send list each time round the loop.
foreach ($id as $mailId) {
$connect->connect('account where id=:id', array('id' => $mailId), '', 0);
$users = $connect->connect->fetch(PDO::FETCH_ASSOC);
$name = $users['name'];
$mailAdres = $users['mail'];
$mail_template = $name;
$mail->addAddress($mailAdres, $name);
// $mail->addBCC($mailAdres, $name);
//Content
$mail->isHTML(true);
$mail->CharSet = 'UTF-8';
$mail->Subject = $odemeType;
$mail->Body = $mail_template;
$mail->AltBody = '';
$mail->send();
// clear this email address before continuing the loop
$mail->clearAddresses();
}
Note that will clear only the to address, if you also use cc and bcc you may need to do
//Clear all recipients (to/cc/bcc) for the next iteration
$mail->clearAllRecipients();

How To create a url link and send it to email using php mailer

I created a form where a user types in a code,if the code and email exists in database the code then retrieves the email and a token is generated and updated to the database and has to be sent to that email that is retrieved. I am using php mailer to send an email, can someone help me figure what is wrong with the code below, is the url query correct?
<?php
error_reporting(1);
session_start();
include 'includes/connect.php';
include 'includes/additional_function.php';
include('classes/phpmailer/phpmailer.php');
if($_POST["Submit"]=="Submit"){
$idcode=$_POST['idcode'];
$_SESSION['idcode'] = $post['idcode'];
$sql = "SELECT * FROM people WHERE idcode = :idcode";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':idcode', $idcode);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if(!empty($result)){
$email = $result['email'];
//echo $email;
$token = generateToken();
//echo $token;
$sql = "UPDATE student SET token = :token WHERE email = :email";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
':token' => $token,
':email' => $email
));
$result1 = $stmt->fetch(PDO::FETCH_ASSOC);
if(!empty($result)){
{
// $email and $message are the data that is being
// posted to this page from our html contact form
$email = $_REQUEST['email'] ;
$mail = new PHPMailer();
// set mailer to use SMTP
$mail->IsSMTP();
// As this email.php script lives on the same server as our email server
// we are setting the HOST to localhost
$mail->Host = "localhost"; // specify main and backup server
$mail->SMTPAuth = true; // turn on SMTP authentication
// When sending email using PHPMailer, you need to send from a valid email address
// In this case, we setup a test email account with the following credentials:
// email: send_from_PHPMailer#bradm.inmotiontesting.com
// pass: password
$mail->Username = "send_from_PHPMailer#bradm.inmotiontesting.com"; // SMTP username
$mail->Password = "password"; // SMTP password
// $email is the user's email address the specified
// on our contact us page. We set this variable at
// the top of this page with:
// $email = $_REQUEST['email'] ;
$mail->From = $email;
// below we want to set the email address we will be sending our email to.
$mail->AddAddress("bradm#inmotiontesting.com", "Brad Markle");
// set word wrap to 50 characters
$mail->WordWrap = 50;
// set email format to HTML
$mail->IsHTML(true);
$mail->Subject = "You Registration Link!";
$mail->Body = 'http://www.domain.com/register/registration.php?token=$token&stud_id=stud_id';
$mail->AltBody = 'Click to Register';
if(!$mail->Send())
{
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
echo "Message has been sent";
}
}
}
else{
echo 'You are not Registered';
}
}
?>
Firstly, variables don't get parsed in single quotes
$mail->Body = 'http://www.domain.com/register/registration.php?token=$token&stud_id=stud_id';
wrap it in double quotes
$mail->Body = "http://www.domain.com/register/registration.php?token=$token&stud_id=stud_id";
and will not populate themselves in the email sent.
Which for example:
$token = "abcde";
echo $var = 'http://www.domain.com/register/registration.php?token=$token&stud_id=stud_id';
echo "<br>";
echo $var = "http://www.domain.com/register/registration.php?token=$token&stud_id=stud_id";
will echo the following:
http://www.domain.com/register/registration.php?token=$token&stud_id=stud_id
http://www.domain.com/register/registration.php?token=abcde&stud_id=stud_id
As you can see, $token doesn't get its intended value populated, but echos as $token instead of abcde.
Reference:
http://php.net/manual/en/language.types.string.php#language.types.string.syntax.single
This is assuming your conditional statement and POST arrays are kosher.
Plus this $post['idcode'] needs to read as $_POST['idcode'] as per $idcode=$_POST['idcode']; and error reporting would have helped you here. That's a superglobal http://php.net/manual/en/language.variables.superglobals.php and missed the underscore and putting POST in uppercase letters.
If you're unsure:
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Then the rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
or post your HTML form in your question.
Footnotes:
Unsure what you want to use stud_id for and how that is supposed to be populated. Only you know that. As per $token&stud_id=stud_id';
Now, if your query is failing, then that's a different story and you would need to find out why that is and is beyond the scope of the question.
http://php.net/manual/en/pdo.error-handling.php

cannot send email to multiple recepients using phpmailer

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 {
}
?>

phpmailer with mysql results

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..

PHP script: send-to another e-mail adres with SMTP

Currently I am using the following script. This script will send an email to email1, but not always.
When somebody adds the second email2, the email only goes to number 2.
I want to change the script to sent to both emails (1 and 2) when email2 exists.
Tried a lot of things, but can't get it right.
// Email
if(!$row->email2){
$email = $row->email1;
} else{
$email = $row->email2;
// Tried this below and a lot more
if(!$row->email2){
$email = $row->email1;
} else{
$email = $row->email1;
$email = $row->email2;
// E-mail to
if(!is_array($email)){
$mail->ClearAddresses();
$mail->AddAddress($email);
$mail->Send();
} else{
foreach($email as $email){
$mail->ClearAddresses();
$mail->AddAddress($email);
$mail->Send();
$emails = array();
if($email = $row->email1) {
$emails[] = $email;
}
if($email = $row->email2) {
$emails[] = $email;
}
foreach($email as $email){
$mail->ClearAddresses();
$mail->AddAddress($email);
$mail->Send();
}

Categories