Checking your IMAP email using PHP

Josh Sherman
1 min read
Software Development 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 = '{}INBOX';
$username = '[email protected]';
$password = 'password';

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

		// 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);
		exit('No messages on the IMAP server.');
	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.

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

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.

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles