<p>I'm looking for good/working/simple to use PHP code for parsing raw email into parts.</p>
<p>I've written a couple of brute force solutions, but every time, one small change/header/space/something comes along and my whole parser fails and the project falls apart.</p>
<p>And before I get pointed at PEAR/PECL, I need actual code. My host has some screwy config or something, I can never seem to get the .so's to build right. If I do get the .so made, some difference in path/environment/php.ini doesn't always make it available (apache vs cron vs CLI).</p>
<p>Oh, and one last thing, I'm parsing the raw email text, NOT POP3, and NOT IMAP. It's being piped into the PHP script via a .qmail email redirect.</p>
<p>I'm not expecting SOF to write it for me, I'm looking for some tips/starting points on doing it &quot;right&quot;. This is one of those &quot;wheel&quot; problems that I know has already been solved.</p>

[{'answer_id': 12965, 'author': 'jj33', 'author_id': 430, 'author_profile': 'https://Stackoverflow.com/users/430', 'pm_score': 6, 'selected': True, 'text': '<p>What are you hoping to end up with at the end?  The body, the subject, the sender, an attachment?  You should spend some time with <a href="http://www.faqs.org/rfcs/rfc2822.html" rel="noreferrer">RFC2822</a> to understand the format of the mail, but here\'s the simplest rules for well formed email:</p>\n\n<pre><code>HEADERS\\n\n\\n\nBODY\n</code></pre>\n\n<p>That is, the first blank line (double newline) is the separator between the HEADERS and the BODY.  A HEADER looks like this:</p>\n\n<pre><code>HSTRING:HTEXT\n</code></pre>\n\n<p>HSTRING always starts at the beginning of a line and doesn\'t contain any white space or colons.  HTEXT can contain a wide variety of text, including newlines as long as the newline char is followed by whitespace.</p>\n\n<p>The "BODY" is really just any data that follows the first double newline.  (There are different rules if you are transmitting mail via SMTP, but processing it over a pipe you don\'t have to worry about that).</p>\n\n<p>So, in really simple, circa-1982 <a href="http://www.faqs.org/rfcs/rfc822.html" rel="noreferrer">RFC822</a> terms, an email looks like this:</p>\n\n<pre><code>HEADER: HEADER TEXT\nHEADER: MORE HEADER TEXT\n  INCLUDING A LINE CONTINUATION\nHEADER: LAST HEADER\n\nTHIS IS ANY\nARBITRARY DATA\n(FOR THE MOST PART)\n</code></pre>\n\n<p>Most modern email is more complex than that though.  Headers can be encoded for charsets or <a href="http://www.faqs.org/rfcs/rfc2047.html" rel="noreferrer">RFC2047</a> mime words, or a ton of other stuff I\'m not thinking of right now.  The bodies are really hard to roll your own code for these days to if you want them to be meaningful.  Almost all email that\'s generated by an MUA will be <a href="http://www.faqs.org/rfcs/rfc2045.html" rel="noreferrer">MIME</a> encoded.  That might be uuencoded text, it might be html, it might be a uuencoded excel spreadsheet.</p>\n\n<p>I hope this helps provide a framework for understanding some of the very elemental buckets of email.  If you provide more background on what you are trying to do with the data I (or someone else) might be able to provide better direction.</p>\n'}, {'answer_id': 13001, 'author': 'Uberfuzzy', 'author_id': 314, 'author_profile': 'https://Stackoverflow.com/users/314', 'pm_score': 0, 'selected': False, 'text': "<p>yeah, ive been able to write a basic parser, based off that rfc and some other basic tutorials. but its the multipart mime nested boundaries that keep messing me up.</p>\n\n<p>i found out that MMS (not SMS) messages sent from my phone are just standard emails, so i have a system that reads the incoming email, checks the from (to only allow from my phone), and uses the body part to run different commands on my server. its sort of like a remote control by email.</p>\n\n<p>because the system is designed to send pictures, its got a bunch of differently encoded parts. a mms.smil.txt part, a text/plain (which is useless, just says 'this is a html message'), a application/smil part (which the part that phones would pic up on), a text/html part with a advertisement for my carrier, then my message, but all wrapped in html, then finally a textfile attachment with my plain message (which is the part i use) (if i shove an image as an attachment in the message, its put at attachment 1, base64 encoded, then my text portion is attached as attachment 2)</p>\n\n<p>i had it working with the exact mail format from my carrier, but when i ran a message from someone elses phone through it, it failed in a whole bunch of miserable ways.</p>\n\n<p>i have other projects i'd like to extend this phone->mail->parse->command system to, but i need to have a stable/solid/generic parser to get the different parts out of the mail to use it.</p>\n\n<p>my end goal would be to have a function that i could feed the raw piped mail into, and get back a big array with associative sub-arrays of headers var:val pairs, and one for the body text as a whole string</p>\n\n<p>the more and more i search on this, the more i find the same thing: giant overdeveloped mail handling packages that do everything under the sun thats related to mails, or useless (to me, in this project) tutorials.</p>\n\n<p>i think i'm going to have to bite the bullet and just carefully write something my self.</p>\n"}, {'answer_id': 13195, 'author': 'jj33', 'author_id': 430, 'author_profile': 'https://Stackoverflow.com/users/430', 'pm_score': 1, 'selected': False, 'text': '<p>You\'re probably not going to have much fun writing your own MIME parser.  The reason you are finding "overdeveloped mail handling packages" is because MIME is a really complex set of rules/formats/encodings.  MIME parts can be recursive, which is part of the fun.  I think your best bet is to write the best MIME handler you can, parse a message, throw away everything that\'s not text/plain or text/html, and then force the command in the incoming string to be prefixed with COMMAND: or something similar so that you can find it in the muck.  If you start with rules like that you have a decent chance of handling new providers, but you should be ready to tweak if a new provider comes along (or heck, if your current provider chooses to change their messaging architecture).</p>\n'}, {'answer_id': 13270, 'author': 'Polsonby', 'author_id': 137, 'author_profile': 'https://Stackoverflow.com/users/137', 'pm_score': 1, 'selected': False, 'text': '<p>I\'m not sure if this will be of help to you - hope so - but it will surely help others interested in finding out more about email. <a href="http://marcus.bointon.com/" rel="nofollow noreferrer">Marcus Bointon</a> did one of the best presentations entitled "Mail() and life after Mail()" at the PHP London conference in March this year and the <a href="http://www.phpconference.co.uk/media/docs/marcus_bointon_mail_presentation.pdf" rel="nofollow noreferrer">slides</a> and <a href="http://www.phpconference.co.uk/media/audio/mail_and_life_beyond_mail_marcus_bointon.mp3" rel="nofollow noreferrer">MP3</a> are online. He speaks with some authority, having worked extensively with email and PHP at a deep level.</p>\n\n<p>My perception is that you are in for a world of pain trying to write a truly generic parser.</p>\n\n<p>EDIT - The files seem to have been removed on the PHP London site; found the slides on Marcus\' <a href="http://marcus.bointon.com/archives/53-PHPLondon.html" rel="nofollow noreferrer">own site</a>: <a href="http://marcus.bointon.com/uploads/MarcusBointonMailpresentation.pdf" rel="nofollow noreferrer">Part 1</a> <a href="http://marcus.bointon.com/uploads/MarcusBointonLifeaftermailpresentation.pdf" rel="nofollow noreferrer">Part 2</a> Couldn\'t see the MP3 anywhere though</p>\n'}, {'answer_id': 4106876, 'author': 'zuups', 'author_id': 338756, 'author_profile': 'https://Stackoverflow.com/users/338756', 'pm_score': 2, 'selected': False, 'text': '<p>There are Mailparse Functions you could try: <a href="http://php.net/manual/en/book.mailparse.php" rel="nofollow">http://php.net/manual/en/book.mailparse.php</a>, not in default php conf, however.</p>\n'}, {'answer_id': 4234946, 'author': 'astateful', 'author_id': 514705, 'author_profile': 'https://Stackoverflow.com/users/514705', 'pm_score': 1, 'selected': False, 'text': "<p>Parsing email in PHP isn't an impossible task. What I mean is, you don't need a team of engineers to do it; it is attainable as an individual. Really the hardest part I found was creating the FSM for parsing an IMAP BODYSTRUCTURE result. Nowhere on the Internet had I seen this so I wrote my own. My routine basically creates an array of nested arrays from the command output, and the depth one is at in the array roughly corresponds to the part number(s) needed to perform the lookups. So it handles the nested MIME structures quite gracefully.</p>\n\n<p>The problem is that PHP's default imap_* functions don't provide much granularity...so I had to open a socket to the IMAP port and write the functions to send and retrieve the necessary information (IMAP FETCH 1 BODY.PEEK[1.2] for example), and that involves looking at the RFC documentation.</p>\n\n<p>The encoding of the data (quoted-printable, base64, 7bit, 8bit, etc.), length of the message, content-type, etc. is all provided to you; for attachments, text, html, etc. You may have to figure out the nuances of your mail server as well since not all fields are always implemented 100%.</p>\n\n<p>The gem is the FSM...if you have a background in Comp Sci it can be really really fun to make this (they key is that brackets are not a regular grammar ;)); otherwise it will be a struggle and/or result in ugly code, using traditional methods. Also you need some time!</p>\n\n<p>Hope this helps!</p>\n"}, {'answer_id': 5954640, 'author': 'Carter Cole', 'author_id': 180434, 'author_profile': 'https://Stackoverflow.com/users/180434', 'pm_score': 3, 'selected': False, 'text': '<p>I cobbled this together, some code isn\'t mine but I don\'t know where it came from... I later adopted the more robust "MimeMailParser" but this works fine, I pipe my default email to it using cPanel and it works great.</p>\n\n<pre><code>#!/usr/bin/php -q\n&lt;?php\n// Config\n$dbuser = \'emlusr\';\n$dbpass = \'pass\';\n$dbname = \'email\';\n$dbhost = \'localhost\';\n$notify= \'services@.com\'; // an email address required in case of errors\nfunction mailRead($iKlimit = "") \n    { \n        // Purpose: \n        //   Reads piped mail from STDIN \n        // \n        // Arguements: \n        //   $iKlimit (integer, optional): specifies after how many kilobytes reading of mail should stop \n        //   Defaults to 1024k if no value is specified \n        //     A value of -1 will cause reading to continue until the entire message has been read \n        // \n        // Return value: \n        //   A string containing the entire email, headers, body and all. \n\n        // Variable perparation         \n            // Set default limit of 1024k if no limit has been specified \n            if ($iKlimit == "") { \n                $iKlimit = 1024; \n            } \n\n            // Error strings \n            $sErrorSTDINFail = "Error - failed to read mail from STDIN!"; \n\n        // Attempt to connect to STDIN \n        $fp = fopen("php://stdin", "r"); \n\n        // Failed to connect to STDIN? (shouldn\'t really happen) \n        if (!$fp) { \n            echo $sErrorSTDINFail; \n            exit(); \n        } \n\n        // Create empty string for storing message \n        $sEmail = ""; \n\n        // Read message up until limit (if any) \n        if ($iKlimit == -1) { \n            while (!feof($fp)) { \n                $sEmail .= fread($fp, 1024); \n            }                     \n        } else { \n            while (!feof($fp) &amp;&amp; $i_limit &lt; $iKlimit) { \n                $sEmail .= fread($fp, 1024); \n                $i_limit++; \n            }         \n        } \n\n        // Close connection to STDIN \n        fclose($fp); \n\n        // Return message \n        return $sEmail; \n    }  \n$email = mailRead();\n\n// handle email\n$lines = explode("\\n", $email);\n\n// empty vars\n$from = "";\n$subject = "";\n$headers = "";\n$message = "";\n$splittingheaders = true;\nfor ($i=0; $i &lt; count($lines); $i++) {\n    if ($splittingheaders) {\n        // this is a header\n        $headers .= $lines[$i]."\\n";\n\n        // look out for special headers\n        if (preg_match("/^Subject: (.*)/", $lines[$i], $matches)) {\n            $subject = $matches[1];\n        }\n        if (preg_match("/^From: (.*)/", $lines[$i], $matches)) {\n            $from = $matches[1];\n        }\n        if (preg_match("/^To: (.*)/", $lines[$i], $matches)) {\n            $to = $matches[1];\n        }\n    } else {\n        // not a header, but message\n        $message .= $lines[$i]."\\n";\n    }\n\n    if (trim($lines[$i])=="") {\n        // empty line, header section has ended\n        $splittingheaders = false;\n    }\n}\n\nif ($conn = @mysql_connect($dbhost,$dbuser,$dbpass)) {\n  if(!@mysql_select_db($dbname,$conn))\n    mail($email,\'Email Logger Error\',"There was an error selecting the email logger database.\\n\\n".mysql_error());\n  $from    = mysql_real_escape_string($from);\n  $to    = mysql_real_escape_string($to);\n  $subject = mysql_real_escape_string($subject);\n  $headers = mysql_real_escape_string($headers);\n  $message = mysql_real_escape_string($message);\n  $email   = mysql_real_escape_string($email);\n  $result = @mysql_query("INSERT INTO email_log (`to`,`from`,`subject`,`headers`,`message`,`source`) VALUES(\'$to\',\'$from\',\'$subject\',\'$headers\',\'$message\',\'$email\')");\n  if (mysql_affected_rows() == 0)\n    mail($notify,\'Email Logger Error\',"There was an error inserting into the email logger database.\\n\\n".mysql_error());\n} else {\n  mail($notify,\'Email Logger Error\',"There was an error connecting the email logger database.\\n\\n".mysql_error());\n}\n?&gt;\n</code></pre>\n'}, {'answer_id': 6011540, 'author': 'Dan', 'author_id': 354742, 'author_profile': 'https://Stackoverflow.com/users/354742', 'pm_score': 4, 'selected': False, 'text': '<p>Try the Plancake PHP Email parser:\n<a href="https://github.com/plancake/official-library-php-email-parser" rel="noreferrer">https://github.com/plancake/official-library-php-email-parser</a></p>\n\n<p>I have used it for my projects. It works great, it is just one class and it is open source.</p>\n'}, {'answer_id': 8042425, 'author': 'postfuturist', 'author_id': 1892, 'author_profile': 'https://Stackoverflow.com/users/1892', 'pm_score': 2, 'selected': False, 'text': '<p>The Pear lib Mail_mimeDecode is written in plain PHP that you can see here: <a href="http://svn.php.net/viewvc/pear/packages/Mail_mimeDecode/trunk/Mail/mimeDecode.php?revision=337165&amp;view=markup" rel="nofollow noreferrer">Mail_mimeDecode source</a></p>\n'}, {'answer_id': 8057264, 'author': 'Petah', 'author_id': 268074, 'author_profile': 'https://Stackoverflow.com/users/268074', 'pm_score': 0, 'selected': False, 'text': '<p>This library work very well:</p>\n\n<p><a href="http://www.phpclasses.org/package/3169-PHP-Decode-MIME-e-mail-messages.html" rel="nofollow">http://www.phpclasses.org/package/3169-PHP-Decode-MIME-e-mail-messages.html</a></p>\n'}, {'answer_id': 31186504, 'author': 'Yaroslav', 'author_id': 3238670, 'author_profile': 'https://Stackoverflow.com/users/3238670', 'pm_score': 2, 'selected': False, 'text': '<p>There is a library for parsing raw email message into php array - <a href="http://flourishlib.com/api/fMailbox#parseMessage" rel="nofollow">http://flourishlib.com/api/fMailbox#parseMessage</a>. </p>\n\n<blockquote>\n  <p>The static method parseMessage() can be used to parse a full MIME\n  email message into the same format that fetchMessage() returns, minus\n  the uid key.</p>\n  \n  <p>$parsed_message =\n  fMailbox::parseMessage(file_get_contents(\'/path/to/email\'));</p>\n  \n  <p>Here is an example of a parsed message:</p>\n</blockquote>\n\n<pre><code>array(\n    \'received\' =&gt; \'28 Apr 2010 22:00:38 -0400\',\n    \'headers\'  =&gt; array(\n        \'received\' =&gt; array(\n            0 =&gt; \'(qmail 25838 invoked from network); 28 Apr 2010 22:00:38 -0400\',\n            1 =&gt; \'from example.com (HELO ?192.168.10.2?) (example) by example.com with (DHE-RSA-AES256-SHA encrypted) SMTP; 28 Apr 2010 22:00:38 -0400\'\n        ),\n        \'message-id\' =&gt; \'&lt;4BD8E815.1050209@flourishlib.com&gt;\',\n        \'date\' =&gt; \'Wed, 28 Apr 2010 21:59:49 -0400\',\n        \'from\' =&gt; array(\n            \'personal\' =&gt; \'Will Bond\',\n            \'mailbox\'  =&gt; \'tests\',\n            \'host\'     =&gt; \'flourishlib.com\'\n        ),\n        \'user-agent\'   =&gt; \'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.9) Gecko/20100317 Thunderbird/3.0.4\',\n        \'mime-version\' =&gt; \'1.0\',\n        \'to\' =&gt; array(\n            0 =&gt; array(\n                \'mailbox\' =&gt; \'tests\',\n                \'host\'    =&gt; \'flourishlib.com\'\n            )\n        ),\n        \'subject\' =&gt; \'This message is encrypted\'\n    ),\n    \'text\'      =&gt; \'This message is encrypted\',\n    \'decrypted\' =&gt; TRUE,\n    \'uid\'       =&gt; 15\n);\n</code></pre>\n'}, {'answer_id': 33311882, 'author': 'Jonathan Roy', 'author_id': 577950, 'author_profile': 'https://Stackoverflow.com/users/577950', 'pm_score': 0, 'selected': False, 'text': '<p>I met the same problem so I wrote the following class: Email_Parser. It takes in a raw email and turns it into a nice object.</p>\n\n<p>It requires PEAR Mail_mimeDecode but that should be easy to install via WHM or straight from command line.</p>\n\n<p>Get it here : <a href="https://github.com/optimumweb/php-email-reader-parser" rel="nofollow">https://github.com/optimumweb/php-email-reader-parser</a></p>\n'}, {'answer_id': 40764732, 'author': 'TomaszKane', 'author_id': 1829368, 'author_profile': 'https://Stackoverflow.com/users/1829368', 'pm_score': 2, 'selected': False, 'text': '<p>This <a href="https://github.com/zbateson/MailMimeParser" rel="nofollow noreferrer">https://github.com/zbateson/MailMimeParser</a> works for me, and don\'t need  mailparse extension.</p>\n\n<pre><code>&lt;?php\necho $message-&gt;getHeaderValue(\'from\');          // user@example.com\necho $message\n    -&gt;getHeader(\'from\')\n    -&gt;getPersonName();                          // Person Name\necho $message-&gt;getHeaderValue(\'subject\');       // The email\'s subject\n\necho $message-&gt;getTextContent();                // or getHtmlContent\n</code></pre>\n'}, {'answer_id': 47110625, 'author': 'Kazik', 'author_id': 8885286, 'author_profile': 'https://Stackoverflow.com/users/8885286', 'pm_score': 0, 'selected': False, 'text': '<p>Simple PhpMimeParser <a href="https://github.com/breakermind/PhpMimeParser" rel="nofollow noreferrer">https://github.com/breakermind/PhpMimeParser</a> Yuo can cut mime messages from files, string. Get files, html and inline images.</p>\n\n<pre><code>$str = file_get_contents(\'mime-mixed-related-alternative.eml\');\n\n// MimeParser\n$m = new PhpMimeParser($str);\n\n// Emails\nprint_r($m-&gt;mTo);\nprint_r($m-&gt;mFrom);\n\n// Message\necho $m-&gt;mSubject;\necho $m-&gt;mHtml;\necho $m-&gt;mText;\n\n// Attachments and inline images\nprint_r($m-&gt;mFiles);\nprint_r($m-&gt;mInlineList);\n</code></pre>\n'}, {'answer_id': 67923886, 'author': 'Adam Winter', 'author_id': 10664600, 'author_profile': 'https://Stackoverflow.com/users/10664600', 'pm_score': 0, 'selected': False, 'text': "<p>If you're trying to do this from a Docker container, use PEAR to install Mail and Mail_mimeDecode at build.</p>\n<pre><code>FROM php:7.4-apache\nWORKDIR /var/www/html\nEXPOSE 80\nWORKDIR /var/www\nRUN chown -R www-data html\nRUN docker-php-ext-install mysqli\nRUN pear install --alldeps mail\nRUN pear install Mail_mimeDecode\n</code></pre>\n<p>Then in your PHP code, something like this:</p>\n<pre><code>&lt;?php\n\nrequire_once &quot;/usr/local/lib/php/Mail.php&quot;;\nrequire_once &quot;/usr/local/lib/php/Mail/mimeDecode.php&quot;;\n\n$mailfiles = ['/var/www/mail/mailFile1','/var/www/mail/mailFile2'];\n\nforeach($mailfiles as $filename){\n    $theFile = fopen($filename, &quot;r&quot;) or die(&quot;Unable to open file!&quot;);\n    $rawEmail = fread($theFile, filesize($filename));\n    fclose($theFile);\n\n    $args = [];\n    $args['include_bodies'] = true;\n    $args['decode_bodies'] = FALSE;\n    $args['decode_headers'] = FALSE;\n    $objMail = new Mail_mimeDecode($rawEmail);\n    $return = $objMail-&gt;decode($args);\n\n    if (PEAR::isError($return)) {\n        echo(&quot;&lt;p&gt;&quot; . $return-&gt;getMessage() . &quot;&lt;/p&gt;&quot;);\n        var_dump($return);\n    } else {\n        //echo(&quot;No error in PEAR::isError(return)&quot;);\n    }\n\n    if($return-&gt;body){\n        $decoded = base64_decode($return-&gt;body, true);\n        var_dump($decoded);\n    }//end if(body)\n\n}//end foreach(mailfiles as file)\n\n\n?&gt;\n</code></pre>\n"}]
['https://Stackoverflow.com/questions/12896', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/314/']