I'm using PHP's IMAP functions to scrape emails out of a Gmail account, using pretty standard code. It seems to work with text and HTML emails, but NEVER with any email with an attachment or embedded image.
Whenever there's an attachment, the return value of imap_fetchbody() is just one big bitstream rendered in ASCII--and there's no part that looks anything like the original message, so I can't imagine any way to extract the original message without the attachments. What's going on here?
Here is my code:
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'XXXX';
$password = 'XXXX';
$good = 0;
$max_emails = 25;
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());
$datelimit = date ( "d M Y", strToTime ( "-1 days" ) );
$emails = imap_search($inbox,"ALL");
if($emails) {
$output = '';
foreach($emails as $email_number) {
$overview = imap_fetch_overview($inbox,$email_number,0);
$structure = imap_fetchstructure($inbox, $email_number);
if(isset($structure->parts) && is_array($structure->parts) && isset($structure->parts[1])) {
$part = $structure->parts[1];
$message = imap_fetchbody($inbox,$email_number,2);
if($part->encoding == 3) {
$message = imap_base64($message);
} else if($part->encoding == 1) {
$message = imap_8bit($message);
} else {
$message = imap_qprint($message);
}
}
echo "Message: " . $message . "<br><br>";
...
I appreciate any insights as to what is missing that would cause it to fail to read an email. Thank you!