PHP Classes

PHP MIME Email Message Parser: Decode MIME e-mail messages

Recommend this page to a friend!
  Info   Example   Screenshots   View files Files   Install with Composer Install with Composer   Download Download   Reputation   Support forum   Blog    
Last Updated Ratings Unique User Downloads Download Rankings
2024-11-03 (Yesterday) RSS 2.0 feedStarStarStarStar 79%Total: 30,648 This week: 6All time: 16 This week: 9Up
Version License PHP version Categories
mimeparser 1.89BSD License4.3Email, Text processing, Parsers
Description 

Author

This class can be used to parse and decode MIME e-mail messages.

It supports decoding single RFC 2822 MIME messages or archives that aggregate multiple messages in the mbox format.

The decoded message data is returned as an array that describes one or more messages found in a message file or data string.

The bodies of multipart messages can be decoded into distinct sub-messages.

The message body data can decoded and saved to separate files, so the class can handle messages larger than the available memory.

The parser can tolerate some syntax errors in malformed messages that are not compliant with RFC 2822.

An auxiliar class is provided to parse and extract e-mail address lists from message headers.

Picture of Manuel Lemos
  Performance   Level  
Name: Manuel Lemos <contact>
Classes: 45 packages by
Country: Portugal Portugal

Recommendations

SMS Messages to Email
Get SMS Messages

Recommendation for a PHP class to save email attachment
Read email and save attachment

What is the best PHP display email with images class?
IMAP function to find an inline email images

saving email attachment into local folder
I want to save all attachment from all email into local folder

What is the best PHP imap email body decode class?
Need to encode =0D=0A=0D=0A such text to tab or new line

Retrieve email from gmail with imap
Retrieve mail and decode correctly

How to extract HTML from message file?
Read HTML from message in Outlook

What is the best PHP mail mime decode class?
Parse email messages

Example

<?php
/*
 * test_message_decoder.php
 *
 * @(#) $Id: test_message_decoder.php,v 1.14 2021/02/22 16:02:28 mlemos Exp $
 *
 */

   
require_once('rfc822_addresses.php');
    require_once(
'mime_parser.php');

   
$message_file=((IsSet($_SERVER['argv']) && count($_SERVER['argv'])>1) ? $_SERVER['argv'][1] : 'test/sample/message.eml');
   
$mime=new mime_parser_class;
   
   
/*
     * Set to 0 for parsing a single message file
     * Set to 1 for parsing multiple messages in a single file in the mbox format
     */
   
$mime->mbox = 0;
   
   
/*
     * Set to 0 for not decoding the message bodies
     */
   
$mime->decode_bodies = 1;

   
/*
     * Set to 0 to make syntax errors make the decoding fail
     */
   
$mime->ignore_syntax_errors = 1;

   
/*
     * Set to 0 to avoid keeping track of the lines of the message data
     */
   
$mime->track_lines = 1;

   
/*
     * Set to 1 to make message parts be saved with original file names
     * when the SaveBody parameter is used.
     */
   
$mime->use_part_file_names = 0;

   
/*
     * Set this variable with entries that define MIME types not yet
     * recognized by the Analyze class function.
     */
   
$mime->custom_mime_types = array(
       
'application/vnd.openxmlformats-officedocument.wordprocessingml.document'=>array(
           
'Type' => 'ms-word',
           
'Description' => 'Word processing document in Microsoft Office OpenXML format'
       
)
    );

   
$parameters=array(
       
'File'=>$message_file,
       
       
/* Read a message from a string instead of a file */
        /* 'Data'=>'My message data string', */

        /* Save the message body parts to a directory */
        /* 'SaveBody'=>'/tmp', */

        /* Do not retrieve or save message body parts */
       
'SkipBody'=>1,
    );

/*
 * The following lines are for testing purposes.
 * Remove these lines when adapting this example to real applications.
 */
   
if(defined('__TEST'))
    {
        if(IsSet(
$__test_options['parameters']))
           
$parameters=$__test_options['parameters'];
        if(IsSet(
$__test_options['mbox']))
           
$mime->mbox=$__test_options['mbox'];
        if(IsSet(
$__test_options['decode_bodies']))
           
$mime->decode_bodies=$__test_options['decode_bodies'];
        if(IsSet(
$__test_options['use_part_file_names']))
           
$mime->use_part_file_names=$__test_options['use_part_file_names'];
        if(IsSet(
$__test_options['use_part_file_names']))
           
$mime->use_part_file_names=$__test_options['use_part_file_names'];
        if(IsSet(
$__test_options['message_buffer_length']))
           
$mime->message_buffer_length = $__test_options['message_buffer_length'];
    }

    if(!
$mime->Decode($parameters, $decoded))
    {
        echo
'MIME message decoding error: '.$mime->error.' at position '.$mime->error_position;
        if(
$mime->track_lines
       
&& $mime->GetPositionLine($mime->error_position, $line, $column))
            echo
' line '.$line.' column '.$column;
        echo
"\n";
    }
    else
    {
        echo
'MIME message decoding successful.'."\n";
        echo (
count($decoded)==1 ? '1 message was found.' : count($decoded).' messages were found.'),"\n";
        for(
$message = 0; $message < count($decoded); $message++)
        {
            echo
'Message ',($message+1),':',"\n";
           
var_dump($decoded[$message]);
            if(
$mime->decode_bodies)
            {
                if(
$mime->Analyze($decoded[$message], $results))
                   
var_dump($results);
                else
                    echo
'MIME message analyse error: '.$mime->error."\n";
            }
        }
        for(
$warning = 0, Reset($mime->warnings); $warning < count($mime->warnings); Next($mime->warnings), $warning++)
        {
           
$w = Key($mime->warnings);
            echo
'Warning: ', $mime->warnings[$w], ' at position ', $w;
            if(
$mime->track_lines
           
&& $mime->GetPositionLine($w, $line, $column))
                echo
' line '.$line.' column '.$column;
            echo
"\n";
        }
    }
?>


Screenshots (1)  
  • mimeparser.gif
  Files folder image Files (27)  
File Role Description
Files folder imagetest (1 file, 3 directories)
Accessible without login Plain text file test_message_decoder.php Example Example script to demonstrate how to decode a e-mail message
Accessible without login Plain text file test_parse_addresses.php Example Example to demonstrate how to parse e-mail address lists
Plain text file mime_parser.php Class MIME message parser and decoder class
Accessible without login HTML file mime_parser_class.html Doc. Class documentation
Plain text file rfc822_addresses.php Class Class to parse e-mail address lists from message headers
Accessible without login HTML file rfc822_addresses_class.html Doc. Documentation of the RFC 822 address parser class

  Files folder image Files (27)  /  test  
File Role Description
Files folder imageexpect (9 files)
Files folder imagesample (9 files)
Files folder imagegenerated (1 file)
  Accessible without login Plain text file test.php Test Unit test script to verify different message parsing cases

  Files folder image Files (27)  /  test  /  expect  
File Role Description
  Accessible without login Plain text file longheader.txt Doc. Long header test expected results
  Accessible without login Plain text file longmessage.txt Doc. longmessage test expected results
  Accessible without login Plain text file quotedfilename.txt Doc. Unit test expected output
  Accessible without login Plain text file mbox.txt Data Expected output of the mbox test
  Accessible without login Plain text file missingheaderseparator.txt Data Expected output of the missingheaderseparator test
  Accessible without login Plain text file mixedlinebreaks.txt Data Mixed line breaks test expected results
  Accessible without login Plain text file normal.txt Data Expected output of the decoder example script when parsing the message.eml file
  Accessible without login Plain text file parse_addresses.txt Data Expected output of the e-mail address parser example script
  Accessible without login Plain text file q-encoding.txt Data Q-encoding test expected results

  Files folder image Files (27)  /  test  /  sample  
File Role Description
  Accessible without login Plain text file longheader.eml Data Long header test sample message
  Accessible without login Plain text file longmessage.eml Data Sample long message for testing
  Accessible without login Plain text file quotedfilename.eml Data Sample message with file name with quote
  Accessible without login Plain text file mbox.eml Data Sample mbox message file
  Accessible without login Plain text file message.eml Data Sample MIME message file used by the example script
  Accessible without login Plain text file missingheaderseparator.eml Data Sample MIME message file used by the example script
  Accessible without login Plain text file mixedlinebreaks.eml Data Mixed line breaks test sample message
  Accessible without login Plain text file noendbreak.eml Data Sample MIME message file used by the example script
  Accessible without login Plain text file q-encoding.eml Data Q-encoding test sample message

  Files folder image Files (27)  /  test  /  generated  
File Role Description
  Accessible without login Plain text file .cvsignore Data Dummy file to force the distribution of this directory

The PHP Classes site has supported package installation using the Composer tool since 2013, as you may verify by reading this instructions page.
Install with Composer Install with Composer
 Version Control Reuses Unique User Downloads Download Rankings  
 88%2
Total:30,648
This week:6
All time:16
This week:9Up
User Ratings User Comments (12)
 All time
Utility:94%StarStarStarStarStar
Consistency:91%StarStarStarStarStar
Documentation:78%StarStarStarStar
Examples:78%StarStarStarStar
Tests:77%StarStarStarStar
Videos:-
Overall:79%StarStarStarStar
Rank:24
 
We are using this library in the SaltOS project and works nic...
3 years ago (Josep Sanz Campderrós)
85%StarStarStarStarStar
This was the MIME Email Message Parser I needed.
7 years ago (Susan Bassein)
90%StarStarStarStarStar
Thank you!
8 years ago (Michael)
80%StarStarStarStarStar
Awesome! Non verbose, easy to understand without reading any ...
8 years ago (Nadir)
85%StarStarStarStarStar
Great little class, extremely useful and it made my work very...
8 years ago (Chris King)
67%StarStarStarStar
out of several classes, this is the only one that works for m...
10 years ago (scott backup)
90%StarStarStarStarStar
worked well for us in 2 usages
13 years ago (Tushar)
80%StarStarStarStarStar
Perfect class.
14 years ago (ilinsky)
90%StarStarStarStarStar
Not a simple class.
16 years ago (Thales Jacobi)
60%StarStarStarStar
Perfect.
15 years ago (Daniel Tlach)
90%StarStarStarStarStar
Only use for decode body and attachment, but working very weel !
16 years ago (seb)
87%StarStarStarStarStar
This was exactly what I needed.
16 years ago (Ilan Berkner)
82%StarStarStarStarStar