Saving IMAP XLS Attchements with PHP


I have written a script to check my Gmail account and extract XLS file attachments from the message. I am using the following code to grab the attachment from the body:

$mege = imap_fetchbody($connection,$message_number,2);

The message is being retrieved just fine. Here is a sample of the output for the above code:

-Apple-Mail=_9EBAFC63-4E12-4E64-A4F9-F8D5834F3523 Content-Transfer-Encoding: 7bit Content-Type: text/html; charset=us-ascii --Apple-Mail=_9EBAFC63-4E12-4E64-A4F9-F8D5834F3523 Content-Disposition: attachment; filename=test.xls Content-Type: application/octet-stream; x-mac-type=584C5338; x-mac-creator=5843454C; x-unix-mode=0644; name="test.xls" Content-Transfer-Encoding: base64 0M8R4KGxGuEAAAAAAAAAAAAAAAAAAAAAPgADAP7/CQAGAAAAAAAAAAAAAAABAAAAAQAAAAAAAAAA EAAAIQAAAAEAAAD+////AAAAAAAAAAD///////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// ///////////////bABpAGIAcgBpADEAHgDwAAAACACQAQAAAAIA2gcBQwBhAGwAaQBiAHIAaQAxAB4A8AAAAAgAkAEA...

This is expected since the XLS file is base64 encoded. However, when i decode the message and save to a file, I am getting an empty excel file. But, it is an excel file.

I am using this to decode the content before writing to a file:


I am wondering if there is anything more I am supposed to be doing to the attachment in order to populate the file.




You are fetching the full body of a mail message, not just the attachment. What is missing is the code to parse the MIME structure, locate the actual interesting part, extract that part from the MIME container and only after that decode according to theContent-Transfer-Encoding header (your "base64" in this particular case). You just cannot blindly base64-decode the whole body and hope to get an attachment in return.

People are also looking for solutions to the problem: php - send to an additional email if button is checked


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.