Retrieve E-Mails With The PHP IMAP Class

Have you ever had the need to retrieve e-mail information and utilize the data for display on a website, GUI, or for some other web-based purpose? Recently, I was tasked with doing just that. The goal was to retrieve thousands of e-mail submissions from a contact form and parse out the information into readable CSV format.

In order to accomplish this goal, the first step was to get the body of the email in a text-based format automatically. PHP offers a fantastic solution for this very issue within its PHP IMAP class. Essentially, it allows you to connect to any mailbox or mailboxes within a mail server given the provided credentials. Once that connection has been established, you can loop through every email or find an arbitrary e-mail via the PHP_IMAP functions. In our case, we needed to retrieve all e-mails with a given subject line, as all contact form submissions from this website had the same subject line. With just a few short lines of code, we can open up the imap stream and retrieve the necessary information. Here is some sample code:

$mailbox = imap_open("{mail.example.com}", "username", "password", OP_READONLY); //Note 1
if ($mailbox) {
	$num_msg = imap_num_msg($mailbox); //Note 2
	if ($num_msg > 0) {
		
		//Loop through all messages
		for ($i=$num_msg; $i>0; $i--) {
			$headers = imap_header($mailbox, $i); //Note 3
			
			//If the subject is "Contact Form Submission", read the body
			if ($headers->Subject == "Contact Form Submission") { 
				
				$body = imap_body($mailbox, $i); //Note 5
				//Run code to parse body information
			}
		}

	} else {
		echo "No messages in mailbox";
	}
	imap_close($mailbox);
} else {
	echo "Cannot open mailbox.";
}
  • Note 1: The first line opens the imap stream. The last variable "OP_READONLY" means that we only want to up the mailbox as read-only.
  • Note 2: The imap_num_msg function returns how many messages are currently in the mailbox.
  • Note 3: The imap_header function returns a bunch of information relating to each message, such as dates, senders, receivers, the subject etc.
  • Note 4: The imap_body function returns the verbatim content of the message body. It is possible that this information could be returned in an encoded fashion. For example, Gmail returns the base64 encoded version of the message, so you will need to use the php base64_decode function to get the readable message content.

As you can imagine, the possibilities for e-mail manipulation and display are endless. If you need to cook up something that involves interacting with e-mail, chances are you'll be toasting PHP_IMAP at the end of the day!