Get IMAP mail embedded images in php

There is plenty of php snippets , showing how to get mail from an imap server. Even though many illustrates important concepts most are either faulty or incomplete. The file imapClient.php implements a complete simple php imap web client in less than 300 lines with the following features:

  • connecting to the server using imap_open()
  • finding messages to download with imap_search()
  • downloading messages including embedded images and attachments using imap_headerinfo(), imap_fetchmime(), imap_fetchstructure() and imap_fetchbody()
  • decoding messages and filenames into utf8 using charset information in message
  • formatting messages to html with embedded images and attachment links
  • html image references in the mail text src=”cid:…” are substituted with image urls.
  • closing server connection using imap_close()

The code is a good starting point if you want to pull in mails in php for further processing.  Errors are handled but not reported. Some points you would address are better styling and cleanup of attachments on the web-server after a session. On the mail server mails should be deleted or marked as read. And certainly you wouldn’t normally allow a client to download any attachment to your web-server for security reasons.

The code itself is pretty much self explained, so I won’t add any details for now. The tricky parts are to

  • do the recursion on the structure from imap_fetchstructure()
  • interpret the mime information
  • decode the data with the right decoder
  • handle more attachments with same name

The mail client is self contained, i.e. only the file imapClient.php is required. Point your browser to imapClient.php, to check it out. For attachment download to work correctly, your web-server needs permissions to create the attachment directory in the same directory as the imapClient.php file.

A good implementation of an imap mail reader is the Drupal mailhandler module. If you download the module, relevant source is in the file MailhandlerPhpImapRetrieve.class.php.

2 thoughts on “Get IMAP mail embedded images in php

  1. Hi Kim – this is a good tutorial, thanks for your work.

    I have found (and fixed) the bugs that people will come across and posted the issues on Github with the fixes.

Leave a Reply

Your email address will not be published. Required fields are marked *