Send email to adress from mysql database
Posted: Tue Mar 08, 2011 8:57 am
I would like to be able to send emails to people who have entered their details in my sql database.
I have some code that I think should work, but no such luck.
The database name is correct, the table name is LtUsers, and email is stored in the Email field. All I need to happen is for the code to connect to the database, select the email addresses and send the same static text email to all of them.
I have pasted the code below. When I run it, there are no error messages - just a blank screen and the emails are not sent. I know I am missing something obvious here - but any help would be great.
<?php // set db access info as constants
define ('DB_USER','mydbuser');
define ('DB_PASSWORD','mypass');
define ('DB_HOST','localhost');
define ('DB_NAME','mydbname');
// make connection and select db
$dbc = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) OR die ('Could not connect to MySQL: ' . mysql_error() );
mysql_select_db(DB_NAME) OR die ('Could not select the db: ' . mysql_error() );
$recipients = "SELECT Email FROM LtUsers";
$email_list = $db->query($recipients);
foreach($email_list as $row) { $to = $row['email'];
$subject = "Subject test subject";
$body = "Message from me to all";
if (mail($to, $subject, $body)) { echo("<p>Message successfully sent!</p>");
} else {
echo("<p>Message delivery failed...</p>");
}
}
?>
I have some code that I think should work, but no such luck.
The database name is correct, the table name is LtUsers, and email is stored in the Email field. All I need to happen is for the code to connect to the database, select the email addresses and send the same static text email to all of them.
I have pasted the code below. When I run it, there are no error messages - just a blank screen and the emails are not sent. I know I am missing something obvious here - but any help would be great.
<?php // set db access info as constants
define ('DB_USER','mydbuser');
define ('DB_PASSWORD','mypass');
define ('DB_HOST','localhost');
define ('DB_NAME','mydbname');
// make connection and select db
$dbc = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) OR die ('Could not connect to MySQL: ' . mysql_error() );
mysql_select_db(DB_NAME) OR die ('Could not select the db: ' . mysql_error() );
$recipients = "SELECT Email FROM LtUsers";
$email_list = $db->query($recipients);
foreach($email_list as $row) { $to = $row['email'];
$subject = "Subject test subject";
$body = "Message from me to all";
if (mail($to, $subject, $body)) { echo("<p>Message successfully sent!</p>");
} else {
echo("<p>Message delivery failed...</p>");
}
}
?>