Test PHP Connection to IMAP Mailbox

Simply enter your server location, account name, and password into this code and it will connect to your email account via IMAP (or display the reason why it couldn't connect).

For more information on PHP IMAP functions, see the official documentation.


$mail_server = "imap.example.com" ;
$mail_port = 143 ;
$mail_username = "test@example.com" ;
$mail_password = "pw" ;

echo "<h1>".$mail_username." on ".$mail_server."</h1>\n\n" ;
$mbox = imap_open("{".$mail_server.":".$mail_port."}".$mail_folder, $mail_username, $mail_password) or die("Error opening mailbox: ".imap_last_error());
$mailboxheaders = imap_headers($mbox);
if ($mailboxheaders == false) {
    echo "<p>".$mail_folder." is empty.</p>\n\n";
} else {
    echo "<h2>".$mail_folder."</h2>\n" ;
    echo "<ol>\n" ;
    $msgno = 0;
    foreach ($mailboxheaders as $val) {
        echo "  <li>".$val ."</li>\n";
    echo "</ol>\n\n" ;




This post was published on February 20th, 2009 by Robert James Reese in the following categories: IMAP and PHP Before using any of the code or other content in this post, you must read and agree to our terms of use.