email looping in php - php

I use the code below to send email to many people from my database but it usually timeouts and does not send to all. Please tell me how can i set it in php so that it sends like only 1000 email per 10mins in php?
require_once "Mail.php";
$from = "xxx Support <$sender>";
$to = "$to";
$subject = "$subject";
$body = "Dear $fname,\n\n$note\n\n\nYou are getting this email because you registered on our website www.xxx.com and agreed to our Terms and Conditions which includes to receive email from us at any time to your email address $to.";
$host = "smtp1.xxx.net";
$username = "no_reply#xxx.net";
$password = "4t46546$##?";
$headers = array ('From' => $from,
'To' => $to,
'Subject' => $subject);
$smtp = Mail::factory('smtp',
array ('host' => $host,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($to, $headers, $body);
if (PEAR::isError($mail)) {
echo("<p>" . $mail->getMessage() . "</p>");
}
// Show sent emails.
echo "$row[fname] $row[lname] ($row[email])<br>";
}

You can modify your script to pull recipients starting from a certain number, and until all recipients are served, output a META redirect to force the browser to reload from where it left off.
Imagine:
<?php
// Start from $x, or zero if no $x
$x = ( isset( $_REQUEST['x'] ) ? $_REQUEST['x'] : 0 );
// Count total number of recipients
$rs = mysql_query('SELECT COUNT(*) AS total FROM recipients ');
if ( $rs ) $row = mysql_fetch_assoc( $rs );
$total = $row['total'];
// Pull recipients $x through $x+1000 from database
$rs = mysql_query('SELECT * FROM recipients ORDER BY email ASC LIMIT ' . $x . ', 1000 ' );
// Count number of recipients in query result set
$num_recipients = mysql_num_rows( $rs );
while ( $row = mysql_fetch_assoc( $rs ) ){
// Send the message here...
}
if ( ( $num_recipients + $x) < $total ){
// We've not yet reached the total # of recipients
// Output the meta redirect to start from ($x+1000).
echo '<meta http-equiv="REFRESH" content="0;url=this-script.php?x=' . ($x+1000) . '">';
} else {
// We've finished, do something...
}

Related

PHP Send Email Using SMTP If BCC Empty Email Can't Send

I have PHP Send Email using SMTP.
$from = "Info <donotreply#test.com>";
$subject = "Calibration will be expiring!";
$body = 'Hello';
$to = "david#test.com, dono#test.com";
$cc = "rena#test.com";
$bcc = ""; //sometimes BCC can be empty
$host = 'smtp.test.com';
$port = '587';
$username = 'donotreply#test.com';
$password = 'dontreply?';
$headers = array(
'Port' => $port,
'From' => $from,
'To' => $to,
'Subject' => $subject,
'Content-Type' => 'text/html; charset=UTF-8',
'Cc' => $cc
);
$recipients = $to.", ".$bcc.", ".$cc;
$smtp = Mail::factory('smtp',
array ('host' => $host,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($recipients, $headers, $body);
if (PEAR::isError($mail)) {
echo("<p>" . $mail->getMessage() . "</p>");
} else {
echo("<p>Message successfully sent!</p>");
}
I tried to run above code and only working if $bcc is not empty.
Error when $bcc is empty
Failed to add recipient: #localhost [SMTP: Invalid response code received from server (code: 501, response: 5.1.3 Invalid address [HKXPR02MB0695.apcprd02.prod.outlook.com])]
Is there any way how to fix it or need some modification there?
If $bcc variable is empty then your concatenated string contains ,, which is syntactically incorrect. You need to add some logic there to make ensure this is not happening.
Also I doubt you set BCC correctly anyway. It should not be just another recipient like you have now.
I've got the solution below:
$bcc = $dEmailListBCC['EMAIL_ADDRESS'];
if($bcc == "")
{
$a = "";
}
else
{
$a = ",".$bcc;
}
First, check the $bcc variable is empty or not.
and then the recipients to be like this:
$recipients = $to." ".$a.", ".$cc;

not able to send details via email [duplicate]

This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 5 years ago.
$sql = "insert into book (uid,interest,tid,lid)values('$id','$interest','$tid','$lid') ";
$result = $conn->query($sql);
if($result)
{
echo"<script type='text/javascript'>
alert('added');
</script>";
$message = "Your have interest in ".$interest."";
$to=$email;
$subject="Booked for ".$title."";
$from = 'vkcvkc8#gmail.com';
$body="Booked for ".$title."located in".$location.".You will be charged with".$cost.
".Contact:".$contact."";
$headers = "From:".$from;
mail($to,$subject,$body,$headers);
}
else
{
echo"<script type='text/javascript'>
alert('error');
</script>";
}
not sending email
not sending emailnot sending emailnot sending emailnot sending emailnot sending emailnot sending email?????
You have to use smtp settings to be able to send the mail as most hosting providers now have closing the php mail function due to security reasons, this is the script for a proper smtp mail function and dont use third party tools like php mailer just ask your hosting provider to activate mail function in pear packages
<?php
require_once "Mail.php";
$from = "Web Master <webmaster#example.com>";
$to = "Nobody <nobody#example.com>";
$subject = "Test email using PHP SMTP\r\n\r\n";
$body = "This is a test email message";
$host = "SMTPhostname";
$username = "webmaster#example.com";
$password = "yourPassword";
$headers = array ('From' => $from, 'To' => $to, 'Subject' => $subject);
$smtp = Mail::factory('smtp', array ('host' => $host, 'auth' => true, 'username' => $username, 'password' => $password)); $mail = $smtp->send($to, $headers, $body);
if (PEAR::isError($mail)) {
echo("<p>" . $mail->getMessage() . "</p>"); }
else
{ echo("<p>Message successfully sent!</p>");
}
?>
As mentioned - your code is at risk of sql injection so it would be wise to use a prepared statement as below.
try{
$sql='insert into book ( uid, interest, tid, lid ) values (?,?,?,?)';
$stmt=$conn->prepare( $sql );
if( $stmt ){
/*
assuming parameters are
-----------------------
uid=integer
interest=string
tid=integer
lid=integer
*/
$stmt->bind_param('isii', $id, $interest, $tid, $lid );
$result=$stmt->execute();
if( $result && $stmt->affected_rows==1 ){
$message = "You have interest in {$interest}";
$to=$email;
$from='vkcvkc8#gmail.com';
$subject="Booked for {$title}";
$body="{$message}\n\nBooked for {$title} located in {$location}.\n\nYou will be charged with {$cost}\n\nContact:{$contact}";
$headers=array();
$headers[]="MIME-Version: 1.0";
$headers[]="Content-type: text/plain; charset:utf-8";
$headers[]="To: {$to}";
$headers[]="From: {$from}";
$headers[]="Reply-To: {$from}";
$headers[]="X-Mailer: PHP/".phpversion();
$status = mail( $to, $subject, $body, implode( "\r\n", $headers ) );
throw new Exception( $status ? 'success - mail sent' : 'fail - mail not sent' );
} else {
throw new Exception('Failed to insert data');
}
} else {
throw new Exception('Unable to prepare sql query');
}
}catch( Exception $e ){
exit( "<script>alert('{$e->getMessage()}');</script>" );
}

How to send two emails in a single contact form using PEAR Mail

I have a contact form and I want to receive message through mail and simultaneously send mail to the client. I have the below code it works some times. That is some times I get the message and client also get the message but sometimes only one email is sent either to client or to me but never both all the time.
I have seen example in the following link https://teamtreehouse.com/community/how-to-send-two-different-email-with-different-bodies-using-phpmailer but it uses PHP Mailer I want the same functionality but by using PEAR Mail.
I have seen other similar question over here PEAR Mail using gmail SMTP won't send 2 emails in sucession but the answer given in that question doesn't solve my problem
Below is the code which works some time.
<?php
require_once('Mail.php');
require_once('Mail/mime.php');
if (isset($_POST['Captcha'])) {
$name = filter_var($_POST['Name'] , FILTER_SANITIZE_STRING);
$email = filter_var($_POST['Email'] , FILTER_SANITIZE_EMAIL);
$phone = filter_var($_POST['Phone'] , FILTER_SANITIZE_STRING);
$budget = filter_var($_POST['Budget'] , FILTER_SANITIZE_STRING);
$timeline = filter_var($_POST['Timeline'] , FILTER_SANITIZE_STRING);
$description = filter_var($_POST['Description'] , FILTER_SANITIZE_STRING);
$spam = filter_var($_POST['usernameoftest'] , FILTER_SANITIZE_STRING); // Bot trap
if($spam)
{ // If the hidden field is not empty, it's a bot
die("No spamming allowed bitch!");
} else {
$from = "sales#ganeshghate.com";
$to = "ganeshghate#hotmail.com";
$subject = "Message from : ".$name;
$body = "Client's Name : ".$name."\r\n";
$body .= "Client's Email ID : ".$email."\r\n";
$body .= "Client's Phone Number : ".$phone."\r\n";
$body .= "Client's Budget : ".$budget."\r\n";
$body .= "Client's Timeline : ".$timeline."\r\n";
$body .= "Client's Message : ".$description."\r\n";
$host = "myhost";
$port = "myport";
$username = "myusername";
$password = "mypassword";
$crlf = "\n";
$headers = array ('From' => $from,
'To' => $to,
'Subject' => $subject);
$mime = new Mail_mime($crlf);
$mime->setTXTBody($body);
$body = $mime->get();
$headers = $mime->headers($headers);
$smtp = Mail::factory('smtp',
array ('host' => $host,
'port' => $port,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($to, $headers, $body);
if (PEAR::isError($mail)) {
$output["errorclientemail"] = "<div>
<h2 class='error'>".$mail->getMessage().$mail->getUserInfo()."</h2>
<h2>Oops there was some error we have not received your message</h2>
<h2>Please report the above error to us via skype , email , phone details are on the left side</h2>
</div>"."\r\n";
} else {
$output["successclientemail"] = "Thank you we will get back to you soon";
}
$bodyback = "We have received your message :".$body."\r\n";
$bodyback .= "We will get back to you soon"."\r\n";
$bodyback .= "With Regards "."\r\n";
$bodyback .= "Ganesh Ghate "."\r\n";
$subjectback = "Thank You for contacting us";
$headersreply = array ('From' => $from,
'To' => $email,
'Subject' => $subjectback);
$crlf1 = "\n";
$mime = new Mail_mime($crlf1);
$mime->setTXTBody($bodyback);
$bodyback = $mime->get();
$headersreply = $mime->headers($headersreply);
$smtp = Mail::factory('smtp',
array ('host' => $host,
'port' => $port,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($email, $headersreply, $bodyback);
if (PEAR::isError($mail)) {
$output["errorreplyemail"] = "<div>
<h2 class='error'>".$mail->getMessage().$mail->getUserInfo()."</h2>
<h2>Oops there was some error we have not delivered confirmation email to you</h2>
<h2>Please report the above erorr to us via skype , email , phone details are on the left side</h2>
</div>"."\r\n";
} else {
$output["successreplyemail"] = "We have sent confirmation email to you. Please check your inbox / junk mail";
}
echo json_encode($output);
}
}
?>
Thanks in advance

Cannot get email from query string

I'm having trouble getting an email address from $_GET.
Here is my code:
<?php
$eadd = $_GET['email'];
echo("<p>Please check your inbox on your email $eadd.</p>");
?>
I went to this link:
http://localhost/file.php?email=myemail#company.com
Yet the output is only:
Please check your inbox on your email .
EDIT
Here's my complete code :
<?php
require_once "Mail.php";
//Get link posted info's needed
//Email
$eadd = $_GET['email'];
$from = "OtakuJam Registration <no-reply#comp.com>";
$to = " $unick < $eadd >";
$subject = "Thank you for registering";
$body = "Dear $unick ,
\n Thank you for registering to OtakuJam. To activate your account, \n
";
$host = "mail.srv.com";
$username = "name#comp.com";
$password = "mypass";
$headers = array ('From' => $from,
'To' => $to,
'Subject' => $subject);
$smtp = Mail::factory('smtp',
array ('host' => $host,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($to, $headers, $body);
if (PEAR::isError($mail)) {
echo("<p>" . $mail->getMessage() . "</p>");
} else {
echo("<p>Please check your inbox on your email $eadd.</p>");
}
?>
`Please ignore the $unick there, also the mail won't send unless i put an email on the code instead of < $eadd >
turning my $to syntax to $to = $unick . "<" . $eadd . ">"; as #Charlie gave me helped me. Also to those who told me to use ".$variable.". to my echo helped. thanks

How to send e-mail to multiple recipients from database query (PHP)

I'm trying to send an e-mail to multiple e-mail address in my database. Here is my current code. It is only working when I specify a single e-mail address, however, I need to have them query my database and send the e-mail to each e-mail address. Where am I going wrong here?
function sendmail($cat, $user) {
require_once "Mail.php";
$elist = mysql_query("SELECT cEmail FROM tblUsers WHERE cAlerts = 'All' AND cEAlerts = 'Yes' AND cPreferences LIKE '%$cat%';");
$elist = mysql_fetch_array($elist);
$from = "EMAIL ADDRESS";
$to = $elist;
$subject = "SUBJECT";
$body = "BODY";
$host = "smtp.domain.com";
$username = "USERNAME";
$password = "PASSWORD";
$headers = array ('From' => $from,
'To' => $to,
'Subject' => $subject);
$smtp = Mail::factory('smtp',
array ('host' => $host,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($to, $headers, $body);
}
Try something like this but one point to note is that you should send emails individually ratehr than group all your email addresses in one "to" field. Other users might not like others seeing that. Maybe your smtp function breaks down the array, not sure :-|
function sendmail($cat, $user)
{
require_once "Mail.php";
$elist = mysql_query("SELECT cEmail FROM tblUsers WHERE cAlerts = 'All' AND cEAlerts = 'Yes' AND cPreferences LIKE '%$cat%';");
$from = "EMAIL ADDRESS";
$subject = "SUBJECT";
$body = "BODY";
$host = "smtp.domain.com";
$username = "USERNAME";
$password = "PASSWORD";
if(mysql_num_rows($elist) > 0)
{
while($elist_result = mysql_fetch_array($elist))
{
$headers = array ('From' => $from,
'To' => $elist_result['cEmail'],
'Subject' => $subject);
$smtp = Mail::factory('smtp',
array ('host' => $host,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($to, $headers, $body);
}
}
}
mysql_fetch_array fetches an array with entries corresponding to each of the columns of a single row of your table. In other words, here it's an array containing one user's cEmail column.
You need to fetch all the values into a single array before calling the mail functions. You could do it like this:
$dest = array();
while ($arr = mysql_fetch_array($elist)) {
$dest[] = $arr['cEmail'];
}
I had a similar issue while trying to loop though my recipients' database table with the aim of sending personalized PEAR emails to each recipient.
The problem I encountered was that the loop would cease after one iteration until I amended $recipients to just send the first item in the array, as illustrated in this code snippet. ($recipients is an array of IDs for recipients):
/*PEAR mail set-up code included here*/
for ($i = 0; $i < count($recipients); $i++) {
$sql_recipients = "SELECT * FROM $data_table WHERE id = $recipients[$i] ORDER BY id ASC ";
$res_recipients = mysqli_query($mysqli,$sql_recipients)
or die (mysqli_error($mysqli));
$recipients_info = mysqli_fetch_array($res_recipients);
$recip_id = $recipients_info['id'];
$recip_organisation = $recipients_info['organisation'];
$recip_fname = $recipients_info['fname'];
$recip_lname = $recipients_info['lname'];
$recip_email = $recipients_info['email'];
/*PEAR mail code here */
$recipients[0] = $recip_email;
$mail->send($recipients[0], $hdrs, $body);
}
I learned to this from one of the examples in the book I am learning PHP from, Head First PHP & MySQL.
What you can do is send each e-mail individually, but simultaneously, through a while loop. With a mysqli_query selecting the e-mails, make a while loop that goes through my
while ($row_data = mysqli_fetch_array($your_query_in_a_variable)) {
// Then you will set your variables for the e-mail using the data
// from the array.
$from = 'you#yoursite.com';
$to = $row_data['email']; // The column where your e-mail was stored.
$subject = 'Open Me!';
$msg = 'Hello world!';
mail($to, $msg, $from);
}
I hope that is clear. You basically just call the rows you want in your query, then use mysqli_fetch_array, which goes through each row every time it is called (someone correct me, if wrong) and will exit when there are no more rows left that were called.
My suggestion would be use the php mail() function and set the smtp server parameters in your php.ini file.
Then all you have to do is query your db, pull the first record out as your to address and then loop through the result set and put each email address into an array. Then just use the join function to join the array with commas and use it as the BCC for the header string.
Here is what I would use if possible. I've included a couple notes as //comments
function sendmail($cat, $user) {
$result = mysql_query("SELECT cEmail FROM tblUsers WHERE cAlerts = 'All' AND cEAlerts = 'Yes' AND cPreferences LIKE '%$cat%';");
//pull out first email as the to address
$to = mysql_fetch_array($result);
//create array to store all the emails
$elist = array();
//loop through and put each email into an array
// you might be able to skip this altogether if you can just join $result
// but I'm to lazy to investigate what all is being returned
while($row = mysql_fetch_assoc($result)){
$elist[] = $row['cEmail'];
}
//join the emails into a comma separated string
$bcc = join($elist, ",");
$from = "EMAIL ADDRESS";
$subject = "SUBJECT";
$body = "BODY";
$headers = "From: ". $from ."\r\n";
$headers .="BCC: ". $bcc ."\r\n";
mail($to, $subject, $body, $headers);
}
Hopefully this is useful information.. Feel free to pick it apart and use whatever you may need, like if you can use part to implement your Mail class.
You schould not use the php mail() function. It is dead slow because it does a full connect to the smtp server every single mail you send.
A good Mail library such as Zend_Mail connects only once and delivers the mails in one batch to the smtp server.
You should also not send all your mails via a long BCC-Line. At least if you want your email not marked as spam (See this Question and this Blog-Entry by Jeff).
<?php
function sendmail($cat, $user) {
// Setup mailer
require_once "Mail.php";
$smtp = Mail::factory('smtp', array(
'host' => "smtp.domain.com";
'auth' => true,
'username' => "USERNAME";
'password' => "PASSWORD";
));
// ALWAYS escape your variables!
$query = sprintf("SELECT cEmail FROM tblUsers WHERE cAlerts = 'All' AND cEAlerts = 'Yes' AND cPreferences LIKE '%s'",
mysql_real_escape_string($cat),
// submit the query
$result = mysql_query($query);
// iterate over each row
while ($row = mysql_fetch_assoc($result)) {
$from = "EMAIL ADDRESS";
$to = $row['cEmail'];
$subject = "SUBJECT";
$body = "BODY";
$headers = array(
'From' => $from,
'To' => $to,
'Subject' => $subject
);
// Send mail with individual to-address via smtp
$mail = $smtp->send($to, $headers, $body);
}
}
Use this code to resolve your problem.
//Connect to database
mysql_connect("localhost","user","password") or die(mysql_error());
mysql_select_db("db") or die(mysql_error());
$sql = "SELECT email FROM members";
$res = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_assoc($res) )
{
$area .= $row['email']. ", ";
}
// read the list of emails from the file.
$email_list = explode(',', $area);
// count how many emails there are.
$total_emails = count($email_list);
// go through the list and trim off the newline character.
for ($counter=0; $counter<$total_emails; $counter++)
{
$email_list[$counter] = trim($email_list[$counter]);
}
$to = $email_list;
echo $to;

Categories