Simple newsletter system using PHP

Some days ago, I wrote a post about how to implement a newsletter system using Coldfusion and a lot of users have asked to me if I could add the same tutorial using PHP. This is the code, really simple, where I used PHPMailer to send emails.

Download this tutorial


Step 1
This picture is the folders structure of this tutorial:


PHPMailer folder contains all classes to send email from PHP, and config.php, contains info about DB connection. Take a look at config.php file source here.


Step 2: PHP and HTML Code
Create a new php page and call it index.php. Copy and past this code into this page (take a mind you have a MYSQL database installed with a table called user, with a field called email.):

<?php
if(isset($_POST['emailSubject']) && isset($_POST['emailBody']) && strlen($_POST['emailSubject'])>1 && strlen($_POST['emailBody'])>1 ){
include('config.php');
include('PHPMailer2/class.phpmailer.php');

// Get users info
$getUser_Sql = 'SELECT email FROM USER';
$getUser = mysql_query($getUser_Sql);

// Post Variables
$emailSubject = $_POST['emailSubject'];
$emailBody = $_POST['emailBody'];

while ($row = mysql_fetch_array($getUser)) {
// Get the current user's email
$emailUser = $row['email'];
// Define mail object and mail parameters
$mail = new PHPMailer();
$mail->From = 'name@mysite.com';
$mail->FromName = 'Add your name or your site name here';
$mail->AddAddress($emailUser);
$mail->Subject = $emailSubject;
$mail->Body = $emailBody;
// Send and verify
if(!$mail->Send()) {
echo 'Your message was not sent to '. $emailUser;
echo 'Error is: '. $mail->ErrorInfo;
} else {
echo 'The message has been sent to '.$emailUser;
}
}
}
?>

<form action="index.php" method="post">
<strong>Email Subject</strong><br />
<input name="emailSubject" type="text" size="32" />
<br /><br />
Email text<br />
<textarea name="emailBody" cols="20" rows="6"></textarea>
<br />
<input name="send" type="button" value="Send!" />
</form>

It's all! Source: woork.blogspot.com