PHP Newsletter script

24.Sep.2010

Suppose you’ve just finished designing your personal newsletter and you wish to test it. Here’s a small snippet that you might find handy.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$query = 'SELECT id, email FROM users';
$result = mysql_query($query);
 
while ($row = mysql_fetch_assoc($result)) {
 
 	$email_address = $row['email'];
 	$id = $row['id'];
 
 	$subject = 'Newsletter subject';
 	$message = file_get_contents('newsletter.html');
 	$message = str_replace('http://www.xxxxxxxxxxxx.com', 'http://unsusbcribescript.mysite.com?id='.$id, $message);
 
 	$headers  = 'MIME-Version: 1.0' . "rn";
 	$headers .= 'Content-type: text/html; charset=iso-8859-1' . "rn";
 	$headers .= 'From: Me <[email protected]/>' . "rn";
 
 	mail($email_address, $subject, $message, $headers);
 
}

There are few things you need to audit before sending the e-mails.

Edit the line 1 for setting the proper database query, line 9 for setting the message subject, and line 15 for setting the sender’s address.
Also, in your newsletter, edit the unsubscribe href link and set it to something like “http://www.xxxxxxxxxxxx.com”. In that way, you can dynamically generate the proper unsubscribe link for each of your readers without parsing the complete html code (line 13).

When finished, simply save your design as newsletter.html, put it next to this script, and go ahead check your luck (: