Handling Attachments in MIME Email with 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!

Sending plain text email with PHP is a pretty simple task that can be tackled with minor efforts thanks mostly to the easy learning curve of its popular “mail()” built-in function. You know, you code a simple script that sends email messages to a bunch of recipients. It feeds this function with the proper email headers and the text of the message and… voila! The script works like a charm, and best of all, it only took a few minutes to be developed.

However, things get slightly more complicated when it comes to sending email messages in HTML, or when it’s necessary to work with attachments, since these tasks require the use of MIME, which is the mail extension that permits you to send messages formatted in HTML, include inline files, and so forth.

The good news concerning the use of MIME email with PHP is that you can develop your own reusable functions in order to send messages in HTML and handle a huge variety of attachments. You can also take advantage of the object-oriented paradigm and create a highly modular MIME mailer class that does all of this hard work for you.

In either case, in this group of tutorials you’ll find useful material regarding the construction of an expansible PHP class that can be utilized to send MIME-compliant messages very easily and work with different types of attachments.

And speaking of sending MIME-compliant email messages, in the last article of this series I went through the development of a basic mailer class in PHP 4. It was capable of dispatching plain text messages to a specified recipient by way of an intuitive API. Indeed, the functionality of this class was pretty limited, since it wasn’t capable of working with HTML messages or attachments.

{mospagebreak title=Developing a simple MIME mailer class with PHP 4}

As I said in the beginning, I started this series of articles by explaining how to build a basic MIME mailer class with PHP 4. This was only capable of sending messages in plain text. So let me quickly remind you of the definition of this introductory class. It looked like this:


class Mailer{

var $sender;

var $recipient;

var $subject;

var $headers=array();

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

// validate incoming parameters

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

trigger_error(‘Invalid value for email sender.’,E_USER_ERROR);

}

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

trigger_error(‘Invalid value for email recipient.’,E_USER_ERROR);

}

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

trigger_error(‘Invalid length for email subject.’,E_USER_ERROR);

}

if(!$message){

trigger_error(‘Invalid value for email message.’,E_USER_ERROR);

}

$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_BOUNDRYnContent-Type: text/plain; charset=iso-8859-1nContent-Transfer-Encoding: quoted-printablennn".$this->message."nn";

}

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

}

// send email

function send(){

$to=$this->recipient;

$subject=$this->subject;

$headers=$this->buildHeaders();

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

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

trigger_error(‘Error sending email.’,E_USER_ERROR);

}

return true;

}

}


As shown above, the previous “Mailer” class comes in handy for sending MIME-complaint messages in just plain text format, meaning that its functionality may be limited in certain situations. Despite this issue, below coded a short, hands-on example that shows how to use it in a simple way:


// create a new instance of the ‘Mailer’ class

$mailer=&new Mailer(‘alejandro@mydomain.com,’mybuddy@yourdomain.com’,’Testing mailer class’,’Hello buddy. Is everything doing fine over there?’);

// send MIME email message

if($mailer->send()){

echo ‘Message was sent successfully.';

}


That wasn’t rocket science. I have to admit that the mailer class in its current incarnation is pretty useless, particularly when used with PHP applications that require you to work with attachments. What comes next, though? Well, in accordance with the concepts that I deployed in the introduction, in the section to come I’m going to add a couple of additional methods to the pertaining “Mailer” class, so it can handle several types of attachments with relative ease.

To see how this will be done, please jump forward and read the next few lines. It’s only one click way.

{mospagebreak title=Working with email attachments}

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_BOUNDRYnContent-Type: text/plain; charset=iso-8859-1nContent-Transfer-Encoding: quoted-printablennn".$this->message."nn";

}

// 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_BOUNDRYnContent-Type: ".$this->getMimeType($attachment)."; name="".basename($attachment).""nContent-disposition: attachmentnContent-Transfer-Encoding: base64nn".$fileStr."nn";

}

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.

{mospagebreak title=Seeing the Mailer class in action}

I listed the complete definition of this improved MIME “Mailer” class below along with a short script that demonstrates how to use it to send a trivial message that incorporates a pair of attached files.

Here’s the corresponding code sample: 


// create a new instance of the ‘Mailer’ class

$mailer=&new Mailer(‘alejandro@mydomain.com,’mybuddy@yourdomain.com’,’Testing mailer class’,’Hello buddy. Is everything doing fine over there?’);

// add some attachments

$mailer->addAttachment(‘file1.gif’);

$mailer->addAttachment(‘file2.gif’);

// send MIME email

$mailer->send();


That’s all the source code that you need to get the “Mailer” class working as expected. For this particular case, I utilized the class to send a simple message in plain text along with a couple of attached GIF files. This should clearly show its considerable functionality.

As always, you’re free to use the code samples shown in this tutorial in case you want to use the previous “Mailer” class to improve your existing skills in sending MIME email with PHP.

Final thoughts

That’s all for the moment. In this second chapter of the series, I taught you how to extend the existing functionality of the previous MIME mailer class in order to provide it with the capacity to work with attachments.

In the next tutorial, I’m going to improve the business logic implemented by the class, particularly when it comes to determining the MIME type of an attached file. This will make it slightly more compact and efficient.

Now that you’ve been warned about the subject of the upcoming article, you won’t want to miss it!

[gp-comments width="770" linklove="off" ]

chat sex hikayeleri Ensest hikaye