Sending MIME Email with PHP

One of the most common tasks that a PHP programmer has to tackle is the development of applications that send MIME email in one form or another. In simple terms, MIME email consists of an extension of traditional email technology and comes in handy for sending email messages in fancy HTML and handling file attachments in a wide variety of formats. This article is the first part of a five-part series.

While using MIME email with PHP is a pretty fun process, the bad news is that it can be quite challenging to implement, particularly if you’re not very familiar with its most complex facets. There’s also the possibility that you often find yourself writing the same annoying code over and over again, especially when you have to construct MIME email modules within your applications.

In either case, one thing is certain: creating MIME email-related scripts with PHP is one of those things that you’ll only want to do once in your lifetime. Suppose you’re sick of writing code used to send MIME email to your customers and wish to find a more practical solution to this task. Well, you could pick up one of the numerous third-party classes that are available on the web, or develop your own fine-tuned MIME email class that can be reused many times in the future.

If you have any interest in the last option, then you’ll find this article series pretty useful. In the different tutorials that comprise it, I’ll teach you how to build a modular MIME mailer class with PHP 5. It will be equipped with a bunch of intuitive methods that are useful for handling the most common tasks associated with sending MIME email.

In this first part of the series, I’ll walk you through creating the bare bones structure of the mailer class, and I’ll be progressively adding more to it in upcoming articles.

Now, let’s move forward and learn how to build a reusable MIME mailer class with PHP. Here we go!

{mospagebreak title=Building a MIME mailer class}

Before I get my hands dirty by coding this extensible MIME mailer class with PHP, I’d like to explain the functionality that I plan to implement behind its API. The class will be comprised of a few straightforward methods that will be useful for sending MIME-compliant email messages. It will also incorporate the capacity to handle simple attachments.

Once the class has been completed, you’ll be able to incorporate additional methods into it, according to your personal requirements.

Having explained how this MIME mailer class will work, I’ll start by defining its principal structure and implementing its constructor. Here’s the first incarnation of the class in question:


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.’);

}

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

// code to send text/plain messages goes here

}

// create message MIME headers

function buildHeaders(){

// code to build MIME headers goes here

}

// add new MIME header

function addHeader($name,$value){

// code to add MIME headers goes here

}

// send email

function send(){

// code to send MIME email goes here

}

}


As you can see, the structure of the above “Mailer” class is quite simple to grasp and its methods are extremely intuitive. In this first step, I only implemented the corresponding constructor, but in the upcoming sections, I’ll be defining the others also.

For now, pay close attention to the constructor. It accepts a few basic email-related parameters, such as the sender, the recipient, the message’s subject, and finally, the text of the message itself.

The method performs a basic validation on these input arguments, and if they’re considered valid, they are designated class properties. The constructor finishes its execution by defining some default MIME headers, which will be added later on when actually sending the MIME-based email message.

The rest of the methods defined by the “Mailer” class speak for themselves, since they’ve been named according to the task they will perform. However, they haven’t been implemented concretely yet. In the upcoming section of this tutorial, I’ll be doing just that. This will complete the definition of this MIME mailer class.

To see how the remaining methods of the class will be implemented, please click on the link that appears below and keep reading.

{mospagebreak title=Completing the definition of the Mailer class}

As you saw in the previous section, the only method of the “Mailer” class that was concretely implemented was its corresponding constructor. However, I’ll show you the implementations of the other methods of this mailer class, so that you can understand these methods more easily.

Now, pay attention to the following code sample, which completes the definition of the “Mailer” class: Here it is:


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;

}

}


At this moment, and after studying the recently-implemented methods of the above mailer class, you’ll have to agree with me that things are definitely more interesting! As you can see, the class now has been provided with the capacity to incorporate any number of additional MIME headers via the “addHeader()” method to a particular email message. The “buildHeaders()” and “send()” methods have been concretely defined, turning the mailer class into a completely functional piece of code.

You should also notice how the respective header and body parts of the MIME-based message are internally assembled by the “send()” method, before sending the message in question to the specified recipient. For this specific case, I created a basic MIME boundary to delimit the different parts of the message, but you can use a different one as long as it fits the specifications of the MIME extension. Simple and understandable, isn’t it?

Now everything looks good, since you hopefully learned how to build an expansible mailer class with PHP 4, which, for the moment, permits you to send MIME-compliant text messages with minor efforts.

However, I’m pretty sure that you’re anxious to see how the previous “Mailer” class can be used in the context of a hands-on example. Therefore, in the last section of this tutorial, I’ll build a short script that will demonstrate the functionality of the class.

To see how this practical example will be developed, please read the next few lines. I’ll be there waiting for you.

{mospagebreak title=Sending MIME-compliant email messages}

I will now set up a simple hands-on example that illustrates how the “Mailer” class can be used to send MIME email messages. Thus, below I included the complete definition of the class, along with a short script that will send a trivial message by using the class in question.

Here’s the corresponding code sample:


// include MIME mailer class


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;

}

}


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

$mailer=&new Mailer(‘alejandro@mydomain.com,’mybuddy@yourdomain.com’,’Testing mailer class’,’Hello buddy. How are you?’);

// send MIME email message

if($mailer->send()){

echo ‘Message was sent successfully.';

}


As you can see, sending MIME-compliant messages with this basic mailer class is a no-brainer process that can be tackled with minor hassles. In the above example, I first created a new instance of the class with the appropriate message’s arguments (i.e. the respective sender, recipient, subject, and text) and then sent the message via the “send()” method. It’s that simple.

Of course, there’s plenty of room to improve the functionality of the previous mailer class, but all of these possible modifications will be implemented throughout the course of the upcoming tutorials in the series. In the meantime, play around with the class and use it to familiarize yourself with sending MIME-compliant email messages with PHP.

Final thoughts

In this first chapter of the series, I walked you through building a basic mailer class that has the capacity to send text-based messages that fit the specification of MIME email. As you saw earlier, the class is very simple to code and use. And due to its flexible structure, it can be extended with minor efforts.

In the next article, I’ll be teaching you how to improve the functionality of the class in order to provide it with the capacity to send different types of attachments. Don’t miss the next article!

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

antalya escort bayan antalya escort bayan Antalya escort diyarbakir escort