I am trying to write some PHP code that emails every user in my database (around 500) their usernames. I have successfully managed to pull the email addresses and usernames for each user and store them in an array. However, I cannot figure out how to email each individual user with their individual usernames. I am pretty sure I need to use a foreach loop to do this, but I have had no luck.
Here is what I have.
<?php
include('databaseConn.php');
$query = mysql_query("SELECT * FROM staff");
$emailArray;
while ($row = mysql_fetch_array($query)) {
$emailArray[] = array($row['email']=>$row['username']);
}
print_r($emailArray); //This associative array now contains each username along with their respective email address.
?>
==***********===
WITH MAIL FUNCTION
<?php
include('functions/core.php');
$query = mysql_query("SELECT * FROM users");
$emailArray;
while ($row = mysql_fetch_array($query)) {
$emailArray[] = array($row['email']=>$row['username']);
}
foreach($emailArray as $email => $username) {
echo $username; // outputs the indexes.
$subject = 'Accoutn Details';
$message = 'This email contains your login details.<br/><br/>
<b>Username: '.$username.'</b><br/>
<br/><br/>Kind regards,<br/>';
$headers = 'From: noreply#xxxxx.co.uk' . "\r\n" .
'Reply-To: noreply#xxxxx.co.uk' . "\r\n" .
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
mail($emailAddress, $subject, $message, $headers);
}
//print_r($emailArray);
?>
bad idea to use mail in a loop unless its a one off, which it sounds like it, also most shared hosts would not allow 500 emails to be sent at once.
$subject = 'Account Details';
$headers = 'From: noreply#xxxxx.co.uk' . "\r\n" .
'Reply-To: noreply#xxxxx.co.uk' . "\r\n" .
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
while ($row = mysql_fetch_array($query)) {
$message = 'This email contains your login details.<br/><br/>
<b>Username: '.$row['username'].'</b><br/>
<br/><br/>Kind regards,<br/>';
mail("$row['email']", $subject, $message, $headers);
}
If your question is how to use foreach... http://www.php.net/manual/en/control-structures.foreach.php
For example:
foreach ($emailArray as $email => $username) {
// Send an email to $email with their $username
}
#Dagon is right, there's no need to iterate twice if there's nothing else you need the associative array for. Even if you do need an array, it doesn't necessarily have to be associative; it could be the raw rows from the DB, which you could iterate over. The only time you need an associative array is when you need to look up the values (usernames) by the keys (email addresses), which, as far as I can tell, you don't need to do.
Related
I've created a web site and I'm using this link for a JS pop up form to be emailed using PHP.
I also used the code from here and everything works except for a couple things. When I don't remove some variables, the order of information is out of place when it emails.
And when I keep all the variables, I get the following error in a log and nothing sends until I remove them:
PHP Warning: mail() expects at most 5 parameters, 7 given in xxxxxxxxxxxxxxxxxxxxx/quote.php on line 41
Below is the code where the error is coming from:
else{
$Company = $_POST['company'];
$Email = $_POST['vemail'];
$Name = $_POST['name'];
$Number = $_POST['number'];
$Info = $_POST['info'];
$headers = 'From:'. $email2 . "\r\n"; // Sender's Email
$headers .= 'Cc:'. $email2 . "\r\n"; // Carbon copy to Sender
// Message lines should not exceed 70 characters (PHP rule), so wrap it
// $message = wordwrap($message, 70);
// Send Mail By PHP Mail Function
mail("info#bvcdenver.com", $Company, $Email, $Name, $Number, $Info, $headers);
echo "Your quote request has been sent successfuly ! Thank you for your interst. You are being redirected back to xxxxxxxxxxxx in 5 seconds.";
}
How can I send all the variable? Order won't matter if I can get them all to send.
Note: I don't have a lot of scripting experience. This site is created using only HTML/CSS and these PHP and JS sections. So ideally I'd like to not change the entire site.
You need to proper use the php mail function() as it is stated here http://php.net/manual/en/function.mail.php.
The max number of parameters is 5:
- TO ( in your case: "info#bvcdenver.com" )
- SUBJECT ( in your case: $Company )
- MESSAGE ( in your case: $Email )
the last 2 are additional headers and additional parameters.
If you want to send all the data "email, name, number and info" you should organize a string/text variable and put it on the 3rd place
like:
$message = $Email . " - " . $Name . " - " . $Number . " - " . $Info;
mail("info#bvcdenver.com", $company, $message, $headers);
This should do the work and you can customize the message numbers how you want, with html or raw new lines, and get a proper template.
<?php
$to = 'nobody#example.com';
$subject = 'the subject';
$message = 'hello';//pass every variable into message
$headers = 'From: webmaster#example.com' . "\r\n" .
'Reply-To: webmaster#example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
?>
I wish to send an email to one address and cc to other addresses drawn from a table.
// get all cc email id's for this users site
$results3h = mysql_query("SELECT user_id FROM company_ccemails WHERE site_id = '$site_id' ");
echo mysql_error();
while($row = mysql_fetch_array($results3h))
{
$cc_id = $row['user_id'] ;
//get email addresses for each id
$results3i = mysql_query("SELECT username FROM user WHERE id = '$cc_id' ");
echo mysql_error();
while($row = mysql_fetch_array($results3i))
{
$ccemails = $row['username'] . "," ;
}
mysql_free_result($results3i);
}
mysql_free_result($results3h);
//send emails to
$to = "support#mydomain.com ; ";
$subject = "$email_subject";
$message = "$email_message";
$headers = "CC: " .$ccemails. "\r\n";
$headers .= "From: " . strip_tags($myusername) . "\r\n";
$headers .= "Reply-To: ". strip_tags($myusername) . "\r\n";
$headers .= "BCC: " .$myusername. "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
mail($to, $subject, $message, $headers);
when sending this email only the 'to' and 1 'cc' is sent although there are 3 'cc' email address. if I move the send code under $ccemails = $row... then an email is sent to each 'cc' separately along with support#mydomain.com. this results in support# getting lots of emails.
how do I change the code to get the cc emails in one string and send as one email so support only receives one copy?
I'm relatively new to PHP coding (usually ASP) and am sure this is straight forward but is confusing me at the moment
thanks for any help
With $ccemails = $row['username'] . "," ; you are assigning the value of $row['username'] to your $ccemails variable. This means you override it everytime in the loop.
You have to concat the string with .=
Try this below:
$ccemails = ""; // define this here, because otherwise you will get a notice
while ( $row = mysql_fetch_array( $results3h ) ) {
/**
* Your code
*/
while ( $row = mysql_fetch_array( $results3i ) ) {
$ccemails .= $row['username'] . ",";
}
/**
* Your code
*/
}
I want to send mass emails using PHP mail function. Email addresses are stored in MySQL database. There are nearly 30k email addresses. I am sending one email at a time.
60 emails are sent properly & the next all emails are skipped. I am using godaddy host to send emails. Following is code I am using
<?php
$con1=mysqli_connect("subscibe","subscibe","pw","subscibe");
$subject = $_POST['subject'];
$message = $_POST['message'];
$getusers = mysql_query("SELECT * FROM subscibe.emaillist");
$email_from = "email#gmail.com";
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
while($result = mysql_fetch_array($getusers)) {
$emailaddress = $result['Emailaddresses'];
mail($emailaddress,$subject,$message,$headers);
//Add email address to temp table
$sqlq="INSERT INTO subscibe.temp VALUES ('$emailaddress')";
if (!mysqli_query($con1,$sqlq)) {
die('Error: ' . mysqli_error($con1));
}
}
echo "Emails are sent"
?>
you may want to use a foreach loop which would send the email to each record in your DB.
Something like:
$getusers = mysql_query("SELECT * FROM subscibe.emaillist");
foreach ($getusers as $maillist) {
$mail->to($mailist['email_address']);
$mail->send()
<?php
$con = mysql_connect("localhost","dbuser","dbpass"); // replace dbuser, dbpass with your db user and password
mysql_select_db("dbname", $con); // replace dbname with your database name
/*
To use this script database table must have three fields named sno, email and sub_status
*/
$query = "select sno, email from dbtable where sub_status = 'SUBSCRIBED'";
$result = mysql_query($query, $con);
$emails = array();
$sno = array();
while($row=mysql_fetch_assoc($result))
{
$sno[] = $row['sno']; // this will be used to unsubscribe the user
$emails[]=$row['email']; // email id of user
}
/* you can also get email id data from CSV using below code */
//$file = file_get_contents("travel_database.csv");
//$emails = explode(",",$file);
/* count.txt is used to store current email sent number/count */
$count = file_get_contents("count.txt");
for($i=$count;$i<count($emails);$i++)
{
$to = $emails[$i];
// subject
$subject = 'Set Your Title Here';
// message
$message = file_get_contents("sample.html"); // this will get the HTML sample template sample.html
$message .= '<p>Please click here to unsubscribe.</p>
</body>
</html>';
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Additional headers
//$headers .= "To: $to" . "\r\n";
$headers .= 'From: Name <info#yourdomain.com>' . "\r\n";
//$headers .= 'Cc: sendcc#yourdomain.com' . "\r\n";
//$headers .= 'Bcc: sendbcc#yourdomain.com' . "\r\n";
// Mail it
if(mail($to, $subject, $message, $headers)) {
$file = fopen("mailsentlist.txt","a+"); // add email id to mailsentlist.txt to track the email sent
fwrite($file, $to.",\r\n");
fclose($file);
}
else
{
$file = fopen("notmailsentlist.txt","a+"); // add email to notmailsentlist.txt here which have sending email error
fwrite($file, $to.",\r\n");
fclose($file);
}
if(($i-$count)>=200) // this will send 200 mails from database per execution
{
$filec = fopen("count.txt",'w'); // store current count to count.txt
fwrite($filec, $i);
fclose($filec);
break;
}
}//for end
$filec = fopen("count.txt",'w'); // store fine count to count.txt this will be used as a start point of next execution
fwrite($filec, $i);
fclose($filec);
?>
I have a format simple certificate. The certificate needs to be populated with values from the database and emailed. Below is the quick fix I did. The problem is the certificates sent are not of one person instead of those queried.
$query ="SELECT r.email, r.LastName, r.OpNo,
r.QuizNo From tbl_cert where Pass =1 AND Printed is null;
$result=mysql_query($query);
while( ($row= mysql_fetch_array($result)) ){
$subject = "CPD Certificate";
$email = $row['email'];
$LastName = $row['LastName'];
$OpNo = $row['OpNo'];
$TestNo = $row['QuizNo'];
$headers = "From: online#example.com";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html;
charset=iso-8859-1' . "\r\n";
$mail_body ='<html>...Here its were my my
html comes with values from table...</html>';
if (mail($to, $subject, $mail_body, $headers)){
$query = "UPDATE `tbl_cert` SET Printed = 1
WHERE CertificateNo = " . $CertificateNo;
$certresult=mysql_query($query);
if ($certresult) {
header('Location:tsCertlist.php');
}
The problem is how to get the $mail_body to have both html and php within the while loop. My generated form or certificate was the same for the 4 users who had Passed and had not printed their certificate.
create a separate template file which contains your HTML and the places you want to insert a variable / replace something put in something like %REPLACE_FIRSTNAME%
Then use str_replace() to change your replacement vars with the db/input/whatever variables with the data you require.
$mail_body = file_get_contents("templates/emailtemplate.htm");
$mail_body = str_replace("%REPLACE_FIRSTNAME%",value_from_DB,$template);
Sorted and if you ever want to change your layout just edit the template file accordingly.
$certNo = 0;
//get $certNo from data base
$mail_body ='<html>'.$certNo.'</html>';
//send
just done a little bit of code to send out a newsletter based on a sql table.
first one with 70/80 subscribers went off fine, now when i've moved to the second one that has around 250, the body_message of the email is repeated inside the email equally to the number of people on the mailing list, in this case I was sending emails with 250 duplicates of the content inside...
not sure whats wrong with the code, have stripped it down as much as i could and was wondering if someone could talk a look and hopefully point out the issue
<?php
$i=1;
if (isset($_POST['submit_btn'])) {
connect_newsletter();
$result = mysql_query("SELECT id, mail FROM test") or die('Could not connect. ' . mysql_error());
while ($row = mysql_fetch_array($result)) {
$email = $row['mail'];
$nid = $row['id'];
$ip=$_SERVER['REMOTE_ADDR'];
$ref="http://www.domain.co.uk";
$body_message ='newsletter html code';
$y_email="noreply#domain.co.uk";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers4=$y_email;
$headers .="Reply-to: $headers4\n";
$headers .= "From: $headers4\n";
$headers .= "Errors-to: $headers4\n";
$subject="subject";
mail($email,$subject,$body_message,$headers);
echo $i." sent to ".$email;
echo "<br>";
$i++;
}
}
?>
Watching your code that is not possibile because in the loop you safely reset the value of $body and $subject
The problem could be somewhere else. Check your sendmail log