Trouble sending emails with PHP
Hello everyone!
I've created a mailing list where users can subscribe with a form, and the results are added to a MySQL database. They can also unsubscribe. The subscribe/unsubscribe pages work GREAT, but the page where I send out the email is giving me some trouble. It says that the email was sent, but the users never get it! Any suggestions?
The PHP for the send_email.php page is:
<?php
$from = 'me@example.com';
$subject = $_POST['subject'];
$text = $_POST['body'];
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$dbc = mysqli_connect('db.server.com', 'my_username', 'my_password', 'my_database')
or die('Error: Could not connect to database');
$query = "SELECT * FROM email_list";
$result = mysqli_query($dbc, $query)
or die('Error: Could not connect to database');
while ($row = mysqli_fetch_array($result)){
$first_name = $row['first_name'];
$last_name = $row['last_name'];
$to = $row['email'];
$msg = "Hello $first_name!$textThis message was sent to $first_name $last_name ($to) because they signed up to my email listDon't want to receive these emails? Click <a href='http://my-site.com/mailing-list/remove.php?email=$to' title='Unsubscribe'>here</a> to unsubscribe.";
mail($to, $subject, $msg, $headers, 'From:' . $from);
echo 'Email sent to: ' . $to . '';
}
mysqli_close($dbc);
?>
Thanks!
calebcook
Junior Poster in Training
66 posts since Jun 2011
Reputation Points: 10
Solved Threads: 4
Have you tried commenting out the mail function and echo out the emails instead to see if you are actually getting any results from the mysql query? Also echo "Hello World" inside the while loop to see if the code is going in there.
If the query is working ok then try changing the mail function arguments. This is what I use:
$to = $_POST[email];
$subject = "Website Registration";
$message = "Welcome to our website ".$name."!\r\nPlease validated your useraccount bla bla.";
$headers = 'From: noreply@blabla.com' . "\r\n" .
'Reply-To: noreply@blabla.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
Yes, I tried that. It displayed the email as it would be sent to each person
(e.g. Hello Person1! MESSAGE
Hello Person 2! MESSAGE
and so forth.)
Also, your code that you provided does not connect to a MySQL database for emails.
calebcook
Junior Poster in Training
66 posts since Jun 2011
Reputation Points: 10
Solved Threads: 4
I've found that the problem lies on this line:
mail($to, $subject, $msg, $headers, 'From:' . $from);
I tried
mail($to, $subject, $msg, $headers);
and that worked, so for some reason
$headers, 'From:' . $from
is creating the problem.
calebcook
Junior Poster in Training
66 posts since Jun 2011
Reputation Points: 10
Solved Threads: 4