Checking your IMAP email using PHP

I have an upcoming freelance project coming up that includes checking an IMAP email account as well as working with XML in PHP. Let’s talk about connecting to an IMAP account in PHP, don’t worry, I’ll discuss parsing XML next week 😉

For the sake of example, we’re going to connect to a Gmail account:

$hostname = '{imap.gmail.com:993/imap/ssl}INBOX'
$username = 'example@gmail.com'
$password = 'password'

if ($imap = imap_open($hostname, $username, $password))
{
	// Checks the inbox
	if ($messages = imap_search($imap 'ALL'))
	{
		// Sorts the messages newest first
		rsort($messages

		// Loops through the messages
		foreach ($messages as $message_number)
		{
			// Grabs the overview and body
			$overview = imap_fetch_overview($imap, $message_number, 0
			$message  = imap_fetchbody($imap, $message_number, 2

			// This is where you'd do some fun stuff if you wanted
			var_dump($overview, $message
		}
	}
	else
	{
		exit('No messages on the IMAP server.'
	}
}
else
{
	exit('Unable to connect to the IMAP server.'
}

Not much to it, set up the variables, connect and utilize the imap_fetch* methods to get what you want. Keep in mind that imap_fetch_overview will return an array of objects. If you wanted to grab just the subject line, you would call $overview[0]->subject.

Also be mindful of the third argument being passed to imap_fetchbody. The 2 specified here should return the message in RFC822 format but is more so contingent on what type of email you received (text-only or multipart). You may have to play around with that value to get the results you desire.

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.