PHP Connecting to a mailbox


Example

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)
  • Connection flags (see below)
FlagDescriptionOptionsDefault
/service=serviceWhich service to useimap, pop3, nntp, smtpimap
/user=userremote user name for login on the server
/authuser=userremote authentication user; if specified this is the user name whose password is used (e.g. administrator)
/anonymousremote access as anonymous user
/debugrecord protocol telemetry in application's debug logdisabled
/securedo not transmit a plaintext password over the network
/norshdo not use rsh or ssh to establish a preauthenticated IMAP session
/ssluse the Secure Socket Layer to encrypt the session
/validate-certcertificates from TLS/SSL serverenabled
/novalidate-certdo not validate certificates from TLS/SSL server, needed if server uses self-signed certificates. USE WITH CAUTIONdisabled
/tlsforce use of start-TLS to encrypt the session, and reject connection to servers that do not support it
/notlsdo not do start-TLS to encrypt the session, even with servers that support it
/readonlyrequest read-only mailbox open (IMAP only; ignored on NNTP, and an error with SMTP and POP3)

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 command which returns a resource value pointing to a stream:

<?php
$mailbox = imap_open("{imap.example.com:993/imap/tls/secure}", "username", "password");
if ($mailbox === false) {
    echo "Failed to connect to server";
}