PHP
  Home arrow PHP arrow Page 3 - Handling Attachments in MIME Email wit...
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Sun Developer Network 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Mobile Linux 
App Generation ROI 
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? 
PHP

Handling Attachments in MIME Email with PHP
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 2
    2008-07-16

    Table of Contents:
  • Handling Attachments in MIME Email with PHP
  • Developing a simple MIME mailer class with PHP 4
  • Working with email attachments
  • Seeing the Mailer class in action

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb 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


    Handling Attachments in MIME Email with PHP - Working with email attachments


    (Page 3 of 4 )

    In the previous section, I demonstrated that the “Mailer” class in its current state is limited in terms of functionality, since it’s only capable of sending MIME-compliant email messages in plain text. However, it’s perfectly possible to extend the existing capacity of the mentioned class in order to provide it with the ability to handle attachments in a straightforward way.

    Considering this, I developed an improved version of the previous MIME mailer class that implements two additional methods that are useful for working with several types of attachments.

    Here’s how this class looks now:


    class Mailer{

    var $sender;

    var $recipient;

    var $subject;

    var $headers=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';

    }

    // 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 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;

    }

    }

    // 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";

    }

    // add new MIME header

    function addHeader($name,$value){

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

    }

    // 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){

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

    switch(strtolower($nameArray[count($nameArray)-1])){

    case 'jpg':

    $mimeType='image/jpeg';

    break;

    case 'jpeg':

    $mimeType='image/jpeg';

    break;

    case 'gif':

    $mimeType='image/gif';

    break;

    case 'txt':

    $mimeType='text/plain';

    break;

    case 'pdf':

    $mimeType='application/pdf';

    break;

    case 'csv';

    $mimeType='text/csv';

    break;

    case 'html':

    $mimeType='text/html';

    break;

    case 'htm':

    $mimeType='text/html';

    break;

    case 'xml':

    $mimeType='text/xml';

    break;

    }

    return $mimeType;

    }

    // send email

    function send(){

    $to=$this->recipient;

    $subject=$this->subject;

    $headers=$this->buildHeaders();

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

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

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

    }

    }

    }


    After modifying the existing definition of the “Mailer” class, you’ll have to agree with me that it now looks much more useful. In this specific case, I added up a couple of brand new methods, called “addAttachment()” and “buildAttachmentPart()” respectively, which, when used in conjunction, enable the class to attach different types of files to an existing email message.

    You should also pay close attention to the private “getMimeType()” method, which implements the programming logic required to determine the correct MIME type of a specified attached file. For this case, the class only works with the most common MIME types, such as “image/jpg,” “image/gif,” “plain/text,” “application/pdf,” etc. Nevertheless, you can reconfigure this method and add support for other MIME types that might also be useful to you.

    It’s also worthwhile to point out that there are many PHP functions available on the web that can be used to get the MIME type of a given file. On this occasion, I utilized a method developed by Chris Root in his article (http://www.devshed.com/c/a/PHP/A-MIME-Mailer-Class/), but you can pick up the one that best suits your needs.

    Now, back to the mailer class. Notice how the “send()” method now calls all the required private methods mentioned above in order to correctly assemble the pertaining MIME-compliant message, including all the files that could have been attached previously.

    So far, so good, right? At this stage, the initial functionality of this MIME mailer class has been expanded considerably, since it’s now capable of sending plain text messages that also incorporate attachments. However, if you’re anything like me, then you may want to see a concrete example where this class is put to work.

    Considering this possibility, in the last section of this tutorial I’m going to set up a functional example for you, so you can clearly appreciate the improved functionality of this MIME mailer class.

    Click on the link below and keep reading.

    More PHP Articles
    More By Alejandro Gervasio


       · This second tutorial of the series shows how to improve the initial structure of the...
     

       

    PHP ARTICLES

    - Working With Different Namespaces in PHP 5
    - User Management Explained: Overview
    - Using Namespaces in PHP 5
    - Database Security: Guarding Against SQL Inje...
    - Building a Modular Exception Class in PHP 5
    - Database and Password Security for Web Appli...
    - Handling MySQL Data Set Failures in PHP 5
    - Building Site Registration for Web Applicati...
    - Intercepting Customized Exceptions in PHP 5
    - Securing Your Web Application Against Attacks
    - Sub Classing Exceptions in PHP 5
    - Authentication for Web Application Security
    - Building a Content Management System with Co...
    - Filters and Login Systems for Web Applicatio...
    - Working with the Email Class in Code Igniter





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 4 hosted by Hostway
    Stay green...Green IT