Home arrow PHP arrow Page 3 - Handling Attachments in MIME Email with PHP

Working with email attachments - PHP

In this second tutorial of the series, I’m going to teach you how to improve the initial structure of the MIME mailer class developed in the first article by giving it the ability to work directly with attachments. Sounds fairly interesting, right? Then don’t waste any more time in preliminaries and begin reading this article now!

TABLE OF CONTENTS:
  1. Handling Attachments in MIME Email with PHP
  2. Developing a simple MIME mailer class with PHP 4
  3. Working with email attachments
  4. Seeing the Mailer class in action
By: Alejandro Gervasio
Rating: starstarstarstarstar / 3
July 16, 2008

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

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
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: