Links & Resources

Home
Tutorial
CSV To XML
Email Scripts
Form to email
Newsletter
Email this page
Captcha
Display a Table

sponsored link

sponsored link

Newsletter

This script allows you to send out an html page by multipart email (Html text and images). The main por tion of the script is the sendmail function and I have included a database lookup script and and also form script The database script assumes you have a database of members and their emails who have "opted in".

You can create a simple database by going into your website's mysql section and creating your database, user and password then going into phpmyadmin and running this MySql script in your database.

DROP TABLE IF EXISTS `members`;
CREATE TABLE `members` (
`id` int(7) NOT NULL auto_increment,
`user` varchar(20) NOT NULL default '',
`email` varchar(40) NOT NULL default '',
`optin` enum('0','1') NOT NULL default '0',
PRIMARY KEY  (`id`)
) TYPE=MyISAM AUTO_INCREMENT=1 ;

Now create your newsletter as a standard HTML / XHTML page also to can if you wish create a text file for users with text only email. Replace you variables in your page with words in [square brackets]. So if you want to put a date in the newsletter you must pur [date] in the HTML and text files and enter the appropriate lines in the script. In this example I will include the variables [date],[season],[user] and [email] but you can easily change these to suit your own requirement.

The newsletter file would look like this:

<html>
<head>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<a href="index.php">Home</a>
<p>Hi [user].</p>  
<p>This is the [season] newsletter.</p> 
<p>This email has been sent to [email] and was sent
on [date].</p>
<img src="images/logo.jpg />
</body>
</html>

and the text file

Hi [user].
This is the [season] newsletter.
This email has been sent to [email] and was sent on [date].
visit my home page at http://example.com

If you use an input form to send the emails put this script in any page in your website change the action="sendmail.php" to the name of your script.

<table>
<form action="sendmail.php" method="post">
<tr>
<td>User Name </td>
<td>
<input name="user" type="text" size="6" maxlength="6" />
</td>
</tr>
<tr>
<td>Email</td>
<td>
<input name="email" type="text" size="15" maxlength="30" />
</td>
</tr>
<tr>
<td></td>
<td><input name="Submit" type="submit" value="Submit" /> </td>
</tr>
</form>
</table>

In the sendmail program first you must set the variables and parameters

$uservar['date']=date("d-m-Y");
$uservar['season']="summer";
$sendmail['path']="";
$sendmail['filename']="newsletter.php";
$sendmail['textfile']="text.txt";
$sendmail['frommail']="you@example.com";
$sendmail['fromname']="You";
$sendmail['Subject']="Subject Line of email";
$sendmail['style']= "style.css";
//copy and paste your style tag here
$sendmail['oldstyle']='<link href="style.css" rel="stylesheet" 
type="text/css" />';
$sendmail['url']="example.com";

If you are using a database get the user names and email addresses and then call the sendmail function.

$dbase="host_db";
$dbuser="host_db";
$dbpass="password";
$link = mysql_connect("$dbhost", "$dbuser", "$dbpass")
or die("Could not connect : " . mysql_error());
mysql_select_db("$dbase") 
or die("Could not select database");
$query = "SELECT * from members WHERE optin='1'";
$result = mysql_query($query) 
or die("Select Query failed : " . mysql_error());
while ($line = mysql_fetch_assoc($result))
{
extract($line);
$sendmail['user']=$user;
$sendmail['email']=$email;
$uservar['user']=$user;
$sendmail['email']=$email;
sendmail($sendmail,$uservar);
}

If you have used the input form get the $_POST variables. As you are using the user and email variables in the body of the newsletter as well as the headers you must set them in the $uservar array as well the $sendmail array

if($_POST['Submit']=="Submit")
{
$sendmail['user']=$_POST['user'];
$sendmail['email']=$_POST['email'];
$uservar['user']=$_POST['user'];
$uservar['email']=$_POST['email'];
sendmail($sendmail,$uservar);
}

The start of the main sendmail function reads the html (php) file and if neccesary evaluates any dynamic PHP in the page.

