Iain's IT Solutions Ltd.

Iain's IT Solutions Ltd Mobile Nav Menu

Reading email with PHP

14-Dec-2014

I've just today learnt how to use PHP to connect to a mailbox, iterate through the emails in it, and get hold of their attributes - such as date, subject and body.

This is something I've been meaning to learn for a while.  It uses the imap functions such as imap_open, imap_headerinfo & imap_fetchbody.

Once a connection to the mailbox is made (with some faffing to get the mailbox name correct) it's fairly straightforward to iterate through the mail items and read them - remembering that index number of first email is 1 and not 0.

Just learning this is a really handy thing to know, but I've implemented a use for it already.  If I send a structured email to one of my accounts, containing some recent news, I can pick this email up with the PHP of my website content management system, parse out its text and insert a record into my CMS database of news items.

The running of the PHP script which looks for new emails could be run from a cron, but instead I made it run on the opening of website home page.  When an email is found in the correct format, the news item is added to the database.  To prevent the same item being added multiple times, the email is deleted after the record is added.

What this means is that I can add a news items to my site without logging in to my content management system.  It therefore makes it very easy to update website content from an email, rather than waiting until I'm in front of my PC.  (I use a Blackberry, so the browser is a but rubbish, so it's not very good using it to log in to my CMS remotely)

The reason I looked into this wasn't just for this purpose, but because I've been having some discussions about building a helpdesk system.  So users raising tickets and IT support staff responding to and updating them.  These responses and updates all being handled via email works really nice and with these tickets being added to a database as well, it means not only a nice process for users, but automated reporting can be added.




No links allowed (to stop persistent spamming...)




Optional - enter if you want to be alerted when new comments are added