Jump to content

Decode an email


daj

Recommended Posts

Hi all,

 

Firstly, i apologise for the long post, but I wanted to give you an overall feel for what I am trying to achieve.  The question is at the end!!

 

My Plan is to take emails and stores these in MySql for late retrieval and display.  The email could be plain text or html and may contain any number of file attachments (or none)!

 

I have no problem getting the email or saving it into SQL, but my problem is decoding it and extracting any attachments.  Ultimately in the SQL database I will have all the usual parts (To, From, etc) plus the body of the email (plain and/or html) and a list of attachments.

 

Everything I have read so far involves getting the emails from an iMap mail server however my emails are all contained in individual text files.

 

My question is really to enquiry what classes/scripts are available to help me decode the text file (email) and gather all the information I need.

 

Any help or pointers much appreciated

 

Thanks

 

David

 

Link to comment
Share on other sites

  • 1 month later...

Hi Daj,

 

I'm currently writing a similar app for a client, and have gotten a certain distance - I can save single attachments locally as well as the email details, but if there is more than one attachment, I run into problems.

 

I'd be interested in working with you to see if you've managed to attain what you need to do, maybe my code thus far might help you out also..?

 

Drop me a PM and I'll send you my email address.

 

All the best,

WoolyG

Link to comment
Share on other sites

Here is code I created. Hope it gives you enough information to create one that does what you need:

#!/usr/bin/php -q
<?php
/*
Parse Mail Script created by Jerry S Hamaker
Pooled together from multiple sources
Created on April 21, 2010

For each email that comes in, this script creates a private gallery, and places all parts of the email into files with details being placed into the database under the new private gallery. It also generates a medium size image (for very large images) and thumbnail for each image that comes in.
*/

require( "../admin/dbconnect.php" ); // This file connects to the MySQL server

$subject = "None";
$from = "";
$galleryid = 0;