function sendmail($sendmail,$uservar)
{
ob_start();
include ($path.$filename);
$html = ob_get_contents();
ob_end_clean();

If you are using a separate text file now is the time to read in the text file. Also replace the variables in square brackets in the html and text with the values of the variables.:

if ($textfile) $text=file_get_contents($textfile);
if (count($uservar))
{
foreach ($uservar as $key=>$value)
{
$html=str_replace("[".$key."]",$value,$html);
if ($text) $text=str_replace("[".$key."]",$value,$text);
echo "[".$key."]".$value."<br>";
}
}

Now you must change the relative page links in the html part of your newsletter with absolute values ie <a href="index.php"> becomes <a href = "http://wwww.example.com/index.php">

$i=0;
do {
$posn =strpos($html,"<a",$posn);
if (!$posn) break;
$posn =strpos($html,"href",$posn);
$tagstart =strpos($html,"\"",$posn);
$tagstart++;$tagend =strpos($html,"\"",$tagstart);
$tagurl[$i] = substr($html,$tagstart,$tagend-$tagstart);
$i++;
} 
while ($posn);
if(count($tagurl))
{
$tagurl=array_unique($tagurl);
foreach($tagurl as $key=>$value)
{
if( substr($value,0,7)!="http://")
{
$html=str_replace('href="'.$value,
'href="http://www.'.$url."/".$value,$html);
}
}
}

The css style needs to be embedded into the html only so if you are not using a separate text file copy the html to the variable $text.

Now embed the css into the html in place of the link tag to the css file.

if (!$text) $text=$html;
if($style){
$styles =file_get_contents($path.$style);
$styles= "<style type='text/css'>\r\n".$styles;
$styles=$styles."\r\n</style>";
$html=str_replace($oldstyle,$styles,$html);
}

The next stage is to create an array of the variables used, firstly in the CSS style tag

$i=0;
do {
$posn =strpos($html,"image:url",$posn);
if (!$posn) break;
$imstart =strpos($html,"(",$posn);
$imstart++;
$imend =strpos($html,")",$imstart);
$imgurl[$i] = substr($html,$imstart,$imend-$imstart);
$imst= strrpos($imgurl[$i],"/");
$imgpath=substr($imgurl[$i],0,$imst+1);
$img[$i] = substr($imgurl[$i],$imst+1,$imend-$imstart-$imst);
$img[$i]=str_replace("%20"," ",$img[$i]);
$file_content =file_get_contents($imgpath.$img[$i]);
$encoded[$i] = chunk_split(base64_encode($file_content)); 
$i++;
$posn++;
} while ($posn);

Then in the body of the html.

do {
$posn =strpos($html,"<",$posn);
$posn =strpos($html,"img",$posn);
if (!$posn) break;
$posn =strpos($html,"src",$posn);
$imstart =strpos($html,"\"",$posn);
$imstart++;
$imend =strpos($html,"\"",$imstart);
$imgurl[$i] = substr($html,$imstart,$imend-$imstart);
$imst= strrpos($imgurl[$i],"/");
$imgpath=substr($imgurl[$i],0,$imst+1);
$img[$i] = substr($imgurl[$i],$imst+1,$imend-$imstart-$imst);
$img[$i]=str_replace("%20"," ",$img[$i]);
$file_content =file_get_contents($imgpath.$img[$i]);
$encoded[$i] = chunk_split(base64_encode($file_content)); 
$i++;
} while ($posn);

Wordwrap the text to 70 character lines and format the text part of the email, adding line feeds and tabs also (if no separate text file was used) delete all html tags apart from the hyperlinks.

$text = wordwrap($text, 70);
$blocktags=array ("</h1>","</h2>","</tr>",
"<br />","</p>","</li>");
$text=str_replace($blocktags,"\r\n",$text);
$text=str_replace("</td>","\t",$text);
$text=strip_tags($text,"<a>");
$text=html_entity_decode($text);

Create the mime boundaries

$boundary0 = "000-".md5(uniqid(time()));
$boundary1=str_replace("000-","001-",$boundary0);

Add the html, text and images separated by the boundaries and the mime enconding into the $Message variable. (The spacing in this section is fairly crititcal and as I have shortened some of the lines to fit the page it is better to download the sendmail.php file.

$Message ="--".$boundary0."\r\n";
$Message .="Content-Type: multipart/alternative;\r\n";
$Message .="\tboundary=\"".$boundary1."\"\r\n\r\n";
$Message .="--".$boundary1."\r\n";
$Message .="Content-Type: text/plain;\r\n";
$Message .="charset=\"iso-8859-1\"\r\n\r\n";
$Message .=$text."\r\n";
$Message .="--".$boundary1."\r\n";
$Message .="Content-Type: text/html;\r\n";
$Message .="\tcharset=\"iso-8859-1\"\r\n\r\n";
$Message .=$html."\r\n\r\n";
$Message .="--".$boundary1."--\r\n";
$imgtmplt="\r\n--".$boundary0."\r\nContent-Type: 
image/[ext];\r\n\tname=\"[imagefile]\"
Content-Transfer-Encoding: base64\r\n
Content-Location: [imageurl]\r\n[base 64]";
$i=0;
while ($img[$i])
{
$imgtmp=$imgtmplt;
$path_parts = pathinfo($img[$i]);
$ext=$path_parts['extension']; 
$imgtmp=str_replace("[ext]",$ext,$imgtmp);
$imgtmp=str_replace("[imagefile]",$img[$i],$imgtmp);
$imgtmp=str_replace("[imageurl]",$imgurl[$i],$imgtmp);
$imgtmp=str_replace("[base 64]",$encoded[$i],$imgtmp);
$Message.=$imgtmp;
$i++;
}
$Message.="--".$boundary0."--";

 

Add the recipient, headers, send the email and close the sendmail function

$Recipient =$email;
$Headers = "Return-path: <".$frommail.">\r\nFrom: ".$fromname.
"<".$frommail.">\r\nMIME-Version: 1.0\r\n
Content-Type: multipart/related;\n boundary=\"$boundary0\" ";
$mailsent=mail($Recipient, $Subject, $Message, $Headers);
}

Finally add your own page or script to continue after the emails have been sent. The variable $mailsent is set to TRUE if the mail has been sent correctly and FALSE otherwise. You could use that variable to create your own counter or test if mail has been sent correctly

echo '<a href="index.php">Click here to continue</a>';

Download sample files in zip format:

Included Files

Demonstration:

User Name
Email