Why is SwiftMailer sending two emails? - php

I am sending emails via PHP's SwiftMailer library. I have this PHP code to send 1 email to 1 email recipient from 1 sender. Here is the code:
$email = /*some email recipient*/;
$sendEmail = /*sender's email*/;
$sendName = /*sender's name*/;
$subject = /*email subject*/;
$body = /*email body*/;
//Create the message
//Create the Transport
$transport = Swift_SmtpTransport::newInstance('/*mail host*/', /*port*/)
->setUsername('/*some username*/')
->setPassword('/*some password*/')
;
//Create the Mailer using your created Transport
$mailer = Swift_Mailer::newInstance($transport);
//Create a message
$message = Swift_Message::newInstance($subject)
->setFrom(array($sendEmail => $sendName))
->setTo($email)
->setBody($body, 'text/html')
;
//Send the message
$result = $mailer->send($message);
Every time I run this code it sends to emails from that sender to that email with that subject and body. Two identical emails right on top of each other. Any idea why?
UPDATE - here is the complete code:
Here is the entire page:
<?php
ob_start();
session_start();
require_once ('config.php');
require_once 'swiftmailer/lib/swift_required.php';
include ('functions.php');
require_once (MYSQL);
sendConfirmation(12,3,$dbc);
ob_end_flush();
?>
And here is the function that is referenced in the page (that is located in the functions.php file:
function sendConfirmation($signup_id,$app_id,$dbc){
//get signup email and ref code
$q = "SELECT email, ref_code FROM sign_ups WHERE (signup_id='$signup_id')";
$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
$email;
$ref;
if (mysqli_num_rows($r) == 1){
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
$email = $row['email'];
$ref = $row['ref_code'];
}
//get app info (subject, email body, sender email, sender name)
$q = "SELECT bsignupemail_subj, bsignup_email, email, name, bsignup_url FROM apps WHERE (app_id='$app_id')";
$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
$sendEmail;
$sendName;
$subject;
$body;
$url;
if (mysqli_num_rows($r) == 1){
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
$url = $row['bsignup_url'];
$sendEmail = $row['email'];
$sendName = $row['name'];
$subject = $row['bsignupemail_subj'];
$body = $row['bsignup_email'];
}
//Create the message
//Create the Transport
$transport = Swift_SmtpTransport::newInstance('/*host*/', /*port*/)
->setUsername('/*username*/')
->setPassword('/*password*/')
;
//Create the Mailer using your created Transport
$mailer = Swift_Mailer::newInstance($transport);
//Create a message
$message = Swift_Message::newInstance($subject)
->setFrom(array($sendEmail => $sendName))
->setTo(array($email))
->setBody($body, 'text/html')
;
//Send the message
$result = $mailer->send($message);
}

This is might be due to a logic error where the code using Swift Mailer is asking it to send twice.
Check for faulty loops, recursive function calls and multiple includes and initialization of variables etc. Something is telling Swift Mailer to send the email twice.

For those who have the same issue use:
return $this->redirectToRoute('route', array('parameter'=>$parameter));
instead of:
return $this->render(...);

Related

PHP mail error domain missing or malformed<EOL>

I'm trying to send a mail to a customers email thats set in my database.
$subject = 'Testing PHP Mail';
$txt = 'This mail is sent using the PHP mail function';
$headers = "FROM: test#gmail.com";
$query = ("SELECT email FROM ps_customer where id_customer = 2");
$result = $dbc->query($query);
$row = $result->fetch_assoc();
echo $row['email'];
$to_email = (string)$row;
//while ($row = $result->fetch_assoc()) {
// echo $row['email'];
// $to_email = (string)'$row <#>';
if (mail($to_email, $subject, $txt, $headers)) {
echo "send";
} else {
echo "failed";
}
this is my code that's need to send the email to the email out of the database.
but when i try to send it i get the error: : domain missing or
malformed
You only want the address, and it's the only field you're fetching, so I'd go with:
$query = ("SELECT email FROM ps_customer where id_customer = 2");
$result = $dbc->query($query);
$row = $result->fetch_row();
$to_email = $row[0];
No need to use an assoc array for this.
You've not mentioned it, but the messages you send will probably be rejected. You're sending via mail(), which means you are not sending through gmail's servers, but you're using a gmail from address. This is forgery and will mean your messages will be bounced or spam filtered. You can't solve this using mail() (other than by not using gmail for your from address); you would need to send using SMTP via gmail using PHPMailer (that you tagged this question with).

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

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

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

Email list from sql practices

I have been using the following to get and email people in my database. The problem is now that the database has over 500+ members the script slows down and SHOWS each member email address in TO: field. I tried a suggestion on another site to use BCC instead but I was wondering isn't there a way to alter this to send the emails individually?
$sql = "SELECT * FROM users WHERE system = '101' AND mailing_list = 'yes'";
$result = mysql_query($sql) or die("Unable to execute<br />$sql<br />".mysql_error());
$row = mysql_fetch_array($result);
var_dump($row);
$to .= $row['email'] . "\r\n";
//send email
php's mail() is very inefficient, I suggest using something like phpmailer
from the manual:
Note:
It is worth noting that the mail() function is not suitable for larger
volumes of email in a loop. This function opens and closes an SMTP
socket for each email, which is not very efficient.
For the sending of large amounts of email, see the » PEAR::Mail, and »
PEAR::Mail_Queue packages.
You need to use PHPMailer as it is meant to be used for just this situation. the trouble with mail() is that it opens and closes a connection after each email. You obviously want to open 1 connection, send all your emails (one by one) and close the connection.
Something like below:
require("class.phpmailer.php");
$mail = new phpmailer();
$mail->From = "list#example.com";
$mail->FromName = "List manager";
$mail->Host = "smtp1.example.com;smtp2.example.com";
$mail->Mailer = "smtp";
#MYSQL_CONNECT("localhost","root","password");
#mysql_select_db("my_company");
$query = "SELECT full_name, email, photo FROM employee WHERE id=$id";
$result = #MYSQL_QUERY($query);
while ($row = mysql_fetch_array ($result))
{
// HTML body
$body = "Hello <font size=\"4\">" . $row["full_name"] . "</font>, <p>";
$body .= "<i>Your</i> personal photograph to this message.<p>";
$body .= "Sincerely, <br>";
$body .= "phpmailer List manager";
// Plain text body (for mail clients that cannot read HTML)
$text_body = "Hello " . $row["full_name"] . ", \n\n";
$text_body .= "Your personal photograph to this message.\n\n";
$text_body .= "Sincerely, \n";
$text_body .= "phpmailer List manager";
$mail->Body = $body;
$mail->AltBody = $text_body;
$mail->AddAddress($row["email"], $row["full_name"]);
$mail->AddStringAttachment($row["photo"], "YourPhoto.jpg");
if(!$mail->Send())
echo "There has been a mail error sending to " . $row["email"] . "<br>";
// Clear all addresses and attachments for next loop
$mail->ClearAddresses();
$mail->ClearAttachments();
}

Categories