Martin van Dam
Martin van Dam

Reputation: 106

email parser or php imap functions?

I want a very reliable way of retrieving data from email headers. Should I use an email parser like eg https://github.com/plancake/official-library-php-email-parser or are php imap functions sufficient to get that data? What is best practice? Is there any experience? I can imagine that there is a lot of differences in formatting email headers composed by many email clients. That is why I want a reliable solution.

Upvotes: 0

Views: 1911

Answers (1)

Tim
Tim

Reputation: 699

I used built-in IMAP functions for a project which requires processing the emails by their dates and didn't need anything else actually. You can try and see if they are useful for you with the code below;

<?php

/* connect to gmail */
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = '[email protected]';
$password = 'pass123';

/* try to connect */
$inbox = imap_open($hostname, $username, $password, OP_READONLY,1) or die('Cannot connect to Gmail: ' . print_r(imap_last_error()));
$emails = imap_search($inbox, 'ALL');

/* if emails are returned, cycle through each... */
if ($emails) {

    foreach ($emails as $email_number) {

        echo imap_fetchbody($inbox, $email_number, 0);
        echo imap_fetchbody($inbox, $email_number, 1);
        echo imap_fetchbody($inbox, $email_number, 2);

    }

}

imap_close($inbox);
?>

The tricky part is imap_fetchbody($inbox, $email_number, 0). This part will return the headers. Once you get them, you can parse or use it as you wish.

Hope it helps.

Upvotes: 1

Related Questions