I have this following code:
<?php
$participants_db = "test_test_test_test_test_test_Sticky_Sticky_Sticky_Sticky_";
$participants = array_unique(explode("_", $participants_db));
foreach($participants as $user)
{
echo $user . '\n';
sleep(10);
}
?>
I spent hours debugging this script, it actually get each username and send email to each one,
the thing is it was sending emails for each user but $user didn't change... Im wondering Why Sleep Break the Foreach and How to fix this..
http://3v4l.org/b048m
UPDATE
here's the Full Code:
foreach($participants as $user)
{
if($user == '')
{
//echo 'broken';
break 1;
}
//get each user's email address
$sql3 = $dbh->prepare("SELECT * FROM users WHERE username = ?");
$sql3->execute(array($user));
while($a = $sql3->fetch())
{
$email = $a['email'];
$username = $a['username'];
}
$message = str_replace("{USERNAME}", $username.'_'.$user, $message);
sendemail($email, $cc, $from, $subject, $message, $filename, $filepath);
//sleep(10);
}
the array (participants) contains usernames , each user has different email address.
this script gets executed by a cron job. after the execution it sent emails to 2 emails (for example), and it's saying Hello Test_test to Both Emails That have Different Usernames
Im just wondering, how did it get the email and the username still the same???
The problem was str_replace
it replaced the {USERNAME} with a username, then after the exection $message doesn't contain {USERNAME} Which caused the main problem of it...
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm trying to send mail with Id Number for user registering, id number inserted automatic from MySQL...
The id number is a primary key and auto increment. Its name in MySQL is 'con_id'
I tried this code:
This is a register.php code and sendmail function:
<?php
class register
{
private $con_name;
private $con_email;
private $con_cell;
private $con_password;
private $cxn;
function __construct($data)
{
if (is_array($data)) {
$this->setData($data);
}
else {
throw new Exception("register not found");
}
$this->connectToDb();
$this->registerUser();
}
private function setData($data)
{
$this->con_name = $data['con_name'];
$this->con_email = $data['con_email'];
$this->con_cell = $data['con_cell'];
$this->con_password = $data['con_password'];
}
private function connectToDb()
{
include '../models/database.php';
$vars = '../include/vars.php';
$this->cxn = new database($vars);
}
function registerUser()
{
$query = mysql_query("SELECT con_email FROM consumer WHERE con_email='$this->con_email'");
if (mysql_num_rows($query) > 0) {
header('location:../invalid-consumer.php');
}
else {
$query = "INSERT INTO `consumer`(`con_id`, `con_name`, `con_email`, `con_cell`, `con_password`) VALUES ('', '$this->con_name', '$this->con_email',
'$this->con_cell', '$this->con_password' )";
$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]" . "activate.php?id=" . $current_id;
$toEmail = $_POST["con_email"];
$body = $_POST["con_name"];
$subject = "User Registration Activation Email";
$content = $_POST["con_id"];
$mailHeaders = "From: Admin\r\n";
if (mail($toEmail, $subject, $content, $mailHeaders)) {
$message = "You have registered and the activation mail is sent to your email. Click the activation link to activate you account.";
}
unset($_POST);
$sql = mysql_query($query);
if ($sql)
header('location:../success.php');
else {
throw new Exception("Error not registerd");
}
}
}
function close()
{
$this->cxn->close();
}
}
?>
An email was successfully sent for a new user registered, but not the id number found or not found. Any content email is empty.
Note: The user registered will be logged in with id number only...
How can I fix this problem?
You are trying to get the con_id from $_[POST] but that's not possible since there is no id for the person yet. Of course it will be empty. You need to retrieve the newly created id from the consumer table.
To do this in mysql_ functionality you will need to execute the query BEFORE sending the email, then use mysql_insert_id() to get the id that was inserted when you ran $query
That being said:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
It's all simple you can get the last inserted id and send it as a parameter to the link: here is how you will proceed:
In the registerUser function
}
else {
$query = "INSERT INTO `consumer`(`con_id`, `con_name`, `con_email`,
`con_cell`, `con_password`) VALUES ('', '$this->con_name', '$this->con_email', '$this->con_cell', '$this->con_password' )";
// Here you get the last inserted id and send it as an email parameter
$current_id = mysql_insert_id();
// And now you can send it correctly to the user
$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]" . "activate.php?id=" . $current_id;
This is the answer and worked correctly:
$query ="INSERT INTO `consumer`(`con_id`, `con_name`, `con_email`, `con_cell`, `con_password`) VALUES ('', '$this->con_name', '$this->con_email', '$this->con_cell', '$this->con_password' )";
$sql = mysql_query($query);
$con_id = mysql_insert_id();
$toEmail = $_POST["con_email"];
$body = $_POST["con_name"];
$subject = "User Registration Activation Email";
$content = $con_id;
$mailHeaders = "From: Admin\r\n";
if (mail($toEmail, $subject, $content, $mailHeaders)) {
$message = "You have registered and the activation mail is sent to your
}
unset($_POST);
A little background,
I'm creating a simple function that emails all users whenever the admin of a blog creates a new announcement. I want to gather all emails using an sql query and inputting them all inside the message body or perhaps looping sending the emails one at a time (though that may seem like it would take longer).
So far this is my code:
public function emailAll()
{
$this->set_mail_settings();
$message = new YiiMailMessage;
$request = Yii::app()->db->createCommand("
SELECT email FROM persons WHERE party_id
")->queryRow();
$message->subject = 'Star Cruises - Login Information';
$message->addTo('sendTo#someone.com');
$message->from = Yii::app()->params['adminEmail'];
Yii::app()->mail->send($message);
exit();
}
private function set_mail_settings()
{
$sysParam = SystemParameters::model()->getSystemParameters(
array("smtp_host", "smtp_port", 'smtp_user','smtp_password')
);
Yii::app()->mail->transportOptions['username'] = $sysParam['smtp_user'];
Yii::app()->mail->transportOptions['password'] = $sysParam['smtp_password'];
Yii::app()->mail->transportOptions['host'] = $sysParam['smtp_host'];
Yii::app()->mail->transportOptions['port'] = $sysParam['smtp_port'];
}
The emailAll() function is called whenever an email is used.
My problem is the $request. I don't know how I would gather all the emails and putting them into the $message->addTo();
UPDATE: I was doing it fine until I reached this point:
public function emailAll()
{
$this->set_mail_settings();
$message = new YiiMailMessage;
$emails = Yii::app()->db->createCommand("SELECT group_concat(email) as em FROM persons")->queryRow();
$email_ids = explode(",",$emails["em"]);
$message->setBcc($email_ids);
$message->setBody('Sample');
$message->subject = 'New Announcement!';
//$message->addTo('blah#blah.com');
$message->from = Yii::app()->params['adminEmail'];
Yii::app()->mail->send($message);
}
private function set_mail_settings()
{
$sysParam = SystemParameters::model()->getSystemParameters(
array("smtp_host", "smtp_port", 'smtp_user','smtp_password')
);
Yii::app()->mail->transportOptions['username'] = $sysParam['smtp_user'];
Yii::app()->mail->transportOptions['password'] = $sysParam['smtp_password'];
Yii::app()->mail->transportOptions['host'] = $sysParam['smtp_host'];
Yii::app()->mail->transportOptions['port'] = $sysParam['smtp_port'];
}
Then I got an error on this line from YiiMail.php:
189 $msg = 'Sending email to '.implode(', ', array_keys($message->to))."\n".
And it stated that : array_keys() expects parameter 1 to be array, null given.
I understand what it wants, but I don't understand WHY this error occurred?
You can get all email ids with use of below query and use BCC instead of To for security reason.
$emails = Yii::app()->db->createCommand("SELECT group_concat(email) as em FROM persons WHERE party_id = $party_id")->queryRow();
$email_ids = explode(",",$emails["em"]);
$message->setBcc($email_ids); // use bcc to hide email ids from other users
$message->addTo("noreply#yourdomain.com"); //as To is required, set some dummy id or your own id.
I need to read an email and then send a value in that email into another page. I've successful to read email and detect subject and date of that email. After read that incoming email, I need to send that value into another php page whoch in that page I can do background process.
Here's the code to read email
include "connect.php";
$mailbox = imap_open("{mail.xxxxx.com:143/novalidate-cert}INBOX", "username", "password"); //Note 1
$count = imap_num_msg($mailbox);
$headers = imap_headerinfo($mailbox, $count);
$sub = $headers->subject;
$time = $headers->date;
$pieces = explode("://",$sub);
$check = mysql_query("SELECT * FROM email WHERE web='$pieces[1]' AND date='$time'");
$data = mysql_fetch_array($check);
if($time != $date['date']) {
//code to send parameter here
echo "enter";
} else {
echo "no";
}
I need to send an email subject and email date into another php page. What ways can be used ? Is that with javascript, ajax or what ?
Thanks for your help,
The following program is intended to match incoming email aliases with those in the database, and forward the email to the right address, like Craigslist does.
I am now getting this error:
Error: [1] You must provide at least one recipient email address.
in anon-email.php at line number: sending the email
Here is the code:
$mailboxinfo = imap_mailboxmsginfo($connection);
$messageCount = $mailboxinfo->Nmsgs; //Number of emails in the inbox
for ($MID = 1; $MID <= $messageCount; $MID++)
{
$EmailHeaders = imap_headerinfo($connection, $MID); //Save all of the header information
$Body = imap_qprint(imap_fetchbody($connection, $MID, 1)); //The body of the email to be forwarded
$MessageSentToAllArray = $EmailHeaders->to; //Grab the “TO” header
$MessageSentToAllObject = $MessageSentToAllArray[0];
$MessageSentToMailbox = $MessageSentToAllObject->mailbox ."#". $MessageSentToAllObject->host; //Everything before and after the “#” of the recipient
$MessageSentFromAllArray = $EmailHeaders->from; //Grab the “FROM” header
$MessageSentFromAllObject = $MessageSentFromAllArray[0];
$MessageSentFromMailbox = $MessageSentFromAllObject->mailbox ."#". $MessageSentFromAllObject->host; //Everything before and after the “#” of the sender
$MessageSentFromName = $MessageSentFromAllObject->personal; //The name of the person who sent the email
$toArray = searchRecipient($MessageSentToMailbox); //Find the correct person to send the email to
if($toArray == FALSE) //If the alias they entered doesn’t exist…
{
$bounceback = 'Sorry the email in your message does not appear to be correct';
/* Send a bounceback email */
$mail = new PHPMailer(); // defaults to using php “mail()”
$mail -> ContentType = 'text/plain'; //Plain email
$mail -> IsHTML(false); //No HTML
$the_body = wordWrap($bounceback, 70); //Word wrap to 70 characters for formatting
$from_email_address = 'name#domain.com';
$mail->AddReplyTo($from_email_address, "domain.Com");
$mail->SetFrom($from_email_address, "domain.Com");
$address = $MessageSentFromMailbox; //Who we’re sending the email to
$mail->AddAddress($address, $MessageSentFromName);
$mail->Subject = 'Request'; //Subject of the email
$mail->Body = $the_body;
if(!$mail->Send()) //If the mail fails, send to customError
{
customError(1, $mail->ErrorInfo, "anon-email.php", "sending the email");
}
}
else //If the candidate address exists, forward on the email
{
$mail = new PHPMailer(); // defaults to using php “mail()”
$mail -> ContentType = 'text/plain'; //Plain E-mail
$mail -> IsHTML(FALSE); //No HTML
$the_body = wordwrap($Body, 70); //Wordwrap for proper email formatting
$from_email_address = "$MessageSentFromMailbox";
$mail->AddReplyTo($from_email_address);
$mail->SetFrom($from_email_address);
$address = $toArray[1]; //Who we’re sending the email to
$mail->AddAddress($address, $toArray[0]); //The name of the person we’re sending to
$mail->Subject = $EmailHeaders->subject; //Subject of the email
$mail->Body = ($the_body);
if(!$mail->Send()) //If mail fails, go to the custom error
{
customError(1, $mail->ErrorInfo, "anon-email.php", "sending the email");
}
}
/* Mark the email for deletion after processing */
imap_delete($connection, $MID);
}
imap_expunge($connection); // Expunge processes all of the emails marked to be deleted
imap_close($connection);
function searchRecipient() // function to search the database for the real email
{
global $MessageSentToMailbox; // bring in the alias email
$email_addr = mysql_query("SELECT email FROM tbl WHERE source='$MessageSentToMailbox'"); // temp store of the real email
$row = mysql_fetch_array($email_addr); //making temp store of data for use in program
if(empty($row['email']))
{
return FALSE;
}
else /* Else, return find the person's name and return both in an array */
{
$results = mysql_query("SELECT * FROM tbl WHERE email = '$email_addr'"); // temp store of both queries from this function
$row = mysql_fetch_array($results, $email_addr); //making temp store of data for use in program
$name = $row['author']; // taking the author data and naming its variable
return array($name, $email_addr); // this is the name and the real email address to be used in function call
}
}
function customError($errno, $errstr, $file, $line)
{
error_log("Error: [$errno] $errstr in $file at line number: $line",1, "name#domain.com","From: name#domain.com.com");
die();
}
Here is the first thing I would try:
It would appear that your function searchRecipient isn't being passed a parameter. Rather than use the global keyword, I would define it in your function call. Also, mysql_fetch_array does not pass back an associative array, which is what you are using in your next step. I would change that to mysql_fetch_assoc (it's the same thing essentially). There are also a few other minor syntax corrections in this function. Here are my proposed changes to that function. I think this should fix your problem. Or at least get you moving forward.
function searchRecipient($MessageSentToMailbox) // function to search the database for the real email
{
$email_addr = mysql_query("SELECT email FROM tbl WHERE source='$MessageSentToMailbox'"); // temp store of the real email
$row = mysql_fetch_assoc($email_addr); //making temp store of data for use in program
if(empty($row['email']))
{
return FALSE;
}
else /* Else, return find the person's name and return both in an array */
{
$email_addr = $row['email'];
$results = mysql_query("SELECT * FROM tbl WHERE email = '$email_addr'"); // temp store of both queries from this function
$row = mysql_fetch_assoc($results); //making temp store of data for use in program
$name = $row['author']; // taking the author data and naming its variable
return array($name, $email_addr); // this is the name and the real email address to be used in function call
}
}
You could also combine this into one query and make it a little easier. Here is that solution.
function searchRecipient($MessageSentToMailbox)
{
$results = mysql_query("SELECT email, author FROM tbl WHERE source='$MessageSentToMailbox'");
$row = mysql_fetch_assoc($results);
if(empty($row['email']) || empty($row['author'])) return false;
return array($row['email'], $row['author']);
}
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?
$elist = $database->getRows("SELECT * FROM `emails`");
if ($elist) {
foreach ($elist as $elist_result) {
$frm = 'rdsyh#gmail.com';
$sub = 'Weekly Work Report';
ob_start(); // start output buffering
include_once('mail_content.php');
$mail_body = ob_get_contents(); // get the contents from the buffer
ob_end_clean();
$to = $elist_result['email'];
$mailstatus = l_mail('', '', $to, $elist_result['firstname'] . ' ' . $elist_result['lastname'], $frm, 'HR', $sub, $mail_body);
}
}
if ($mailstatus == 'ok') {
echo '<center><font color=red style="font-size:14px">Message has been sent Succesfully.....!</font></center><br>';
} else {
echo $mailstatus;
}
Well, there's a lot of abstraction here that we know nothing about from your code. Things to check:
Are you certain that your database query is returning all of the results you're looking for (is $elist populated properly)?
Are you certain that the query is returning data in the format that you're trying to access it in (is $to populated properly)?
Are you certain your l_mail() function is behaving (is it possible it exit's or otherwise terminates script execution in the middle of the first pass)?
Based on what I see here, if everything else was working properly, you should successfully be sending a bunch of emails, one to each email in your list.
Now, if instead you're trying to send a single email that is sent to all of the addresses at once, then you need to group the email addresses in the for loop and then run your mail function afterwards:
<?
$tos = array();
foreach ($elist as $elist_result) {
$tos[] = $elist_result['email'];
}
$frm = 'rdsyh#gmail.com';
$sub = 'Weekly Work Report';
ob_start(); // start output buffering
include_once('mail_content.php');
$mail_body = ob_get_contents(); // get the contents from the buffer
ob_end_clean();
$to = implode(', ', $tos);
$mailstatus = l_mail('', '', $to, $elist_result['firstname'] . ' ' . $elist_result['lastname'], $frm, 'HR', $sub, $mail_body);
?>
What does l_mail() do? If its a web service, then it might have limit for mass emails.