4

How to parse a .eml file in php? Is there any PHP libriary or PHP extension ?

I want to display the mail header information such as sender, receiver, title, attachement and eml body content in browser.

Trufa
  • 39,971
  • 43
  • 126
  • 190
maarten
  • 81
  • 1
  • 1
  • 3
  • 6
    That's not a question but a google request. - If you're looking for code: http://pear.php.net/package/Mail_Mime/ – hakre Jul 10 '12 at 08:23
  • I agree with Hakre, please explain what you've attempted to do so far.. – Luceos Jul 10 '12 at 08:25

2 Answers2

5

There are a couple of ways to do it. One way is to simply do it yourself, it's not that complicated.

Otherwise, you might want to have a look at the Mailparse library:

http://php.net/manual/en/book.mailparse.php

And there is also this one:

http://code.google.com/p/php-mime-mail-parser/

Doa
  • 1,965
  • 4
  • 19
  • 35
  • but even the php extension mailparse in php.net doesn't works well with some eml file.I can not get eml header information such as subject,time,sender when the eml file source like this ------------Return-Path: Delivered-To:aa@mail.com.cn*X-WM-Delivered:bb@mail.com.cn ....------------- the is not blank line between erver item. so can not be parsed – maarten Jul 12 '12 at 08:31
  • 1
    At last I find a php libaray here http://www.phpclasses.org/package/3169-PHP-Decode-MIME-e-mail-messages.html but it doesn't work well.it can not parse eml file when the source of eml file header item does not have break line. – maarten Jul 12 '12 at 08:39
  • `Return-Path: Delivered-To: test@mail.com.cn X-WM-Delivered: test@mail.com.cn Delivered-To: receive@mail.com.cn X-WM-Delivered: all@mail.com.cn Received: from PC-201104191348 ([211.154.169.179]) (envelope-sender ) by 125.208.8.125 with ESMTP Date: Tue, 3 Jul 2012 12:28:16 +0800 From: "test" Subject: =?gb2312?B?ufq80s2zvMa+1jIwMTLE6jfUws+1zbPJ/by2z+7Ev82o1qo=?= Message-ID: <201207031228157969470@mail.com.cn> X-mailer: Foxmail 6, 15, 201, 23 [cn] Mime-Version: 1.0` – maarten Jul 12 '12 at 10:12
  • There is a missing > here: "To: "all" – Doa Jul 12 '12 at 11:56
5

This is what I use:

composer require php-mime-mail-parser/php-mime-mail-parser

And then PHP:

$parser = new \PhpMimeMailParser\Parser();
$emailFile = 'myEmailFile.eml';
$parser->setText(file_get_contents($emailFile));

Then, to get addresses:

$toAddressesQ = $parser->getAddresses('to');

Or the body:

$text = $parser->getMessageBody('text');
$html = $parser->getMessageBody('html');

Or the header:

$subject = $parser->getHeader('subject');

Or the attachments:

$attachments = $parser->getAttachments();
rockstardev
  • 13,479
  • 39
  • 164
  • 296