简体   繁体   中英

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.

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 = 'user@gmail.com';
$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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM