How to Send Out a Mass Email Using PHP

Posted in php by ShortLikeAFox on September 19th, 2008

So you want to send out a mass email or you want to create a program that can quickly be changed to send out multiple mass emails. PHP makes this easy. In this example I will assume that you have a list of email addresses you want to send a certain email to. I will also assume that you are keeping this list in a database, but this code could easily be adjusted to use either a hardcoded email address list or list from another source.

<?php

 

//First connect to the database that contains the email address information.
$user = "USER";
$host = "HOST";
$password = "PASSWORD";
$database = "DATABASE";

$cxn = mysql_connect($host, $user, $password) or die ("Couldn’t connect to server");
mysql_select_db($database);

//Query the table that contains the email addresses. Fill in your own table name here…
$query = "SELECT * FROM theEmailAddresses ";
$result = mysql_query($query, $cxn) or die (mysql_error($cxn));
$nrows = mysql_num_rows($result);

//Who the sender will be identified as. You can put what you want here, but it really isn’t too ethical to place an email address that you don’t control here.
$from = "From: me@mydomain.com";
//A standard email subject line
$subject = "What’s new at mydomain.com ";
//The message
$message = "Hi valued friend,

We now sell cookies at mydomain.com. Be sure to check it out!
Sincerely,
me"
;

//We’ve already queried all of the email address. Now we just need to send the email
for ($i = 0; $i <$nrows; $i++){

$row = mysql_fetch_assoc($result);
extract($row);
//Replace $email with whatever the column of email addresses is called
$to = "$email";
//Send the email to each email in the database
if(mail($to, $subject, $message, $from)){

//Print the name of emails that were successfully sent. I use this just to make sure that the program hasn’t frozen. In theory their should be a steady stream of names being printed>

echo("$to<br/>");

}

}




?>

This bit of code takes advantage of the php mail() function. This is a very powerful and easy to use function. Remember that with great power comes great responsibility. Try not to use this function for evil.

Leave a Comment