Opening a mailbox

resource imap_open ( string mailbox, string username, string password [, int options])

bool imap_close ( resource imap_stream [, int flag])

The first step to reading email is learning how to open and close the connection. As you should have guessed by now, this is accomplished through the imap_open() and imap_close() functions. The first of these two takes a mail box to open as its first parameter, then a username and password as parameters two and three respectively. The first parameter is where the odd syntax comes in - here is an example of imap_open() in action:

    print imap_open("{}INBOX", "username", "password");

Running that script, once you have changed the domain name, username, and password to valid values, should print out something like "Resource id #4". If you get nothing printed out, it means the connection was unsuccessful and you probably need to check you have it typed in correctly.

Once you get your script working, you should see that the imap_open() function returns a resource for the IMAP connection - this is technically known as the IMAP stream. This should be stored for later use, so place it into a variable such as $imap.

Now, the first parameter to imap_open() is where the confusion might come in. In the example above, it designates a connection to the server on port 143, then selects the folder INBOX. The braces, { and }, are required, and should not include any spaces inside them. Some IMAP servers have different forms for connection. For example, connection to Microsoft Exchange might require you to use "{}Inbox" and also provide the username as "<yourdomain>/<yourusername>". Also, if you are running your IMAP server using SSL, you may need to use "{}INBOX". I recommend you imap_open() as shown in the code example above unless you specifically need to change it.

Once you are finished with the connection, call imap_close() and pass the IMAP connection resource variable as its only parameter, like this:

    $imap = imap_open("{}INBOX", "username", "password");

Being able to connect to and disconnect from a mail server is not very impressive, but it is a good start - read on!

Author's Note: It is best to specify the server by its IP address (such as as opposed to the domain name, as you will likely find it a great deal faster. For the purpose of this book domain names are used as they make for much easier reading.


Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Reading message information >>

Previous chapter: Reading mail

Jump to:


Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.