PHP IMAP Reader

Open Source Code Projects

A PHP class that makes working with IMAP as easy as possible. This class is written to be chain-able to create a logically fluent and easily readable way to access an IMAP mailbox. It simplifies the PHP IMAP_* library into a set of easy to read methods that do the heavy lifting for you.

It has been fully tested to work from PHP 5.3+ including PHP 8.

You can view this project on Ben's GitHub account: https://github.com/benhall14/php-imap-reader

Language: PHP

PHP IMAP Reader

A PHP class that makes working with IMAP as easy as possible.

This class is written to be chain-able so to create a logically fluent and easily readable way to access an IMAP mailbox.

It simplifies the PHP IMAP_* library into a set of easy to read methods that do the heavy lifting for you.

It has been fully tested to work with PHP 5.3+, including PHP 8.1.

Installation via Composer

You can now install this class via composer.

$ composer require benhall14/php-imap-reader

Remember to add the composer autoloader before using the class and use the correct namespace.

require 'vendor/autoload.php';

use benhall14\phpImapReader\Email as Email;
use benhall14\phpImapReader\EmailAttachment as EmailAttachment;
use benhall14\phpImapReader\Reader as Reader;

Usage

Please make sure you have added the required classes.

In its simplest form, use the following to connect:

define('IMAP_USERNAME', ''); 				# your imap user name
define('IMAP_PASSWORD', ''); 				# your imap password
define('IMAP_MAILBOX', ''); 				# your imap address EG. {mail.example.com:993/novalidate-cert/ssl}
define('ATTACHMENT_PATH', __DIR__ . '/attachments'); 	# the path to save attachments to or false to skip attachments

try{
    
    # set the mark as read flag (true by default). If you don't want emails to be marked as read/seen, set this to false.
    $mark_as_read = true;

    # You can ommit this to use UTF-8 by default.
    $encoding = 'UTF-8'

    # create a new Reader object
    $imap = new Reader(IMAP_MAILBOX, IMAP_USERNAME, IMAP_PASSWORD, ATTACHMENT_PATH, $mark_as_read, $encoding);

    # use one or more of the following chain-able methods to filter your email selection
    $imap
        ->folder($folder)           # alias for mailbox($mailbox)
        ->mailbox($mailbox)         # sets the mailbox to return emails from. Default = INBOX
        ->id($id)                   # retrieve a specific email by id
        ->recent()                  # get all RECENT emails
        ->flagged()                 # get all FLAGGED emails
        ->unflagged()               # get all UNFLAGGED emails
        ->unanswered()              # get all UNANSWERED emails
        ->deleted()                 # get all DELETED emails
        ->unread() 		    # alias for UNSEEN()
        ->unseen()                  # get all UNSEEN emails
        ->from($email)              # get all emails from $email
        ->searchSubject($string)    # get all emails with $string in the subject line
        ->searchBody($string)       # get all emails with $string in the body
        ->searchText($string)       # get all emails with $string TEXT
        ->seen()                    # get all SEEN emails
        ->read() 		    # alias for SEEN()
        ->newMessages()             # get all NEW emails
        ->oldMessages()             # get all OLD emails
        ->keyword($keyword)         # get all emails with $keyword KEYWORD
        ->unkeyword($keyword)       # get all emails without $keyword KEYWORD
        ->beforeDate($date)         # get all emails received before $date. *Date should be in a format that can be parsed by strtotime.*
        ->sinceDate($date)          # get all emails received since $date. *Date should be in a format that can be parsed by strtotime.*
        ->sentTo($to)               # get all emails sent to $to
        ->searchBCC($string)        # get all emails with $string in the BCC field
        ->searchCC($string)         # get all emails with $string in the CC field
        ->onDate($date)             # get all emails received on $date. *Date should be in a format that can be parsed by strtotime.*
        ->limit($limit)             # limit the number of emails returned to $limit for pagination
        ->page($page)               # used with limit to create pagination
        ->orderASC()                # order the emails returned in ASCending order
        ->orderDESC()               # order the emails returned in DESCendeing order
        ->reset()                   # resets the current reader to be able to reconnect to another folder/mailbox.
        ->all()                     # get all emails (default)
        ->get();                    # finally make the connection and retrieve the emails.
    
    # You can then loop through $imap->emails() for each email.
    foreach($imap->emails() as $email){

        # The email has been clean and formated.
        # see below.

    }

    # Reset the reader and connect to another folder.
    $imap->reset()->folder('Sent')->get();

    # You can also create a folder/mailbox on the IMAP stream.
    $imap->createFolder('New Folder Name');
    #or 
    $imap->createMailbox('New Folder Name');

    # You can also check if a mailbox/folder exists on the IMAP stream using:
    if ($imap->doesMailboxExists('INBOX')) {
        return "Yes, it exsits";
    } else {
        return "No, it doesn't exist.";
    }
    
    # ... your code here ...

} catch (Exception $e){

    echo $e->getMessage();

}

While looping through the returned emails, each email object can be used as below:


    $email->isTo('mail@example.com');   # Return true if the email is to $email, else returns false

    $email->replyTo();              	# Returns an array of Reply To email addresses (and names)

    $email->cc();                 	# Returns an array of CC email addresses (and names)

    $email->to();                       # Returns the recipient email address

    $email->id();                       # Returns the id of the email

    $email->size();                     # Returns the size of the email

    $email->date($format);        	# Returns the date in the $format specified. Default Y-m-d H:i:s

    $email->subject();          	# Returns the email subject

    $email->fromName();     		# Returns the sender's name, if set.

    $email->fromEmail();     		# Returns the sender's email address

    $email->plain();            	# Returns the plain text body of the email, if present

    $email->html();            		# Returns the html body of the email, if present

    $email->hasAttachments();       	# Returns true/false based on if the email has attachments

    $email->attachments();      	# Returns an array of EmailAttachment objects

    $email->attachment($id);    	# Returns an attachment based on the given attachment $id

    $email->isRecent();   		# Returns true/false based on the recent flag

    $email->isUnseen();       		# Returns true/false based on the unseen flag

    $email->isFlagged();  		# Returns true/false based on the flagged flag

    $email->isAnswered(); 		# Returns true/false based on the answered flag

    $email->isDeleted();      		# Returns true/false based on the deleted flag

    $email->isDraft();          	# Returns true/false based on the draft flag

    $email->eml();                      # Returns the email in .eml format

    $email->saveEml($filename);         # Saves the email in .eml format
    
    $email->count();         # Returns number of emails in folder

    $email->getHeader($header_name);         # Returns the data that matches the header name, for example: Thread-Index

    $email->getHeaders();         # Returns an array of all headers attached to the email.

The $email->attachments(); method returns an array of attachments belonging to the email in a benhall14\phpImapReader\EmailAttachment object. The following methods are available for each attachment.


	# check if the current $email has any attachments.
	if($email->hasAttachments()){
	
		# get the attachments for the current $email in the	loop.
		$attachments = $email->attachments();
	
		# loop through the found attachments.
		foreach($attachments as $attachment){

			$attachment->id(); 			# Returns the attachments ID.

			$attachment->name(); 		    	# Returns the attachments name.

			$attachment->filePath(); 		# Returns the local file path for the attachment. This is based on the ATTACHMENT_PATH constant set in the imap config.

			$attachment->content();			# Returns the attachments content data.

			$attachment->type(); 			# Returns either 'attachment' or 'inline'.

		}

}	

Requirements

Works with PHP 5.3+ (including PHP 8.1)

PHP IMAP Extension

License

Copyright (c) 2016-2025 Benjamin Hall, ben@conobe.co.uk https://conobe.co.uk

Licensed under the MIT license

Donate?

If you find this project helpful or useful in anyway, please consider getting me a cup of coffee - It's really appreciated :)

Donate

Ben is an amazing developer with an amazing work ethic. Could not recommend enough.
David C
EXCELLENT AS ALWAYS! I've been working with Ben for a long time now and he is the best programmer. Always efficient and excellent work. Thank you Ben!
Lauren D
Ben is an amazing developer. He took the project and delivered it on time and within budget, whilst maintaining excellent communication. He also worked beyond what was asked to make sure the project was functioning correctly. Would highly recommend A++++!
David B.
Benjamin is a talented developer who can tackle technically challenging projects with great service and communication. Thoroughly recommended.
Steven M.
Excellent working with Ben. he went above and beyond to help us out and was super responsive. Would highly recommend him!
Joe W
Great communication and quick to solve / answer any issues that came up across the way. Would recommend to everyone.
Charlotte C
Ben did an amazing job building an animation for us and a wordpress plugin. Thank you so much for e fast service and great comms Ben!
Effie M
Ben built us a fantastic estate agent brochure site that is both beautiful and functional. He integrated a seamless property search feature and intuitive inquiry forms that have significantly increased our lead volume. The backend is easy for us to update with new listings, and the site's speed is impressive. Ben really understands the balance between aesthetic appeal and conversion-driven design.
Sebastian J.
Absolutely superb, a great work ethic, outstanding knowledge and a great eye for detail. I thoroughly recommend him!
Gary J.
Ben developed a Project Management portal that has become the central hub for our entire team. It has made collaboration effortless—everyone knows exactly what they are responsible for and when it's due. The notification system and progress dashboards keep us all accountable without the need for constant status meetings. Ben didn't just build an app; he built a better way for us to work together.
Benjamin F.
Absolutely amazing experience. Ben is an expert in this field, I was amazed at how quickly he jumped on our platform and decoded the code, db etc. He will go over and above to find solutions for clients. Highly recommended.
Harrus A.
Benjamin is one of the best people that I have worked. Quick, serious and to the point. Highly recommended.
Joseph G
Ben went the extra mile and not only resolved the problem but provided a more suitable solution for the long term. Cheers!
William R.
I was impressed: a freelancer who could give me inputs and details on how he'd implement the solution, kept me updated in the meanwhile, understood my requirements and proposed pretty nice tweaks to make things even better. Ben, you are amazing. I will need no more time to find any other dev's, and will surely deal with you again if I need something related to these things in the future. Full stop.
Marco F.
Ben successfully integrated a booking portal into our WordPress site, allowing us to take direct bookings for the first time. Since the launch, we’ve seen a boost in leads and a much lighter workload for our front-desk staff. Seamless execution!
Christopher P.
Fantastic work on our JS script. Ben worked beyond the goals of the project and overcame extra issues that were not defined in the project. He is very quick to respond and patent when waiting for our response. One of our top 5 Developers, We had to deal with many Interfaces including server firewalls/Java-scripting/JSON/PHP/PHP APIs/Remote Databases and automation.
Kevin J.
Extraordinairly creative, timely and skillful work - Ben is always great to work with.
Charlie D
Our new helpdesk portal has completely transformed our customer support workflow. Ben built a streamlined system that allows clients to submit tickets, track progress in real-time, and access a self-service knowledge base. This has significantly reduced our 'time-to-resolution' and cut down on repetitive email chains. It’s professional, scalable, and exactly what we needed to level up our service.
Nathaniel R.
Benjamin, is brilliant at what he does, he really knows what he is at. Gives real useful advice and guidance. He is fast and timely provides updates and always provides solutions and listens well. Trust me Benjamin is a breath of fresh air.
Alexander T.
Ben truly went above and beyond. He's fantastic at communication, coding, getting round problems, fixing issues, WordPress, custom plugins and much more. I will be using Ben again for other projects.
Rachael R.
Ben had a great idea for my project and completed the project to our requirements very quickly. He also helped me tweak a few issues and answered my questions quickly. We'll work with Ben again!
Gordon S.
Ben is just great to work with. Efficient, clearly communicating, understanding very quickly, and also giving great advice. I will continue working with Ben on any other WordPress stuff. Sorry for all those other PPH'ers :-)
Bruno V.
As a self-employed tutor, I needed a way to streamline student assessments. Ben built a custom app that allows my students to complete quizzes and mock exams directly through my website. The automated notification system is a game-changer! It has made my workflow so much more efficient and has been a huge hit with my students. Ben’s work is top-tier.
Harrison K.
We approached Ben to build a bespoke local intranet HR portal with a complex set of requirements—from leave management and holiday requests to internal job boards and even a uniform request system. Not only did he deliver on every front, including in-app messaging and training modules, but he also went above and beyond our original scope. The system has completely transformed how we handle onboarding and benefits.
Dominic S.
Ben was instrumental in launching my online pottery shop. He built a custom solution that handles unique orders and custom-made items with ease. My online presence has never been stronger, and the ability to manage sales through my own website has been a game-changer for my business growth. Highly recommend his services!
Julian D.

Contact

Get in touch

We are always happy to discuss your project and explore how we can assist you. Please reach out to us using the form.

We would love to hear more about your exciting new venture.

Simply fill in the form to get started, and we'll be in touch soon.

Want to email us direct? No problem - ben@conobe.co.uk.