I have thousands of emails and I want to send an e-mail to all of them and I can not solve it. Is anyone able to help and clarify with examples in ways of solving
As shown in the following code what is the problem and what is the solution
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'gator4164.hostgator.com '; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = "..."; // SMTP username
$mail->Password = '...'; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465; // TCP port to connect to
$mail->CharSet = 'UTF-8';
$get = new get();
$getEmails = $get->getEmails();
$CountEmails = $get->CountEmails();
$mail->setFrom('email#gmail.com', 'Email Name');
foreach($getEmails as $getEmails){
for ($x = $emails['id']; $x <= $CountEmails; $x++) {
$mail->addAddress($emails['email'],$emails['name']);
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $title;
$mail->Body = nl2br($content);
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
}
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo'<div class="done">Done</div>';
}
}
For such kind of scenario, you have to create a Process Queue because every email sending needs some time to process and if the email count is thousand then in that case your system will crash as it is having a processing time limit. For creating a process queue you have to maintain a database table in which save all the records and maintain a status with different values like:
0: Initial, 1:Processing, 2: Email Sent
And create a separate functionality that pick a record on a regular interval and send the email and change the status. Put this functionality on CRON.
Don't add all of the recipients with "add" in one loop then you have one Email with all recipients. Send your E-Mail with every duration.
foreach($getEmails as $getEmails){
$emails['email'] = $getEmails['email'];
$emails['name'] = $getEmails['name'];
$mail->addAddress($emails['email'],$emails['name']);
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $title;
$mail->Body = nl2br($content);
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo'Email send to ' + $emails['email'];
}
$mail->clearAddresses();
}
something like this. So send the Email for every duration. To prevent that you send people duplicate emails you should set the status in your database if the email is send otherwise you send it again if you have an error in your script and you have to restart the script.
Related
I have a foreach loop from which i am sending emails for my customers.
I have 4 customers in my db 1,2,3,4
So according to foreach loop the loop will run for 4 times to send an email to every customer
But in 1st run it sends email to customer 1.
In 2nd run It is sending email to customer 1 and 2.
In thirdd run it is sending email to customer 1,2,3 and so on.
How can i make to send one email to one customer.
here is my code.
$list=$tmp_con->query("SELECT name,email FROM users WHERE user_type='$tp' AND subscribed='yes' AND verified='1'") or die($tmp_con->error);
$lis=array();
while($row=$list->fetch_array()){
$lis[] = $row;
}
foreach($lis as $lst){
$content = str_replace("{name}", $lst['name'], $mail_content);
$content=$content."".$append_unsub;
/**************************************************phpmailer class***********************/
//$mail->SMTPDebug = 3; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = $mail_smtp_host; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = $mail_smtp_username; // SMTP username
$mail->Password = $mail_smtp_password; // SMTP password
$mail->SMTPSecure = $mail_smtp_enc; // Enable TLS encryption, `ssl` also accepted
$mail->Port = $mail_smtp_port; // TCP port to connect to
$mail->setFrom($mail_smtp_from_email, $mail_smtp_from_name);
$mail->addAddress($lst['email']); // Add a recipient
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $mail_subject;
$mail->Body = $content;
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
$lst['email']='';
/*************************************************php mailer ends here*************************************/
} ///foreach ends here
Create a new $mail object in the loop or even better reset the addresses in the loop. You've (probably) declared the $mail object outside the for loop.
So every time you call addAddress you're adding the email address of the user. The first time you're setting the email address of the first user, then the second time you're adding the email address to the list, so two email addresses. Third round the same, fourth round etc..
Edit: Creating $mail inside the loop fixes the problem, but isn't efficient. See Synchro's comment for a better way to create and send the email.
No need of creating an instance of PHPMailer in each and every loop. Use $mail->clearAddresses(); at the end of foreach loop to clear all the addresses.
Updated Code
$list = $tmp_con->query("SELECT name,email FROM users WHERE user_type='$tp' AND subscribed='yes' AND verified='1'") or die($tmp_con->error);
$lis = array();
while ($row = $list->fetch_array()) {
$lis[] = $row;
}
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = $mail_smtp_host; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = $mail_smtp_username; // SMTP username
$mail->Password = $mail_smtp_password; // SMTP password
$mail->SMTPSecure = $mail_smtp_enc; // Enable TLS encryption, `ssl` also accepted
$mail->Port = $mail_smtp_port; // TCP port to connect to
$mail->setFrom($mail_smtp_from_email, $mail_smtp_from_name);
foreach ($lis as $lst) {
$content = str_replace("{name}", $lst['name'], $mail_content);
$content = $content . "" . $append_unsub;
//$mail->SMTPDebug = 3;
$mail->addAddress($lst['email']); // Add a recipient
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $mail_subject;
$mail->Body = $content;
if (!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
$mail->clearAddresses(); // Clear all addresses for next loop
}
References:
PHPMailer
Currently I am working on a PHP email script using PHPMailer` library. I am sending a mass mail using BCC for all the email addresses.
I want each email to contain the current recipient's email address in the message body.
Below is my sample code:
<?php
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = 'smtp1.example.com;smtp2.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'user#example.com';
$mail->Password = 'secret';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom('from#example.com', 'Mailer');
$mail->addAddress('noreply#example.com');
$arrMail [] = array('bcc1#example.com','bcc2#example.com');
for($i=0;$i<count( $arrMail);$i++)
{
$mail->addBCC($arrMail[$i]);
$htmlversion = 'Hello '.$arrMail[$i].' !'.
}
// $htmlversion = 'Hello <email_id needed here> !'.
$mail->Body = $htmlversion;
$mail->AltBody = $textVersion;
if(!$mail->send())
{
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
}
else
{
echo 'Mail sent';
}
Problem: If bcc1#example.com receives the email, its message body should contain their email address. Currently I am getting the first email address in the message body for every recipient.
Note: I dont want to send mail one-by-one using To like mentioned in other pages.
Also is it possible by using some session or database logic?
I am using php 5.5.9.
Your code is reusing the same email address because you didn't put the creation of the mail body in the loop. If you use a loop then you also don't need BCC.
$arrMail [] = array('bcc1#example.com', 'bcc2#example.com');
$total = count($arrMail);
for($i = 0; $i < $total; $i++) {
$email = $arrMail[$i];
$htmlversion = "Hello $email !";
$mail->Body = $htmlversion;
$mail->AltBody = $textVersion;
$mail->AddAddress($email);
if (!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Mail sent';
}
}
I dont want to send mail one-by-one using To like mentioned in other pages.
Unfortunately, BCC by its very nature sends the same email to multiple recipients. If you want to customise each email for each person, you have to send them individual emails.
Once my code is run in PHP, it says that the confirmation mail has been sent successfully, but the mail has not been received at the target mail ID. I have used the mail() function in PHP to send the confirmation mail and I have also installed Postfix on my Ubuntu. What is the problem here?
<?php
include('config.php');
$tb_name = temp_members_db;
$confirm_code = md5(uniqid(rand()));
$name = $_POST['name'];
$email = $_POST['email'];
$pass = $_POST['pass'];
$country = $_POST['country'];
$sql = "INSERT INTO $tb_name(confirm_code,name,email,password,country) VALUES ('$confirm_code','$name','$email','$pass','$country')";
$result = mysql_query($sql);
if($result) {
$to = $email;
$sub = "Your Confirmation Code";
$message = "Your confirmation code is" . $confirm_code;
$send = mail($to,$sub,$message);
var_export($send);
} else {
echo "Havent found email ID in our database";
}
if($send) {
echo "Sent the confirmation link to your email ID";
} else {
echo "Sending failed";
}
?>
Have you switched on the SMTP function on the localhost server?
If not enabled the SMTP and mail functions
Use PHPMailer class. Very easy to install and use. The PHP mail() function usually sends via a local mail server, typically fronted by a sendmail binary on Linux, BSD and OS X platforms, however, Windows usually doesn't include a local mail server; PHPMailer's integrated SMTP implementation allows email sending on Windows platforms without a local mail server.
Just download the class files from here: https://github.com/PHPMailer/PHPMailer
Example:
<?php
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
//$mail->SMTPDebug = 3; // Enable verbose debug output
Set SMTP and if you want to use secure encryption (ssl,tls and ports)
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp1.example.com;smtp2.example.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'user#example.com'; // SMTP username
$mail->Password = 'secret'; // SMTP password
$mail->SMTPSecure = 'tls'; // If you want to use encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to(or port 25,465 etc)
Set fields like from, to, bcc, subject, email body etc.
$mail->setFrom('from#example.com', 'Mailer');
$mail->addAddress('joe#example.net', 'Joe User'); // Add a recipient
// Name is optional
$mail->addReplyTo('info#example.com', 'Information');
$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.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
I am trying to build a recall system in which users are sent reminder emails based on specified criteria. At the moment I would probably be sending 10-15 reminders at a time each week but it's possible that this may escalate to hundreds each week in the future. I've decided to use PHPMailer class to handle mail sending but I am very new to PHPMailer and so i'm not sure if the solution I have come up with will give the best performance or if my code can be improved. Also I am storing the date the email has been sent once it has been sent successfully.
This is what I have come up with:
<?php
//I have left out the database connection details for obvious reasons
require 'PHPMailer-master/PHPMailerAutoload.php';
$result = mysql_query("SELECT * FROM patients_test WHERE recall <> 0 AND DATE_ADD(`last_seen`, INTERVAL recall DAY) < DATE_ADD(NOW(), INTERVAL 21 DAY)");
while($row = mysql_fetch_array($result))
{
//Create new mail object
$mail = new PHPMailer;
///Mail settings
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'host.co.uk'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'myusername'; // SMTP username
$mail->Password = 'mypassword'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable encryption, 'ssl' also accepted
$mail->From = 'myusername';
$mail->FromName = 'Mailer';
$mail->addReplyTo('replytoadd', 'Information');
$mail->WordWrap = 50; // Set word wrap to 50 characters
$mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Reminder email';
$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';
//Recipient info
$ref = $row['identifier'];
$first_name = $row['first_name'];
$surname = $row['surname'];
$email = $row['email'];
$mail->addAddress($email, $first_name." ".$surname); // Add a recipient
if(!$mail->send())
{
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
}
else
{
echo 'Reminder sent to '.$first_name.' '.$surname.' successfully<br/>';
mysql_query("UPDATE patients_test SET last_reminder= CURDATE() WHERE identifier='$ref'");//Update database to show that email has been sent
$mail->clearAllRecipients();
}
}
?>
Also the reason why I chose not to use PHPs default mail() function is because I am worried that my emails will be blocked as spam and I read somewhere that using something like PHPMailer can reduce the chances of this happening. Does anyone have any advice on this issue?
Thanks in advance
Rich
Fill the mail's headers can reduce this issue. The mail server have some rules which define if the mail is a spam or not. Moreover, sending mails through a loop may cause a blocking depending on how it is configured.
I'm using PHPMailer to automatically send an order acknowledgement as an HTML formatted email. Everything is working as expected except that the formatting of the acknowledgement isn't correct. I included my style sheet with an 'AddAttachment' line which seems to have fixed the header of the acknowledgement form, but the rest of the form still isn't right. Has anyone run into this situation before and know what I need to do to fix it? My edited program code follows in case it'll help!
<?php
require("class.phpmailer.php");
$mail = new PHPMailer();
$mail->SMTPDebug = 0;
$mail->IsSMTP(); // telling the class to use SMTP
$mail->SMTPAuth = true;
$mail->Port = 25; // set the SMTP port
$mail->Host = "<<smtp server>>"; // SMTP server
$mail->Username = "<<username>>";
$mail->Password = "<<password>>";
$mail->From = "<<email address>>";
$mail->FromName = "<<name>>";
$mail->AddAddress("<<email address>>");
$mail->Subject = "Acknowledgement Form";
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
$mail->IsHTML(true);
$mail->Body = file_get_contents('<<acknowledgement form page>>');
$mail->AddAttachment('printer.css'); // attach style sheet
if(!$mail->Send()) {
echo 'Message was not sent.';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent.';
}
?>
You should'nt work with external CSS files in emails... Not many of the email-clients can handle that and not all of your customers use email-clients like Outlook or Thunderbird. Instead, you should disgn you html-code "90s style" :-P
e.g. <p style="width: 200px; text-align: center;">