Sending emails to multiple recipients (PHP, My SQL) - php

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.

Related

sending an email in PHP with information taken from database

I want to pull an email from the database as the recipient. If I replace the line "SELECT student_user_email FROM students";' with an actual email address I get the desired outcome. However it would be handier to pull a particular email address from the 'students' table. Below is the current code. Wondering if anyone can help?
mail('"SELECT student_user_email FROM students";','Sample Form',$msg, 'From: johnsmith#gmail.com');
First, use mysqli or PDO because the mysql_ functions are depricated. The documentation has very useful information to get started with it.
mysqli: http://php.net/manual/en/book.mysqli.php
pdo: http://us3.php.net/pdo
mail: http://us3.php.net/manual/en/function.mail.php
This is what you need to do to connect to your database (from the php documentation: http://www.php.net/manual/en/mysqli.quickstart.connections.php)
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
Once connected you can query the database:
$result = $mysqli->query("SELECT student_user_email FROM students");
while ($row = $result->fetch_object()) {
if (isset($row->student_user_email)) {
mail($row->student_user_email,'Sample Form',$msg, 'johnsmith#gmail.com');
}
}
You can't send email to a multiple recipients in this way. Because query return array list so you must be looping and send email one by one recipients by this following way,
Try this will work:
<?php
$con = mysqli_connect("localhost", "uname", "password");
if (!$con){
die('Could not connect: ' . mysqli_error());
}
$db_selected = mysqli_select_db("database",$con);
$sql = "SELECT student_user_email FROM students";
$result = mysqli_query($sql,$con);
while ($row_data = mysqli_fetch_array($result)) {
// 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 = 'Sample Form';
$msg = 'Hello world!';
mail($to, $subject, $msg, $from);
}
?>

Wordpress PHP Server Script to send email

I am trying to get a server script to use wp_mail() and send an email to a user. I am doing this as part of a password reset routine, and calling the script with Ajax from the user's side.
I am getting the following error from my server script:
Fatal error: Call to undefined function wp_mail() in /var/www/abc-php/pwd.php on line 57
I cannot seem to find an answer to my question, so maybe I am asking incorrectly. Is what I am doing possible?
My server script (pwd.php) contains:
<?php
$setFromId = "info#abc.com.au";
$setFromName = "Info # abc";
$replyToId = "info#abc.com.au";
$replyToName = "Info # abc";
$sendToEmail = base64_decode($_GET["ste"]); //the URL in AJAX call contains base64 encoded data
$resetPwd = base64_decode($_GET["rp"]);
$resetSalt = base64_decode($_GET["rs"]);
$param = $_GET["var"];
$username = "xxxxxxxxx";
$password = "xxxxxxxx";
$host = "localhost";
$database = "xxxxxxxxx";
$con = mysqli_connect($host, $username, $password, $database);
// Check connection
if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else {
switch ($param) {
case "PWDRES": // Query 1: Current Logged In Partner Details
$mysqli = new mysqli($host, $username, $password, $database);
if (mysqli_connect_errno()) {
echo '<p>Unable to connect to the server at this time to update and send password. Please contact SMA for help or try again.</p>';
} else {
$myquery = "UPDATE abc_users
SET `password` = SHA2('" . $resetPwd . $resetSalt . "', 512),
`salt_value` = SHA2('" . $resetSalt . "', 512)
WHERE email_user_id = '" . $sendToEmail . "'";
mysqli_query($mysqli, $myquery);
if($mysqli->affected_rows >= 1) {
$headers = 'Reply-To: <' . $replyToName . '> ' . $replyToId;
$subject = "Password Reset - Confidential";
$body = "Subject: " . $subject . "<br/><br/>Your new password is: <br/><strong>" . $resetPwd . "</strong><br/><br/>Please ensure you reset this password next time you log in.";
$mail = wp_mail($sendToEmail, $subject, $body, $headers);
echo "Password was successfully reset and sent to " . $sendToEmail;
} else if($mysqli->affected_rows == 0) {
echo "No user id row was updated in the process of resetting password. Please try again.";
} else if($mysqli->affected_rows < 0) {
echo "There was an SQL error updating the user id password table. Please contact SMA for help.";
};
};
break;
case "OTHER1"
etc, etc, etc...
default;
};
};
unset($con);
unset($myquery);
unset($mysqli);
?>
Any help is appreciated.
You need to include wp-load.php in your file....
Just put this in top of your file.
require_once( dirname(__FILE__) . '/wp-load.php' );
The problem is you are not including Wordpress, so you are not using it at all (and it isn't including its libraries).
Plus, this is unrelated to the question, but you have a weakness in your code :
Any users can define the recipient of the email.

PHP Foreach used to send emails from database?

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");
}

Creating messages (ie drafts) in Gmail with IMAP/SMTP?

I've done quite a bit of inbox manipulation with Gmail via IMAP functions in PHP, but one thing I haven't found is a way to create messages. I'm not sure if IMAP or SMTP is required, but I would like to use PHP to create a new message (specifically a draft) that is stored in my inbox with everything ready to hit send at a later date. How do I go about this?
You might want to look at imap_mail_compose()
Edit
This doesn't create the message on the server. You need to use imap_append() also.
Further Edit
This seems to work ok:
<?php
$rootMailBox = "{imap.gmail.com:993/imap/ssl}";
$draftsMailBox = $rootMailBox . '[Google Mail]/Drafts';
$conn = imap_open ($rootMailBox, "sdfsfd#gmail.com", "password") or die("can't connect: " . imap_last_error());
$envelope["to"] = "test#test.com";
$envelope["subject"] = "Test Draft";
$part["type"] = TYPETEXT;
$part["subtype"] = "plain";
$part["description"] = "part description";
$part["contents.data"] = "Testing Content";
$body[1] = $part;
$msg = imap_mail_compose($envelope, $body);
if (imap_append($conn, $draftsMailBox, $msg) === false) {
die( "could not append message: " . imap_last_error() ) ;
}

PHP, Email and Cron

Let me rephrase my question, I have a mysql database that is holding emails to be sent, on a shared host. I would like to run a cron job that will read the database and sent out any messages in the database every 10 minutes or so.
Now my question is, what is the best way with php to read my database and send out the emails in small batched so that I don't overwhelm the shared host.
Assuming the use of PDO, and making some accommodation for not knowing your schema, it might look something like this:
$dbh = new PDO('mysql:dbname=testdb;host=127.0.0.1', 'dbuser', 'dbpass');
$msgh = $dbh->prepare('SELECT subject, body from message where listname = :listname');
$msgh->bindParam(':listname', $listname, PDO::PARAM_STR);
$msgh->execute();
$msg = $msgh->fetch(PDO::FETCH_ASSOC);
$usrh = $dbh->prepare('SELECT recipient from userlist where is_subscribed_to = :listname');
$usrh->bindParam(':listname', $listname, PDO::PARAM_STR);
$usrh->execute();
while ($recipient = $usrh->fetch(PDO::FETCH_ASSOC)) {
mail($recipient, $msg['subject'], $msg['body']);
if ($over_throttle) {
sleep(THROTTLE_SLEEP_SECONDS);
$over_throttle = 0;
}
++$over_throttle;
}
As for 'prewritten', you might take a look at phplist.
I would leave the throttling to the email server. Ie, run an email server locally, and have your PHP code relay all these messages to that. Then configure the email server itself to only send out at a certain rate.
Well I came up with this solution similar to the PDO one. Are there any unforeseen problems with running this as a cron job?
<?php
$con = mysql_connect("localhost","root","123456");
$throttle = 0;
$batch = 50;
$pause = 10; // seconds
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("maildb", $con);
// Message Table
$MSGresult = mysql_query("SELECT * FROM msgs");
// User Table
$USERresult = mysql_query("SELECT * FROM members");
while($MSGrow = mysql_fetch_array($MSGresult))
{
while($USERrow = mysql_fetch_array($USERresult))
{
mail($USERrow['email'],$MSGrow['subject'],$MSGrow['body']);
$throttle += 1;
if ($throttle > $batch ) { sleep($pause); $throttle = 0;}
}
mysql_data_seek($USERresult,0);
}
mysql_close($con);
?>

Categories