This article describes how to use PHP to connect to mailservers, and display emails on a webpage. In the case of Microsoft Exchange based systems other details such as Calendars, and Tasks can also be retrieved and displayed.
Before starting you will need to make sure that your server is using PHP with the IMAP module included. The method of enabling IMAP will differ depending on whether it is a Windows server or a UNIX server. To see if you have IMAP enabled on the server, the easiest way to check is to create a new PHP and browse to it, the contents of which should be:
<?php
print phpinfo();
?>
If you have it installed there will be a table titled IMAP. If you don't have it installed, and are running Windows then make sure that your PHP installation has the extensions folder and that your php.ini file is pointing to it's correct location for the extension_dir variable. When you have done this uncomment (by removing the semi-colon) before the line that reads:
extension=php_imap.dll
On UNIX based servers it involves compiling PHP with:
--with-imap[=DIR]
The [=DIR] signifies an optional parameter pointing to the location the IMAP files are stored. If you are unsure about any of this stage then ask your server administrator otherwise you risk bringing down your webserver. Once IMAP is sorted, you are now ready to start coding.
Before you can start accessing emails on the server you will need to connect to it with the correct authorisation. Looking at the PHP documentation, we can see that there is the imap_open command, and it will work not just for IMAP servers, but also for POP3 and NNTP.
resource imap_open ( string mailbox, string username, string password [, int options] )
This command will take the location of the mailbox - the server url or ip address, followed by the port number if required. It will also take the username and password to connect with along with any optional parameters you may wish to supply. Most optional parameters can also be added to the mailbox address by using something like /pop3 at the end to signify using POP3 as the protocol instead.
$mbox = imap_open("{www.example.com:890/pop3/ssl/novalidate-cert}",
"admin", "password")
or die("Can't connect: ".imap_last_error());
The above example will connect to a POP3 mailbox on www.example.com connecting to port 890 using SSL, and a self-signed certificate; or fail with the received error if it cannot make the connection. For more details on the optional parameters check the PHP documentation for imap_open.
In creating this application we may want to support multiple users, so we won't hard code this in, but instead create a function that has our desired parameters and mailbox location ready set. So instead, use the following function:
function connectMailbox ($user, $pass)
{
if ($mailbox = @imap_open("{www.example.com:890/pop3/ssl/novalidate-cert}",
$user, $pass)) {
return $mailbox;
}
else {
return -1;
}
}