//parse the email
function getbody( $message ) {
  global $subject, $from, $galleryid;
  $header = "";
  $type = "text/plain";
  $encoding = "none";
  $boundary = "";
  $body = "";
  $filename = "NoName";
  $lines = explode("\n", $message);
  $getheader = TRUE;
  foreach( $lines as $value ) {
    if( $getheader ) {
      $header .= $value . "\n";
      if (preg_match("/^Subject: (.*)/", $value, $matches)) {
        $subject = $matches[1];
      }
      if (preg_match("/^From: (.*)/", $value, $matches)) {
        $from = $matches[1];
      }
      if (preg_match("/^Content-Type: ([^;]+);/", $value, $matches)) {
        $type = $matches[1];
      }
      if (preg_match('/boundary="([^"]+)"/', $value, $matches)) {
        $boundary = $matches[1];
      }
      if (preg_match("/^Content-Transfer-Encoding: (.*)/", $value, $matches)) {
        $encoding = $matches[1];
      }
      if (preg_match('/filename="([^"]+)"/', $value, $matches)) {
        $filename = $matches[1];
      }
    }
    else {
      $body .= $value . "\n";
    }
    if (trim( $value )=="") {
      // empty line, header section has ended
      $getheader = FALSE;
    }
  }
  if ( $type == "multipart/mixed" || $type == "multipart/alternative" ) {
    getmultiparts( $body, $boundary );
  }
  else {
    if( $encoding == "base64" ) {
      $body = base64_decode( $body );
    }
    // store and process part
    $templocation = '../image/file_temp.tmp';
    if( $fh = fopen( $templocation, 'w' ) ) {
      fwrite( $fh, $body );
      fclose( $fh );
      $origname = $filename;
      $type1 = $type;
      $localname = $templocation;
      $checkimage = getimagesize( $localname );
      $imagewidth = ( isset( $checkimage[ 0 ] ) ? $checkimage[ 0 ] : 0 );
      $imageheight = ( isset( $checkimage[ 1 ] ) ? $checkimage[ 1 ] : 0 );
      $type2 = ( isset( $checkimage[ 'mime' ] ) ? $checkimage[ 'mime' ] : '' );
      $mimetype = ( $type1 == $type2 ? $type1 : ( $imagewidth == 0 || $imageheight == 0 ? $type1 : $type2 ) );
      $resizableimage = FALSE;
      if( $mimetype == "image/gif" || $mimetype == "image/jpeg" || $mimetype == "image/png" ) $resizableimage = TRUE;
        $query = "INSERT INTO images ( height, width, type, gallid,";
        $query .= " filename, imagename ) VALUES ( ";
        $query .= $imageheight . ", " . $imagewidth . ", \"" . mysql_real_escape_string( $mimetype ) . "\", ";
        $query .= $galleryid . ", \"" . mysql_real_escape_string( htmlize( $origname ) ) . "\", ";
        $query .= "\"" . mysql_real_escape_string( htmlize( $origname ) ) . "\" )";
        if( mysql_query( $query ) && $lastid = mysql_insert_id() ) {
          $filedestination = '../image/file_' . str_pad( $lastid, 5, '0', STR_PAD_LEFT ) . '.img';
          $thumbdestination = '../image/file_' . str_pad( $lastid, 5, '0', STR_PAD_LEFT ) . '.thm';
          $meddestination = '../image/file_' . str_pad( $lastid, 5, '0', STR_PAD_LEFT ) . '.med';
          if( rename( $localname, $filedestination ) ) {
            if( $resizableimage ) {
              $img_src = ( $mimetype == "image/gif" ? imagecreatefromgif( $filedestination ) : ( $mimetype == "image/png" ? imagecreatefrompng( $filedestination ) : imagecreatefromjpeg( $filedestination ) ) );
              if( $imagewidth > 600 ) {
                $medwidth = 600;
                $medheight = floor( $medwidth * $imageheight / $imagewidth );
                $img_dst = imagecreatetruecolor( $medwidth, $medheight );
                imagecopyresampled( $img_dst, $img_src, 0, 0, 0, 0, $medwidth, $medheight, $imagewidth, $imageheight );
                if( $mimetype == 'image/gif' ) {
                  imagegif( $img_dst, $meddestination );
                }
                elseif( $mimetype == 'image/png' ) {
                  imagepng( $img_dst, $meddestination );
                }
                else {
                  imagejpeg( $img_dst, $meddestination );
                }
                imagedestroy( $img_dst );
              }
              $thumbheight = ( $imageheight > 100 ? 100 : $imageheight );
              $thumbwidth = ( $imagewidth > 100 ? 100 : $imagewidth );
              if( $imageheight > $imagewidth ) {
                $thumbwidth = floor( $thumbheight * $imagewidth / $imageheight );
              }
              else {
                $thumbheight = floor( $thumbwidth * $imageheight / $imagewidth );
              }
              $img_dst = imagecreatetruecolor( $thumbwidth, $thumbheight );
              imagecopyresampled( $img_dst, $img_src, 0, 0, 0, 0, $thumbwidth, $thumbheight, $imagewidth, $imageheight );
              imagejpeg( $img_dst, $thumbdestination );
            }
            else {
              $defaultthumb = '../image/default.thm';
              if( file_exists( '../image/' . $mimetype . '_default.thm' ) ) {
                $defaultthumb = '../image/' . $mimetype . '_default.thm';
              }
              copy( $defaultthumb, $thumbdestination );
            }
          }
        }
      }
      // if( file_exists( $templocation ) ) unlink( $templocation );
  }
}

//parse multi-part
function getmultiparts( $message, $seperator ) {
  $lines = explode("\n", $message);
  $process = "";
  $firstsep = TRUE;
  foreach( $lines as $value ) {
    if( strpos( $value, $seperator ) === FALSE ) {
      $process .= $value . "\n";
    }
    else {
      if( $firstsep ) {
        $process = "";
        $firstsep = FALSE;
      }
      else {
        getbody( $process );
        $process = "";
      }
    }
  }
}

//get the email
$fd = fopen("php://stdin", "r");
$email = "";
while (!feof($fd)) {
    $email .= fread($fd, 1024);
}
fclose($fd);

$galleryname = date( 'Ymd His' ) . '-Emailed';
$query = 'INSERT INTO gallery ( gallname ) VALUES ( "' . mysql_real_escape_string( $galleryname ) . '" )';
$result = mysql_query( $query );
if( $result && $newgall = mysql_insert_id() ) {
$galleryid = $newgall;
getbody( $email );
$query = 'UPDATE gallery SET galldesc="' . mysql_real_escape_string( '--== ' . $subject . ' ==-- Uploaded By: ' . $from );
$query .= '" WHERE gallid=' . $galleryid;
mysql_query( $query );
}
?>

I know it's long. I hope it helps you with what you are trying to do. This file uses a function to parse the email, if it finds multi-part boundaries, it use another function to split up the parts, and each part is then passed to the parse function. Once the email has been parsed, it updates the gallery name to include the subject of the email and the email address it came from.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.