I am a bit confused about how to use foreach. I read some internet things on it and I kind of understand how it works, but I don't fully understand it. I think I could use foreach to create a PHP mass emailer that sends blank carbon copy to email addresses and adresses the customer by name in the subject (Dear, Michael Here is your email). I've figured out how to retrieve the names and emails from my database into variables and I know how to email, but I don't know how to send multiple emails at once and to associate the name and email address.
<?php
//Variables for connecting to your database.
//These variable values come from your hosting account.
$hostname = "MichaelBerna.db.10339998.hostedresource.com";
$username = "MichaelBerna";
$dbname = "MichaelBerna";
//These variable values need to be changed by you before deploying
$password = "********";
$usertable = "subscribers";
$yourfield = "name";
$yourfield1 = "email";
//Connecting to your database
$link = mysql_connect($hostname, $username, $password) OR DIE ("Unable to connect to database! Please try again later.");
mysql_select_db($dbname);
//Fetching from your database table.
$query = "SELECT * FROM $usertable";
$result = mysql_query($query);
if ($result)
{
while($row = mysql_fetch_array($result))
{
$name = $row["$yourfield"];
$email = $row["$yourfield1"];
echo "Name: $name<br>";
echo "Email: $email<br>";
//mysqli_free_result($result);
//mysqli_close($link);
}
}
?>
Here is my email code:
<?php
require_once '../PHPMailer_5.2.2/class.phpmailer.php';
$name = $_POST['name'] ;
$email = $_POST['email'] ;
//$file = $_POST['file'] ; // I'm going to later add a file later to be attached in email from database
$body = "Hey $name thank you for continuing to be a valued customer! This month's story is included in this email asa an attachment.";
$mail = new PHPMailer(true); //defaults to using php "mail()"; the true param means it will throw exceptions on errors, which we need to catch
try
{
$mail->AddAddress($email, $name);
$mail->SetFrom('admins_email#yahoo.com', 'Site Admin');
$mail->AddReplyTo('admins_email#yahoo.com', 'Site Admin');
$mail->Subject = "Dear $name Your monthly subscription has arrived!";
$mail->Body = $body;
if ($_FILES['file']['size'])
{
$mail->AddAttachment($_FILES['file']['tmp_name'], $_FILES['file']['name']);// attachment
}
$mail->Send();
echo "Email Sent Successfully</p>\n";
}
catch (phpmailerException $e)
{
echo $e->errorMessage(); //Pretty error messages from PHPMailer
}
catch (Exception $e)
{
echo $e->getMessage(); //Boring error messages from anything else!
}
?>
Basically, I need a way to combine these two scripts and link them together and that's what I'm unsure of how to do.
Put the mailing code in a function, e.g. send_mail(), so that it can be called from different places. Then change your database query loop to:
while ($row = mysql_fetch_assoc($result)) {
send_mail($row['name'], $row['email'), "Text of the email");
}
Related
I am using a PHP Script written by me with AWS (Amazon Web Service) PHP Script to send emails using SMTP
Everytime I run this script, say I have 3 user's in my database, then the first user get's mail of the first, second and third person. The second user get's mail to second and third person. And the third user get's the mail to the third person only.
I don't know why this is happening, and been pulling my hair for some time. Maybe I am missing some point, that is why adding a question here.
Pre-Requisites:
func1() = Is used to get emails from DB whom I have not send Emails Yet, return's a single value (ID) only
func2() = Is used to get the data of that particular user whose ID was found in func1()
func3() = Is used to mark "Send" to that particular ID whom we send the mail.
<?php
require 'aws-autoloader.php';
require 'vendor/autoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->setFrom('myemail#address.com', 'My Company Name');
$mail->Username = 'Username';
$mail->Password = 'Password';
$mail->Host = 'email-smtp.us-west-2.amazonaws.com';
class Db {
public function dbconnect(){
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
return $conn;
}
public function func1()
{
$conn=$this->dbconnect();
$stmt = $conn->prepare("CALL func1()");
$stmt->execute();
$result=NULL;
$result = $stmt->get_result();
$item=NULL;
while ($row = $result->fetch_array(MYSQLI_NUM))
{
$item[] = $row;
}
return $item;
$stmt->close();
$conn->close();
}
public function func2($id)
{
$conn=$this->dbconnect();
$stmt = $conn->prepare("CALL func2(?)");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$item=NULL;
while ($row = $result->fetch_array(MYSQLI_NUM))
{
$item[] = $row;
}
return $item;
$stmt->close();
$conn->close();
}
public function func3($id)
{
$conn=$this->dbconnect();
$stmt = $conn->prepare("CALL func3(?)");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$item=NULL;
while ($row = $result->fetch_array(MYSQLI_NUM))
{
$item[] = $row;
}
return $item;
$stmt->close();
$conn->close();
}
}
$count=0;
$obj=new Db;
$ids=$obj->func1();
while(($ids[0][0]!=0)&&($count<1000)){
$ids=$obj->func1();
$rslt=$obj->func2($ids[0][0]);
if($rslt[0][0]!=NULL)
{
$idno=$rslt[0][0];
$companyname=$rslt[0][2];
$email=$rslt[0][16];
$complete=NULL;
do{
$mail->addAddress($email, $companyname);
$mail->Subject = 'My Subject';
$mail->Body = '<p>Hello</p>';
$mail->AltBody = "Hello";
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->isHTML(true);
if(!$mail->send()) {
echo "Email not sent. " , $mail->ErrorInfo , PHP_EOL;
} else {
$complete=$obj->func3($ids[0][0]);
}
}while($complete[0][0]!=3);
}
$count=$count+1;
//if($count%10==0) Trying to give a small break after each 10 emails are send
sleep(1);
}
$count=$count-1;
echo 'Email Send to: '.$count.' Users.<br>';
?>
After the function is called, I receive emails as described at the start. And all the users are marked "Send"
Any Idea what I may be doing wrong to get result like that.
Your code is using the same PHPMailer object for each email, and it is adding addresses using $mail->addAddress() without resetting the list of email addresses between emails hence the list of recipients is growing each time.
You can call $mail->clearAllRecipients() for each new email or you could create a new PHPMailer object for each email. Note that if you choose the former approach then you should check to see if there are any other things that also need to be reset from one email to the next.
The assignment I'm working on (an E-commerce course) asks that I use php to generate a new password for a user and send the user an email with the new password. I successfully generate the password, send the email from my school's server to myself (a gmail account), using php mail() however the php variable representing the password is always blank. I have been looking for answers to this on here and other websites but cannot find what I'm doing wrong.
I am looking to solve this particular issue and am not looking to use PHPMailer or some other alternative. Also I am not looking to discuss more secure ways to send email, or discuss encryption, just looking to discuss this particular issue and why it is or isn't working. Thank you in advance for any advice.
if ($mysqli->conect_errno) {
die("Error: Could not connect to database." . $mysqli->connect_error);
} else {
echo "<p>Connected<br></p>";
}
$email = $_POST['email_input'];
try {
$password = reset_password($email, $mysqli);
notify_password($email, $password, $mysqli);
echo 'Your password has changed and has been emailed to you.<br>';
}
catch(Exception $e) {
echo 'Your password could not be reset';
}
function reset_password($email, $mysqli){
$new_password = randomString(8, 12);
if ($new_password == false) {
throw new Exception('could not generate new password');
}
$rand_number = rand(0, 999);
$new_password .= $rand_number;
echo "NEW PASSWORD: " .$new_password."\r\n";
$query = "UPDATE registration
SET password = sha1('".$new_password."')
WHERE email = '".$email."'";
$result = $mysqli->query($query);
if($result) {
echo "<br>Password Reset<br>";
}else {
echo "An error has occured";
}
}
function randomString($min_length, $max_length){
return substr(str_shuffle("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), $min_length, $max_length);
}
function notify_password($email, $password, $mysqli){
$query = "SELECT email FROM registration WHERE email='".$email."'";
$result = $mysqli->query($query);
if(!$result){
throw new Exception('could not find email address');
}else if ($result->num_rows == 0) {
throw new Exception('Could not find email address:user not in database');
}else {
$row = $result->fetch_object();
$email = $row->email;
$from = "From support#HelpFinder \r\n";
$mesg = "Your password has been changed to ".$password."\r\n"."Please change it the next time you log in.\r\n";
if(mail($email, 'HelpFinder Login Information', $mesg, $from)) {
return true;
}else {
throw new Exception('Could not send email.');
}
}
}
the email message that arrives
example from text book I'm learning from
check if you are sending the $password variable as parameter correctly,
may be its empty
First please check that you have a double $result before the if declaration.
$result = $result = $mysqli->query($query);
After that you could try to make a var_dump to $password variable to check if it was correctly passed to the notify_password function. You could also post the $password variable definition so we could check in more depth.
So a couple of months ago i worked on my registration form with an com code (that is being send through the email) to activate it. The case is that the registration, and the activation of it always worked. But since recently, after some changes, it suddenly wont work anymore. The registration works,the email is being send to me with the com code link, and it also says i can now log in, but as soon as i try to log in with the made account, it sends me to my login error (wrong password or email). As soon as i look in my databse i also see that the data hasnt been inserted (its empty). Ive looked and done multiple things trying to get it fixed but none of it is working. So my last resort: stack;) The code is posted below (left the form code out btw since i dont think that is giving the problem):
The code for connection to the databse is (which is included everywhere):
<?php
$user = "XX";
$host = "XX";
$password = "XX"; //http://www.codinghorror.com/blog/2007/09/youre-probably-storing-passwords-incorrectly.html //
$database = "XX";
$conn = new mysqli($host, $user, $password, $database)or die ("Error message");
// check connection
if ($conn->connect_error) {
trigger_error('Database connection failed: ' . $conn->connect_error, E_USER_ERROR);
}
?>
After entering the register button this is the register checking page:
session_start();
include('configdb.php');
if(isset($_SESSION['error']))
{
header("Location: indexresp.php");
exit;
}
else{
if (isset($_POST["submit"])){
$register = $_POST['submit'];
$email2 = strip_tags($_POST['email']);
mysqli_select_db($conn, $database);
$emailcheck = mysqli_query($conn, "SELECT email from user WHERE email='$email2'");
$check = mysqli_num_rows($emailcheck);
if ($check == 0){
}
else {
$_SESSION['error']['email'] = "This Email is already used.";
header("Location: indexresp.php");
exit;
}
}
// the register (form field) data:
$voornaam = $_POST['voornaam'];
$achternaam = $_POST['achternaam'];
$email = $_POST['email'];
$password = $_POST['wachtwoord'];
$com_code = md5(uniqid(rand()));
$sql2 = "INSERT INTO user (email, password, com_code, voornaam, achternaam) VALUES ('$email', '$password', '$com_code', '$voornaam', '$achternaam')";
require("class.phpmailer.php");
$mail = new PHPMailer();
$mail->CharSet = 'UTF-8';
$mail->IsSMTP(); // set mailer to use SMTP
$mail->SMTPSecure = "tls";
$mail->Host = "smtp.gmail.com"; // specify main and backup server
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Port = XXX;
$mail->Username = "XXXXX"; // SMTP username
$mail->Password = "XXX"; // SMTP password
$mail->SetLanguage("nl");
$mail->From = "XXXXX";
$mail->FromName = "Oblectare";
$mail->AddAddress("$email");
// name is optional
$mail->AddReplyTo("XXXXX", "Information");
$mail->WordWrap = 50; // set word wrap to 50 characters
//$mail->AddAttachment("/var/tmp/file.tar.gz"); // add attachments
//$mail->AddAttachment("/tmp/image.jpg", "new.jpg"); // optional name
$mail->IsHTML(true); // set email format to HTML
$mail->Subject = "Account registratie";
$mail->Body = "http://localhost/debasis/hoofdstuk03/confirm.php?passkey=$com_code <br>This adress needs to be copyed in the browser and this is your password:<br><br>" .$password;
$mail->AltBody = "http://localhost/debasis/hoofdstuk03/confirm.php?passkey=$com_code. This adress needs to be copyed in the browser and this is your password:" .$password;
if(!$mail->Send())
{
echo "Error mail<p>";
echo "Mail Error: " . $mail->ErrorInfo;
exit;
}
include ('mailconfirmation.php'); // text to say the email has been send
}
So this code sends an email with the activation code (com code). The code for the email confirmation is just plain text so i left it out.
The next being done is setting the activation (with the supplied link) to yes. This is the code that does that:
include('configdb.php');
$passkey = $_GET['passkey'];
$sql = "UPDATE user SET com_code=NULL WHERE com_code='$passkey'";
$result = mysqli_query($conn,$sql) or die(mysqli_error());
if($result)
{
echo '<div>Your account is now active. You may now Log in</div>';
}
else
{
echo "Some error occur.";
}
?>
So when it passes the if (connection) the user gets redirected to the index where he can login with his account info and his info should be activated (by the update). I think the problem is in this piece of code as the sql variable in here doesnt update the com_code anymore for some reason.
After the redirection i try to login with the just inputted (and as it should be: the activated) details.
The code that checks the login (which look if the pass and mail are valid) is as follows:
session_start();
include('configdb.php');
if(isset($_POST['submit_login']))
{
$email = trim($_POST['email']);
$password = trim($_POST['password']);
$result = mysqli_query($conn,"SELECT * FROM user WHERE email='$email' AND password='$password' AND com_code IS NULL"); // was password
$num_row = mysqli_num_rows($result);
$row=mysqli_fetch_array($result);
if( $num_row ==1 )
{
$_SESSION['email']=$row['email'];
header("Location: member.php");
exit;
}
else
{
include ('errorlogin.php');
}
}
I hope one of you guys can help me with this problem cause after 2 hours searching it is (for now) enough for me;)
Sorry for my english and some dutch words in the code (try'd to translate some).
Thx in advance!
Your insert part :
$sql2 = "INSERT INTO user ..."
Is never used in the provided code. Maybe you removed the SQL process by error.
Hi I am new to this and only have a basic understanding on PHP so any help would be most welcome. Basically I am trying to send an email via PHP that can have multiple recipients. The content also needs to display a list of users following certain criteria. I have got the script to look at the database and send an email however it only sends it to one person and only lists one person in the content. Please could someone advise on how to change that to email / display to multiple recipients. I know that there should be at least three people it is sent to.
Any help / pointers would be most welcome. Thank you.
<?php
session_start();
require_once('../config.php');
$errmsg_arr = array();
$errflag = false;
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
$db = mysql_select_db(database_name);
if(!$db) {
die("Unable to select database");
}
$result = mysql_query("SELECT username FROM users WHERE user_type='admin'");
while($result_email = mysql_fetch_array($result))
$to = $result_email['username'];
$result2 = mysql_query("SELECT * FROM users
WHERE ticked='1' AND NOT user_type='super'");
while($result2 = mysql_fetch_array($result2))
$body = $result2['fname'] . " " . $result2['lname'] . " , " . $result2['username'];
mail ($to, 'Subject', $body);
?>
You can do that. They just need to be comma separated.
$to = "email#email.com, email2#email2.com";
Reference: http://php.net/manual/en/function.mail.php
Also, your code is a little confusing the way you have pasted it. But if you are loading all the emails in a while loop. Then you want to send it after the while. For example:
You want it to be:
//create an empty $to string
$to = '';
//add all the emails
while($emails as $email)
{
$to .= $email . ',';
}
//remove the last comma
rtrim($to, ",");
//send away
mail($to, $subject, $message);
your code is wrong. you would have error if you used it. you need to use implode to add comma between the emails. check your php. i corrected but you have to use while statement right. you have multiple mysql query for one job. also you should not use mysql_query. use PDO instead...
you should use it like this
<?php
while($row = mysql_fetch_array($result2))
{
$addresses[] = $row['username'];
}
$to = implode(", ", $addresses);
?>
with your code
<?php
session_start();
require_once('../config.php');
$errmsg_arr = array();
$errflag = false;
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
$db = mysql_select_db(database_name);
if(!$db) {
die("Unable to select database");
}
$result = mysql_query("SELECT username FROM users WHERE user_type='admin'");
while($row = mysql_fetch_array($result2))
{
$addresses[] = $row['username'];
}
$to = implode(", ", $addresses);
$result2 = mysql_query("SELECT * FROM users
WHERE ticked='1' AND NOT user_type='super'");
$body = mysql_fetch_array($result2);
$body = $result2['fname'] . " " . $result2['lname'] . " , " . $result2['username'];
mail ($to, 'Subject', $body);
?>
You are overwriting the value of $to repeatedly with the statement $to = $result_email['username'];. You should make a comma-separated list instead. But for goodness' sake,
Consider setting the addresses as BCC, and set TO to something that does not matter, e.g. noreply#[yourdomain] to hide the recipients' addresses from each other.
Use DB-access that is not deprecated: PDO
Your call to mail() is not in a loop, so it will only send one e-mail.
And your while loop where you're setting $to is simply overwriting the previous value each time the loop iterates.
So in the end $to will be set to the last username the first query returns. And your $body will be the body you want for the last row your second query returns.
Edit: I solved the problem! It was an issue unrelated to the code that I posted - I had an exit command in the script - but all of your advice still helped in other ways.
I'm trying to automatically send an e-mail to a user when they fill out their picks on a sports website. The early part of the script works: Their picks are correctly inserted or updated in the database. The script breaks when I try to pull the user's e-mail address from a table in the MySQL database and use it to send them a message. But what is very strange about this bug is that it doesn't result in any error messages, and for some reason prevents certain echo statements from running while allowing others.
Here's the relevant code:
...
//set variable for the userID, grabbed from the session array
$userID = $_SESSION['identifier'];
...
//write query to get user's e-mail from the database
$getEmail = "SELECT `email` FROM `useraccounts` WHERE `userID` = '".$userID."'";
//execute query
$result = $db->query($getEmail);
//check if query failed
try
{
if (!$result)
{
throw new customexception("Some kind of database problem occurred when trying to find your e-mail address.");
}
}
catch (customexception $e)
{
include 'error.html';
echo $e;
$db->close();
include 'footer.php';
exit;
}
//get the info from the row
$row = $result->fetch_assoc();
//check if function ran, catch exception if it failed
try
{
if ($row === false)
{
throw new customexception("Some kind of database problem occurred when trying to get your e-mail address from your user record in the database.");
}
}
catch (customexception $e)
{
include 'error.html';
echo $e;
$db->close();
include 'footer.php';
exit;
}
//set e-mail variable
$email = $row['email'];
//set up e-mail information to send a record of their picks to the user
$toAddress = "$email";
$subject = "Your Picks";
$fromAddress = "From: picks#mysite.com";
//take the info the user submitted, format it for the e-mail, and assign to variable $mailContent
//the $winner1, $spread1, etc. variables are defined earlier in the function, and were successfully submitted into the database
$mailContent = "You picked $winner1 to win by $spread1 points, $winner2 to win by $spread2 points, $winner3 to win by $spread3 points, $winner4 to win by $spread4 points, and $winner5 to win by $spread5 points. \n".
"You can change your picks at any time before 1:00pm EST, February 27, 2011. Just go back to the form on the game page and enter your new picks. Good luck!";
//use wordwrap to limit lines of $mailContent to 70 characters
$mailContent = wordwrap($mailContent, 70);
//send the e-mail
$isMailed = mail($toAddress, $subject, $mailContent, $fromAddress);
//debug: check if mail failed
if (!$isMailed)
{
echo "Mail failed.";
}
//debug: echo $email to see if there's anything in there
echo "<p>E-mail: $email</p>";
//debug: echo $toAddress to see if there's anything in there
echo "<p>To address: $toAddress</p>";
//if everything succeeded, write reply and close database
echo $reply;
$db->close();
?>
Just to be clear, $userID is set correctly, because their picks enter the database like they're supposed to. None of the exceptions listed in the code come up, meaning the query seems to have run successfully. I checked the query again by copying it from the PHP code and running it directly on the MySQL database. When it ran directly, it found the correct e-mail address for every userID value I entered.
But the mail never gets delivered, and when I try to echo the $email and $toAddress variables to see if they're empty:
//debug: echo $email to see if there's anything in there
echo "<p>E-mail: $email</p>";
//debug: echo $toAddress to see if there's anything in there
echo "<p>To address: $toAddress</p>";
...nothing shows up. Not even an error message. And that doesn't necessarily mean that the variables are empty: Not even the labels are echoed.
I also tried the code with my personal e-mail hardcoded instead of $toAddress, and no mail was sent. So the mail function isn't working.
I should also note that the script still successfully echoes $reply (which is a string defined much earlier) at the end.
What's really strange is that the login script for my website uses an almost identical piece of code and works perfectly:
$getuserID = "SELECT `userID` FROM `useraccounts` WHERE `u_name` = '".$login."' AND `p_word` = SHA1('".$password."')";
$result = $db->query($getuserID);
//check if query ran, catch exception if it failed
try
{
if ($result === false)
{
throw new customexception("Some kind of database problem occurred when trying to find your user ID.");
}
}
catch (customexception $e)
{
include 'error.html';
echo $e;
$db->close();
include 'footer.php';
exit;
}
//get the info from the row
$row = $result->fetch_assoc();
//check if function ran, catch exception if it failed
try
{
if ($row === false)
{
throw new customexception("Some kind of database problem occurred when trying to get info from your user record in the database.");
}
}
catch (customexception $e)
{
include 'error.html';
echo $e;
$db->close();
include 'footer.php';
exit;
}
//set userID variable
$userID = $row['userID'];
//assign the session identifier and include successfullogin.html if all is well
$_SESSION['identifier'] = $userID;
And I used to have the signup script send me an e-mail every time I got a new user, so I know that mail() works in general with my hosting provider:
//set up static e-mail information
$toAddress = "myemail#mysite.com";
$subject = "Advance Sign-Up";
$mailContent = "Name: $firstName $lastName \n".
"Username: $username \n".
"Password: $password \n".
"E-mail: $email \n".
"Country: $country \n".
"State: $state \n".
"City: $city \n".
"ZIP: $zip \n";
$fromAddress = "From: $email";
...
mail($toAddress, $subject, $mailContent, $fromAddress);
This bug is completely mystifying to me. I wish I had some sort of error message to work with, at least. Can anyone see what's wrong?
It should be a comment but for the sake of formatting.
Your way of error handling is quite unusual.
If you really want to use exceptions, it should be done different way: one try block and multiple throws:
try
{
$getEmail = "SELECT `email` FROM `useraccounts` WHERE `userID` = '".$userID."'";
$result = $db->query($getEmail);
if (!$result)
{
throw new customexception("Some kind of database problem occurred when trying to find your e-mail address.");
}
$row = $result->fetch_assoc();
if ($row === false)
{
throw new customexception("Some kind of database problem occurred when trying to get your e-mail address from your user record in the database.");
}
$email = $row['email'];
$toAddress = "$email";
$subject = "Your Picks";
$fromAddress = "From: picks#mysite.com";
$mailContent = "yadda yadda yadda";
$mailContent = wordwrap($mailContent, 70);
mail($toAddress, $subject, $mailContent, $fromAddress);
}
catch (customexception $e)
{
include 'error.html';
echo $e;
$db->close();
include 'footer.php';
exit;
}
?>
Are you positive the database variables have contents? I use echo (or print) to quickly make sure the variables aren't empty. Are you positive your email code works? Try it with set values (such as your own personal e-mail) to make sure it works.
The best way out to ignore such notices is to ensure that the variables exist or in plain PHP, use isset(),if !isset() throw an exception/error and handle it properly.