When an email is piped to your server, it arrives as a single, long text stream formatted according to the MIME (Multipurpose Internet Mail Extensions) standard. Parsing this stream manually is complex because emails can contain multiple sections: plain-text, HTML, and base64-encoded attachments. Let's explore how to parse MIME emails cleanly in PHP.
1. Installing the mailparse Extension
PHP has a native extension called mailparse that is highly optimized for parsing RFC 822 and RFC 2045 compliant streams. Alternatively, you can use popular composer packages like php-mime-mail-parser which act as a wrapper around the extension, giving you an clean OOP interface.
2. Extracting Headers and Content
Using a parser library, you can easily load the raw SMTP stream and extract individual email components in just a few lines of code:
$parser = new PhpMimeMailParser\Parser();
$parser->setText(file_get_contents('php://stdin'));
$from = $parser->getHeader('from');
$subject = $parser->getHeader('subject');
$textBody = $parser->getMessageBody('text');
$htmlBody = $parser->getMessageBody('html');
3. Processing Attachments Securely
If the email contains attachments, the parser handles the base64 decoding automatically. When saving files, ensure you sanitize the filenames and store them outside the public web root to prevent arbitrary code execution, keeping your mail gateway fast and incredibly secure.