Sunday, 17 February 2013

Send a Pre-Formatted .EML File in PHP


I’m not going to go into any magical back-story about how the “.EML” text-file format for email works or how it’s a good choice in preparing an email template for PHP scripts. I’m just going to get straight to the point:

Easiest way to send an “.EML” file in PHP

$emailpath = 'email.eml'; 
$sendmail = sprintf("cat $emailpath | %s -oi -f %s -t", escapeshellcmd("/usr/sbin/sendmail"), escapeshellarg(; //Message that address if any errors that may occur 
@$mail = popen($sendmail, 'w'); 
$raw = pclose($mail);

Make sure your “email.eml” file contains all the email headers you may need, particularly:
  1. To:
  2. From:
  3. Subject:
I would strongly advice you review my use of “escapeshellcmd” and “escapeshellarg” to prepare the variables to be interpreted by the shell.

Parsing “.EML” files and sending them in PHP:

Since the “.EML” is a text based format, they provide versatility to serve as templates. In this example I supply email header data through pre-set variables. I later use regular expressions to change existing text in the .EML file (in this case [$FirstName] [$LastName] [$EmailAddress] and [$Greeting]) with their corresponding variable as supplied.

I choose to keep the file stream open rather than send the whole of the parsed content into a single command. No particular reason, just thought I should…

Here is the example:

    $sendmailpath = '/usr/sbin/sendmail'; 
    $emailpath = 'emailTemplate.eml'; 
    $messagecontent = file_get_contents($emailpath);
    //Variables for the email 
    $FirstName = "Alex"; 
    $LastName = "Casamassima"; 
    $EmailAddress = ""; 
    $Greeting = "Good day kind sir,"; 
    $parsed_message = preg_replace('/\[\$([01-9A-Za-z_]+)\]/e', "$$1", $messagecontent); 
    $sendmail = sprintf("%s -oi -f %s -t", escapeshellcmd($sendmailpath), escapeshellarg("")); 
    if(!@$mail = popen($sendmail, 'w')) { 
        throw new Exception("Couldn't open the sendmail program!"); 
    fputs($mail, $parsed_message); 
    $result = pclose($mail); 
    if($result != 0) { 
      throw new Exception("Couldn't send email!"); 

.EML files are useful as they offer great facility to provide MulitPart content, including text versions of an email and embedded attachments. As well, modifying them is as simple as opening them up in your text editor of choice.

Easiest way to make a beautiful .EML file

This may be a personal preference of mine. But, Creating a new draft in “Windows Live Mail” often suffices for me. The menu inside the email client allows you to “Save as file” that defaults to an “.EML” file.

Using a client such as “Windows Live Mail” or “Outlook” allows for quick and easy use of embedded pictures, fonts, colours, and special features.

Alternative resources on PHP and .EML:
  3. search for (EML file) on page


Page Hits