PHP
  Home arrow PHP arrow Page 3 - Composing Messages in HTML for MIME Email with PHP
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
Google.com  
PHP

Composing Messages in HTML for MIME Email with PHP
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 6
    2008-07-30


    Table of Contents:
  • Composing Messages in HTML for MIME Email with PHP
  • Review: sending MIME-compliant messages in plain text format
  • Sending email messages in HTML format
  • Sending email in HTML format using the MIME mailer class

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    Composing Messages in HTML for MIME Email with PHP - Sending email messages in HTML format
    ( Page 3 of 4 )

    As I stated in the prior section, it’d be extremely convenient to provide the “Mailer” class with the ability to send email messages in HTML format. This would exploit all the features offered by the MIME extension.

    Fortunately, incorporating this functionality to the mailer class is a only a matter of adding a pair of brand new methods, which, obviously, will be responsible for dispatching email messages formatted in HTML. However, this is merely theory that needs to be put into practice. Thus, let me show you the modified signature of the “Mailer” class, including the additional methods that send email in HTML.

    Here’s the full source code of the class:


    class Mailer{

    var $sender;

    var $recipient;

    var $subject;

    var $headers=array();

    var $mimeTypes=array();

    var $html=array();

    var $attachments=array();

    function Mailer($sender,$recipient,$subject,$message){

    // validate incoming parameters

    if(!preg_match("/^.+@.+$/",$sender)){

    trigger_error('Invalid value for email sender.');

    }

    if(!preg_match("/^.+@.+$/",$recipient)){

    trigger_error('Invalid value for email recipient.');

    }

    if(!$subject||strlen($subject)>255){

    trigger_error('Invalid length for email subject.');

    }

    if(!$message){

    trigger_error('Invalid value for email message.');

    }

    $this->sender=$sender;

    $this->recipient=$recipient;

    $this->subject=$subject;

    $this->message=$message;

    // define some default MIME headers

    $this->headers['MIME-Version']='1.0';

    $this->headers['Content-Type']='multipart/mixed;boundary="MIME_BOUNDRY"';

    $this->headers['From']='<'.$this->sender.'>';

    $this->headers['Return-Path']='<'.$this->sender.'>';

    $this->headers['Reply-To']=$this->sender;

    $this->headers['X-Mailer']='PHP 4/5';

    $this->headers['X-Sender']=$this->sender;

    $this->headers['X-Priority']='3';

    // define some default MIME types

    $this->mimeTypes['image/jpeg']='jpg';

    $this->mimeTypes['image/jpg']='jpg';

    $this->mimeTypes['image/gif']='gif';

    $this->mimeTypes['text/plain']='txt';

    $this->mimeTypes['text/html']='htm';

    $this->mimeTypes['text/xml']='xml';

    $this->mimeTypes['application/pdf']='pdf';

    }

    // add new MIME header

    function addHeader($name,$value){

    $this->headers[$name]=$value;

    }

    // add HTML to message

    function addHTML($html){

    if(!$html){

    trigger_error('Invalid HTML.',E_USER_ERROR);

    }

    $this->html[]=$html;

    }

    // add new attachment

    function addAttachment($attachment){

    if(!file_exists($attachment)){

    trigger_error('Invalid attachment.',E_USER_ERROR);

    }

    $this->attachments[]=$attachment;

    }

    // get MIME Type of attachment

    function getMimeType($attachment){

    $attachment=explode('.',basename($attachment));

    if(!$mimeType=array_search(strtolower($attachment[count($attachment)-1]),$this->mimeTypes)){

    trigger_error('MIME Type not found.',E_USER_ERROR);

    }

    return $mimeType;

    }

    // create message MIME headers

    function buildHeaders(){

    foreach($this->headers as $name=>$value){

    $headers[]=$name.': '.$value;

    }

    return implode("\n",$headers)."\nThis is a multi-part message in MIME format.\n";

    }

    // create text part of the message

    function buildTextPart(){

    return "--MIME_BOUNDRY\nContent-Type: text/plain; charset=iso-8859-1\nContent-Transfer-Encoding: quoted-printable\n\n\n".$this->message."\n\n";

    }

    // create HTML part of the message

    function buildHTMLPart(){

    if(count($this->html)>0){

    $htmlPart='';

    foreach($this->html as $html){

    $htmlPart.="--MIME_BOUNDRY\nContent-Type: text/html; charset=iso-8859-1\nContent-Transfer-Encoding: 8bit\n\n\n".$html."\n\n";

    }

    return $htmlPart;

    }

    }

    // create attachments part of the message

    function buildAttachmentPart(){

    if(count($this->attachments)>0){

    $attachmentPart='';

    foreach($this->attachments as $attachment){

    $fileStr=file_get_contents($attachment);

    $fileStr=chunk_split(base64_encode($fileStr));

    $attachmentPart.="--MIME_BOUNDRY\nContent-Type: ".$this->getMimeType($attachment)."; name="".basename($attachment).""\nContent-disposition: attachment\nContent-Transfer-Encoding: base64\n\n".$fileStr."\n\n";

    }

    return $attachmentPart;

    }

    }

    // send email

    function send(){

    $to=$this->recipient;

    $subject=$this->subject;

    $headers=$this->buildHeaders();

    $message=$this->buildTextPart().$this->buildHTMLPart().$this->buildAttachmentPart()."--MIME_BOUNDRY--\n";

    if(!mail($to,$subject,$message,$headers)){

    trigger_error('Error sendind email.',E_USER_ERROR);

    }

    }

    }


    Now the MIME mailer class defines and implements two additional methods, called “addHTML()” and “buildHTMLPart()” respectively. The first one allows you to aggregate HTML code to an existing email message, and the last one is tasked with assembling the corresponding HTML parts that will be added later to the whole multipart message.

    This assembling process is performed by the “send()” method of the class, so you shouldn’t have major trouble understanding how it works.

    So far, so good. At this stage you hopefully learned how to provide the previous “Mailer” class with the ability to send email messages in HTML format. This ability has to be added to the existing capacities, meaning the class is now much more powerful.

    However, there’s one thing left undone in this specific case. Yes, you guessed right! Naturally, you must want to see how the class works. Therefore, in the last section of this article, I’m going to build a final hands-on example, aimed at demonstrating the improved functionality of the MIME mailer class.

    All you have to do is click on the link that appears below and keep reading.



     
     
    >>> More PHP Articles          >>> More By Alejandro Gervasio
     

       

    PHP ARTICLES

    - Implementing Factory Methods in PHP 5
    - Merging a File Split for FTP Upload using PHP
    - Getting Data from Yahoo Site Explorer Inboun...
    - Method Chaining: Adding More Selecting Metho...
    - How to Split a File During an FTP Upload Usi...
    - Expanding a Custom CodeIgniter Library with ...
    - Using the Yahoo Site Explorer Inbound Links ...
    - Building a CodeIgniter Custom Library with M...
    - Building an E-mini Trading System Using PHP ...
    - Completing the MySQL Class with Method Chain...
    - Building Dynamic Queries with Chainable Meth...
    - PHP Encryption and Decryption Methods
    - Building a MySQL Abstraction Class with Meth...
    - Completing a Sample String Processor with Me...
    - Mastering WHILE Loops for PHP and MySQL





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 3 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek