- # IMAP
- # Install IMAP extension
- # List all folders in the mailbox
- # Finding messages in the mailbox
- imap_list
- Return Values
- Changelog
- Examples
- See Also
- Display mailbox folders with IMAP using PHP
- Client
- Get the connection status
- Check the current connection
- Force reconnect
- Close connection
- List all available folders
- Find a folder by path
- Find a folder by name
- Find a folder by name or path
- Create new folder
- Get folder detail
# IMAP
To do anything with an IMAP account you need to connect to it first. To do this you need to specify some required parameters:
- The server name or IP address of the mail server
- The port you wish to connect on
- IMAP is 143 or 993 (secure)
- POP is 110 or 995 (secure)
- SMTP is 25 or 465 (secure)
- NNTP is 119 or 563 (secure)
Your connection string will look something like this:
imap.example.com:993/imap/tls/secure>
Please note that if any of the characters in your connection string is non-ASCII it must be encoded with utf7_encode($string)
To connect to the mailbox, we use the imap_open
(opens new window) command which returns a resource value pointing to a stream:
$mailbox = imap_open("", "username", "password"); if ($mailbox === false) echo "Failed to connect to server"; >
# Install IMAP extension
(opens new window) in PHP you’ll need to install the IMAP extension:
Debian/Ubuntu with PHP5
sudo apt-get install php5-imap sudo php5enmod imap
Debian/Ubuntu with PHP7
sudo apt-get install php7.0-imap
YUM based distro
Mac OS X with php5.6
brew reinstall php56 --with-imap
# List all folders in the mailbox
Once you’ve connected to your mailbox, you’ll want to take a look inside. The first useful command is imap_list
(opens new window) . The first parameter is the resource you acquired from imap_open , the second is your mailbox string and the third is a fuzzy search string ( * is used to match any pattern).
$folders = imap_list($mailbox, "", "*"); if ($folders === false) echo "Failed to list folders in mailbox"; > else print_r($folders); >
The output should look similar to this
Array ( [0] => imap.example.com:993/imap/tls/secure>INBOX [1] => imap.example.com:993/imap/tls/secure>INBOX.Sent [2] => imap.example.com:993/imap/tls/secure>INBOX.Drafts [3] => imap.example.com:993/imap/tls/secure>INBOX.Junk [4] => imap.example.com:993/imap/tls/secure>INBOX.Trash )
You can use the third parameter to filter these results like this:
$folders = imap_list($mailbox, "", "*.Sent");
And now the result only contains entries with .Sent in the name:
Array ( [0] => imap.example.com:993/imap/tls/secure>INBOX.Sent )
Note: Using * as a fuzzy search will return all matches recursively. If you use % it will return only matches in the current folder specified.
# Finding messages in the mailbox
You can return a list of all the messages in a mailbox using imap_headers
$headers = imap_headers($mailbox);
The result is an array of strings with the following pattern:
[FLAG] [MESSAGE-ID])[DD-MM-YYY] [FROM ADDRESS] [SUBJECT TRUNCATED TO 25 CHAR] ([SIZE] chars)
Here’s a sample of what each line could look like:
A 1)19-Aug-2016 someone@example.com Message Subject (1728 chars) D 2)19-Aug-2016 someone@example.com RE: Message Subject (22840 chars) U 3)19-Aug-2016 someone@example.com RE: RE: Message Subject (1876 chars) N 4)19-Aug-2016 someone@example.com RE: RE: RE: Message Subje (1741 chars)
Symbol | Flag | Meaning |
---|---|---|
A | Answered | Message has been replied to |
D | Deleted | Message is deleted (but not removed) |
F | Flagged | Message is flagged/stared for attention |
N | New | Message is new and has not been seen |
R | Recent | Message is new and has been seen |
U | Unread | Message has not been read |
X | Draft | Message is a draft |
Note that this call could take a fair amount of time to run and may return a very large list.
An alternative is to load individual messages as you need them. Your emails are each assigned an ID from 1 (the oldest) to the value of imap_num_msg($mailbox)
There are a number of functions to access an email directly, but the simplest way is to use imap_header
(opens new window) which returns structured header information:
$header = imap_headerinfo($mailbox , 1); stdClass Object ( [date] => Wed, 19 Oct 2011 17:34:52 +0000 [subject] => Message Subject [message_id] => 04b80ceedac8e74$51a8d50dd$0206600a@user1687763490> [references] => ec129beef8a113c941ad68bdaae9@example.com> [toaddress] => Some One Else someoneelse@example.com> [to] => Array ( [0] => stdClass Object ( [personal] => Some One Else [mailbox] => someonelse [host] => example.com ) ) [fromaddress] => Some One someone@example.com> [from] => Array ( [0] => stdClass Object ( [personal] => Some One [mailbox] => someone [host] => example.com ) ) [reply_toaddress] => Some One someone@example.com> [reply_to] => Array ( [0] => stdClass Object ( [personal] => Some One [mailbox] => someone [host] => example.com ) ) [senderaddress] => Some One someone@example.com> [sender] => Array ( [0] => stdClass Object ( [personal] => Some One [mailbox] => someone [host] => example.com ) ) [Recent] => [Unseen] => [Flagged] => [Answered] => [Deleted] => [Draft] => [Msgno] => 1 [MailDate] => 19-Oct-2011 17:34:48 +0000 [Size] => 1728 [udate] => 1319038488 )
imap_list
reference should normally be just the server specification as described in imap_open() .
Passing untrusted data to this parameter is insecure, unless imap.enable_insecure_rsh is disabled.
Specifies where in the mailbox hierarchy to start searching.
There are two special characters you can pass as part of the pattern : ‘ * ‘ and ‘ % ‘. ‘ * ‘ means to return all mailboxes. If you pass pattern as ‘ * ‘, you will get a list of the entire mailbox hierarchy. ‘ % ‘ means to return the current level only. ‘ % ‘ as the pattern parameter will return only the top level mailboxes; ‘ ~/mail/% ‘ on UW_IMAPD will return every mailbox in the ~/mail directory, but none in subfolders of that directory.
Return Values
Returns an array containing the names of the mailboxes or false in case of failure.
Changelog
Version | Description |
---|---|
8.1.0 | The imap parameter expects an IMAP\Connection instance now; previously, a valid imap resource was expected. |
Examples
Example #1 imap_list() example
$mbox = imap_open ( «» , «username» , «password» , OP_HALFOPEN )
or die( «can’t connect: » . imap_last_error ());
?php
$list = imap_list ( $mbox , «» , «*» );
if ( is_array ( $list )) foreach ( $list as $val ) echo imap_utf7_decode ( $val ) . «\n» ;
>
> else echo «imap_list failed: » . imap_last_error () . «\n» ;
>
See Also
- imap_getmailboxes() — Read the list of mailboxes, returning detailed information on each one
- imap_lsub() — List all the subscribed mailboxes
Display mailbox folders with IMAP using PHP
When using IMAP its likely you will want access to the users mailbox so they can view all their folders. This tutorial will explain how display mailbox folders using imap_list.
Before attempting to show the maiilbox folders a connection with the email server needs to be established with imap_open such as:
$mbox = imap_open("", "sample@example.com","password");
To display mailbox folders use the function imap_list it requires 3 parameters first the imap_stream (connection) then the ref should normally be just the server specification as described in imap_open(). The third parameter dictates which folder to look in.
There are two special characters you can pass as part of the pattern: ‘*’ and ‘%’. ‘*’ means to return all mailboxes. If you pass pattern as ‘*’, you will get a list of the entire mailbox hierarchy. ‘%’ means to return the current level only. ‘%’ as the pattern parameter will return only the top level mailboxes; ‘~/mail/%’ on UW_IMAPD will return every mailbox in the ~/mail directory, but none in subfolders of that directory.
Some mail servers separate the mailboxes with > others use ] such as Gmail to remove these from the folder when viewing them a simply preg_match will do the job
//remove any > characters from the folder if (preg_match("/>/i", $list[0])) < $arr = explode('>', $list[0]); >
Also to remove INBOX. from the mailbox name simply do a string replace
//remove INBOX. from the folder name $folder = str_replace('INBOX.', '', stripslashes($arr[1]));
The inbox is sometimes the last mailbox in the array so look through the array and if the first folder is not the inbox reverse the array
//check if inbox is first folder if not reorder array if($folder !== 'INBOX')
Putting what we have so far the inbox will always come first, at this point nothing is displayed we’re simple doing some prep work
$list = imap_list($mbox, '', "*"); //remove any > characters from the folder if (preg_match("/>/i", $list[0])) < $arr = explode('>', $list[0]); > //also remove the ] if it exists, normally Gmail have them if (preg_match("/]/i", $list[0])) < $arr = explode(']/', $list[0]); >//remove INBOX. from the folder name $folder = str_replace('INBOX.', '', stripslashes($arr[1])); //check if inbox is first folder if not reorder array if($folder !== 'INBOX')
Next loop through the array and display each mailbox I’ve commented each step, also to show the mailbox names correctly decode them with imap_utf7_decode.
charactors from the folder if (preg_match("/>/i", $val)) < $arr = explode('>', $val); > //also remove the ] if it exists, normally Gmail have them if (preg_match("/]/i", $val)) < $arr = explode(']/', $val); >//remove any slashes $folder = trim(stripslashes($arr[1])); //remove inbox. from the folderName its not needed for displaying purposes $folderName = str_replace('INBOX.', '', $folder); echo "".ucwords(strtolower(imap_utf7_decode($folderName)))."
n"; > > else < echo "Folders not currently availablen"; >?>
A lot of these steps are not essentially you could get all the mailbox folders and display them in a few lines as illustrated below but I believe taking the time to display the folders in a user friendly manor is much better.
", "*"); if (is_array($list)) < foreach ($list as $val) < echo imap_utf7_decode($val) . "n"; >> else < echo "imap_list failed: " . imap_last_error() . "n"; >?>
Client
Every client has to connect to the server before any operation can be performed.
/** @var \Webklex\PHPIMAP\Client $client */ $client->connect();
Get the connection status
Check if the current connection is still established.
/** @var \Webklex\PHPIMAP\Client $client */ /** @var boolean $status */ $status = $client->isConnected();
Check the current connection
Check if the current connection is still alive and reconnect if necessary.
/** @var \Webklex\PHPIMAP\Client $client */ $client->checkConnection();
Force reconnect
You can force the client to do a reconnect. This will close the connection and open a new one.
/** @var \Webklex\PHPIMAP\Client $client */ $client->reconnect();
Close connection
You can force the client to close the current connection.
/** @var \Webklex\PHPIMAP\Client $client */ $client->disconnect();
List all available folders
If hierarchical order is set to true, it will make a tree of folders, otherwise it will return flat array.
/** @var \Webklex\PHPIMAP\Client $client */ /** @var \Webklex\PHPIMAP\Support\FolderCollection $folders */ $folders = $client->getFolders($hierarchical = true);
Find a folder by path
Provide the entire folder path. Your delimiter may vary.
/** @var \Webklex\PHPIMAP\Client $client */ /** @var \Webklex\PHPIMAP\Folder $folder */ $folder = $client->getFolderByPath('INBOX.name');
Find a folder by name
Provide only the folder name. A delimiter is not required.
/** @var \Webklex\PHPIMAP\Client $client */ /** @var \Webklex\PHPIMAP\Folder $folder */ $folder = $client->getFolderByName('name');
Find a folder by name or path
Provide either a folder name or path. A delimiter is not required but can be provided as well.
/** @var \Webklex\PHPIMAP\Client $client */ /** @var \Webklex\PHPIMAP\Folder $folder */ $folder = $client->getFolder($folder = "INBOX.name", $delimiter = null); $folder = $client->getFolder($folder = "name", $delimiter = null);
Create new folder
Create a new folder. If you toggle expunge, your current imap session might not recognize the new folder.
/** @var \Webklex\PHPIMAP\Client $client */ /** @var \Webklex\PHPIMAP\Folder $folder */ $folder = $client->createFolder($folder = 'INBOX.name', $expunge = true);
Get folder detail
You can receive basic information about a given folder. These include the number of messages, the next uid and a list off all available flags.
/** @var \Webklex\PHPIMAP\Client $client */ /** @var array $info */ $info = $client->checkFolder($folder = 'INBOX.name');
array:5 [ "flags" => array:1 [ 0 => array:6 [ 0 => "\Answered" 1 => "\Flagged" 2 => "\Deleted" 3 => "\Seen" 4 => "\Draft" ] ] "exists" => "65" "recent" => "0" "uidvalidity" => 1488899637 "uidnext" => 202 ]