(PHP 4, PHP 5)

imap_openOpen an IMAP stream to a mailbox


resource imap_open ( string $mailbox , string $username , string $password [, int $options = 0 [, int $n_retries = 0 [, array $params = NULL ]]] )

Opens an IMAP stream to a mailbox.

This function can also be used to open streams to POP3 and NNTP servers, but some functions and features are only available on IMAP servers.

Список параметров


A mailbox name consists of a server and a mailbox path on this server. The special name INBOX stands for the current users personal mailbox. Mailbox names that contain international characters besides those in the printable ASCII space have to be encoded width imap_utf7_encode().

The server part, which is enclosed in '{' and '}', consists of the servers name or ip address, an optional port (prefixed by ':'), and an optional protocol specification (prefixed by '/').

The server part is mandatory in all mailbox parameters.

All names which start with { are remote names, and are in the form "{" remote_system_name [":" port] [flags] "}" [mailbox_name] where:

  • remote_system_name - Internet domain name or bracketed IP address of server.
  • port - optional TCP port number, default is the default port for that service
  • flags - optional flags, see following table.
  • mailbox_name - remote mailbox name, default is INBOX

Optional flags for names
Flag Description
/service=service mailbox access service, default is "imap"
/user=user remote user name for login on the server
/authuser=user remote authentication user; if specified this is the user name whose password is used (e.g. administrator)
/anonymous remote access as anonymous user
/debug record protocol telemetry in application's debug log
/secure do not transmit a plaintext password over the network
/imap, /imap2, /imap2bis, /imap4, /imap4rev1 equivalent to /service=imap
/pop3 equivalent to /service=pop3
/nntp equivalent to /service=nntp
/norsh do not use rsh or ssh to establish a preauthenticated IMAP session
/ssl use the Secure Socket Layer to encrypt the session
/validate-cert validate certificates from TLS/SSL server (this is the default behavior)
/novalidate-cert do not validate certificates from TLS/SSL server, needed if server uses self-signed certificates
/tls force use of start-TLS to encrypt the session, and reject connection to servers that do not support it
/notls do not do start-TLS to encrypt the session, even with servers that support it
/readonly request read-only mailbox open (IMAP only; ignored on NNTP, and an error with SMTP and POP3)


The user name


The password associated with the username


The options are a bit mask with one or more of the following:

  • OP_READONLY - Open mailbox read-only
  • OP_ANONYMOUS - Don't use or update a .newsrc for news (NNTP only)
  • OP_HALFOPEN - For IMAP and NNTP names, open a connection but don't open a mailbox.
  • CL_EXPUNGE - Expunge mailbox automatically upon mailbox close (see also imap_delete() and imap_expunge())
  • OP_DEBUG - Debug protocol negotiations
  • OP_SHORTCACHE - Short (elt-only) caching
  • OP_SILENT - Don't pass up events (internal use)
  • OP_PROTOTYPE - Return driver prototype
  • OP_SECURE - Don't do non-secure authentication


Number of maximum connect attempts


Connection parameters, the following (string) keys maybe used to set one or more connection parameters:

  • DISABLE_AUTHENTICATOR - Disable authentication properties

Возвращаемые значения

Returns an IMAP stream on success or FALSE on error.

Список изменений

Версия Описание
5.3.2 params added
5.2.0 n_retries added


Пример #1 Different use of imap_open()

// To connect to an IMAP server running on port 143 on the local machine,
// do the following:
$mbox imap_open("{localhost:143}INBOX""user_id""password");

// To connect to a POP3 server on port 110 on the local server, use:
$mbox imap_open ("{localhost:110/pop3}INBOX""user_id""password");

// To connect to an SSL IMAP or POP3 server, add /ssl after the protocol
// specification:
$mbox imap_open ("{localhost:993/imap/ssl}INBOX""user_id""password");

// To connect to an SSL IMAP or POP3 server with a self-signed certificate,
// add /ssl/novalidate-cert after the protocol specification:
$mbox imap_open ("{localhost:995/pop3/ssl/novalidate-cert}""user_id""password");

// To connect to an NNTP server on port 119 on the local server, use:
$nntp imap_open ("{localhost:119/nntp}comp.test""""");
// To connect to a remote server replace "localhost" with the name or the
// IP address of the server you want to connect to.

Пример #2 imap_open() example


$folders imap_listmailbox($mbox"{}""*");

if (
$folders == false) {
"Call failed<br />\n";
} else {
    foreach (
$folders as $val) {
$val "<br />\n";

"<h1>Headers in INBOX</h1>\n";
$headers imap_headers($mbox);

if (
$headers == false) {
"Call failed<br />\n";
} else {
    foreach (
$headers as $val) {
$val "<br />\n";


Смотрите также


I have a single comment to add about imap_open.
If you want to connect to a news server, without specifying any news gruop, you can use the following:

$nntp imap_open($server,"","",OP_HALFOPEN);

and $nntp will become the connection ID.

2000-12-04 14:59:14
Connections to the IMAP server work without specifying the port number, but they are slow, so specifying the port number is important if you don't want a slow application.
2001-03-09 15:34:47
IMAP, POP and NNTP are ok. But plaintext mailboxes are unmentioned here. You just forget the {part} and go for the file (tested on unix): 

$mbox = imap_open ($a_mail_box_file_name_in_home_dir, "", "") || die("Snif...:
2001-03-29 10:12:45
A better way to connect to a mail server would be to use uri syntax, for example:


this is very easy to parse using 'parse_url()'

Remember to keep your username and password hidden if your over an open network
2001-05-23 13:23:07
I have found that the syntax for the imap_open command in PHP 4 differs whether you're passing a variable to the imap_open function or declaring the host directly within the function.  If you are passing variables to the imap_open function, the syntax should look like:

$username = "user";
$password = "password";
$mailserver = "";

$link = imap_open("\{$mailserver}INBOX",$username,$password);

If you don't include the leading backslash (\) you will not open the stream.  Likewise you cannot pass the curly braces to the function.

If you define the server directly, omit the leading backslash.

$username = "user";
$password = "password";

$link = imap_open("{}",$username,$password)"

I discovered all of this after 3 days of trying to get all of this work on redhat 7.1.
2001-06-26 19:16:52
It would be nice to mention that this function does send headers. It makes sense, but it is not obvious. It took me a while to figure it out. I authenticate against a POP3 server, and set a cookie if the authentication validates. At least I wanted to :) But since it sends a header to the server, setcookie() won't work.
2001-08-13 18:41:55
You can do

<? $foo imap_errors(); ?>

to clear unwanted warning messages like 'Mailbox is empty'
2001-10-30 16:01:10
For all imap functions where you specify the mailbox string it is important that you ALWAYS use IP (not hostname) and the portnumber. If you do not do this imap functions will be painfully slow.
Using hostname instead of IP adds 3 seconds to each IMAP call, not using portnumber adds 10 seconds to each imap call. (hint: use gethostbyname() )
2002-04-17 12:02:32
I just want to say to all redhat people who have problem (Couldn't open stream) with the connection on the local pop server to use this :
hope this help
2002-06-05 14:07:09
I ran into the 
PHP Warning:  Certificate failure for <server>: self signed certificate:
message while upgrading 4.0.6->4.1.2.  I'm pleased to report that {<server>:<port>/imap/tls/novalidate-cert}<mailbox>
works as expected (and fixes my problem).  I'm using IMP 2.2.8.
2002-06-17 14:27:41
Note about "PHP Warning:  Certificate failure"

I'm not sure if this is a RedHat, PHP, or IMAP library issue, but the default for SSL seems to have changed.

You now need to specify "/notls" when you don't want TLS, rather than only needing to specify "/ssl" when you do.




2003-01-08 17:07:44
  Note for all having problems to connect hosts using imap_open:

  I spent almost week trying to fix my script which was connecting to localhost but was unable to connect any other host. Sollution was actually wery simple but I'm writing that note becouse there are some posts at usenet or forums decribing similiar problems. And actually I haven't found any  answer for that. So for all of you trying to connect to hosts with imap_open CHECK IF THERE IS NO FIREWALL BLOCKING POP3. 

2003-02-27 09:35:18
pop3 seems to like refusing connection if you have OP_READONLY set

testers: be forewarned :P
2003-04-02 07:37:01
I had been having lots of trouble trying to get imap_open to connect to an imap server.  Then I found another post online that suggested this and it worked, so I am going to post it here.  I hope this helps others..

"I have tried with the following strings instead and it works: 

for pop3: {}INBOX 

and for imap: {}INBOX.
2003-04-08 12:17:54
"notls" seems to be required for PHP on RedHat 8.0, but it seems that "/norsh" is also advisable; without it, the client library will attempt an RSH connection and wait for this to timeout before reverting to normal IMAP. This was causing a 15 second delay in imap_open for me. Looking at the client lib C code this will likely be an issue on other platforms as well as they update to the newer version. You can use both "/notls" and "/norsh", e.g. the first parameter to imap_open can be something like: "{}".
2003-04-23 22:29:46
Had problems to use imap_open with iMail 6.06 Server. My problem was (sounds stupid): Didn't realise that the username had to be the full email address and not just the login. Maybe this helps some people.
2003-05-08 21:10:58
I was getting bizzare errors that I couldn't find documentation about anywhere on Google. I tried connecting to another server and got different, but just as unusual error messages. I even checked the POP3 server logs and it said something about invalid command... I figured it was another libc problem.

Stupidly enough, the problem was that I was using an unset variable for the password! Make sure you don't have an empty username or password... you'll have a hard time debugging the problem ;)
2003-06-14 19:52:23
I only run imap on port 993 (ssl only) and I was unable to use imap_open().. couldn't even get an error out of the script, it just sat there and timed out with no messages in the logs or anything--the page wouldn't load.

Anyway, this is what finally worked, which I found in the readme for a popular opensource webmail system:

$i = @imap_open("{localhost:993/ssl/novalidate-cert}INBOX", $user, $pw);

I didn't see the 'ssl' option mentioned anywhere in these comments so maybe this will help someone out.
2003-08-18 19:44:22
Thanks for all your comments.  The user comments have saved me countless times.

I'd like to give back in my small way by providing this little tip.  To test your pop or imap services you can use telnet (almost all operating systems should come with a command line telnet client).

Here's the pop3 example (the lines that start with + are the server's response):

    telnet 110
    +OK POP3 v2001.78 server ready
    user your_username
    +OK User name accepted, password please
    pass your_password
    +OK Mailbox open, 23 messages

Note that your pop server may be on some other port than 110 but that is the default/standard.

Here's the imap example (Lines that have OK near the begining are server responses):

    telnet 143
    1 LOGIN "your_username" "your_password"
    1 OK [CAPABILITY...] ... User your_username authenticated

This might be old news to some people but I hope it's helpful for many.
2003-11-03 13:50:37
In order to make a IMAP connection to a Microsoft Exchange Server 5.5, I used this connection-string :

if(imap_open ("{}Inbox""DOMAIN/USERNAME/ALIAS""PASSWORD"))
'Connection success!';
'Connection failed';

By replacing "Inbox" with, e.g. "Tasks", its possible to see all your tasks. I Hope this helps anybody!

2004-01-14 05:03:39
To open local mailbox ( mbox ) enter its absolute file name.

>an absolute filename 
>This specifies a mailbox in the default format (usually >Berkeley format for most default library builds) 

2004-06-22 13:37:13
To authenticate using kerberos V / GSSAPI, you might need to add "user=" to the connection string.. eg:

$mbox = imap_open( "\{" . $user . "}INBOX", $user, $passwd );

Our IMAP servers won't allow a user other than the user specified in the kerberos credentials connect using those credentials unless you specify that extra "user=" in the connection string.  Passing it as an argument to imap_open() doesn't seem to be enough.
2004-06-29 19:40:40
I've found that on my servers I _must_ use imap_errors() and imap_alerts() after an imap_open or this error is thrown in the logs when the mailbox is empty: [error] PHP Warning: (null)(); Mailbox is empty (errflg=1) in Unknown on line 0
2004-12-13 13:35:45
thanks to the one who added that the login part should be the whole email address for it to work.. (assuming of course that all other stuff is good and working ;)

to add something, in the 'email address' login name, is not really the email address, ,it's the pop login name plus '@' plus the domain.. hope it's not confusing...

2004-12-14 00:22:28
I can connect to my email server with no problem using regular usernames and passwords but.... in my server the usernames are long.. like , and i get an error when the username size is over 40 chars:

$conn = imap_open("{". $server . ":110/pop3}", $username, $user_password) or die ("Failed with error: ".imap_last_error());


Too many login failures

when the username is over 40 chars. Just remember that if you plan to use long usernames.
2005-02-24 20:14:31
Warning: imap_open() [function.imap-open]: Couldn't open stream {}INBOX 

correct the connection string as :
2005-02-25 23:19:52
a little tip for those who get really frustrated even after reading all the right solutions and implementing them but still get the same errors or none at all..:
after having changed the code.. restart the httpd deamon..

for Fedora or any other Red Hat Linux OS (/etc/init.d/httpd restart).

After this you will be able to make a imap/pop3 stream from apache..
2005-04-27 13:50:27
For FreeBSD users...

If you want to have SSL support, you want to install the ports:


Cheers :)

 - avizion
2005-05-12 06:30:27
WHen you use the /ssl connection...  half open doesnt work...!

what i did was opened it up with the .com:143/pop3}, op_halfopen

when i was getting my folders...
2005-08-02 22:13:13
Looking for a cool PHP Script to help you connect to a POP3 server, and download E-Mail to MySQL? Check out my neet-skeet script I wrote. Have fun.


Download the above TXT file, and rename it to phPOP3.php.

Trust me, you will learn mostly everything about IMAP with this script.

By the way, be sure to use print_r($headers) to discover the headers that come with each message. You can setup your MySQL + Email Account information at the top of the script. No includes required!

2005-12-08 22:36:40
imap_open will not open a stream if your server operates with Transport Layer Security (i.e. TLS) imap_open connects with SSL if its there. So try opening mailbox as 

$mailbox="{}"; This works...

Some mail server requires you to provide so you can always use.

$conn=imap_open($mailbox, $username, $password);

Some server may ask for username as ""

2006-04-04 14:55:08
None of the above comments explain the configuration issues on Apache/Windows combination. I thought it might be helpful to list my findings here so that Windows people's time is saved.

There is a bug in Windows php_imap.dll that prevents it from connecting it to the SSL IMAP/POP3 server.
2006-09-11 13:25:22
you can avoid this message :

Warning: (null)(); Mailbox is empty (errflg=1) in Unknown on line 0

by specified the option OP_SILENT to imap_open.
2007-02-27 03:08:17
Beginning with 5.2.2, binaries built for Windows also seem to have changed its default behavior.
'/notls' needs to be specified for a non-SSL connection.
2007-05-11 02:11:56
Setting a mailbox name (eg INBOX) at the end of the connection string does not work when using imap_open() with OP_HALFOPEN. You may use imap_reopen() then.


/* this will fail : */
$connection imap_open('{}INBOX''foo''secret'OP_HALFOPEN.);
$num_mgs imap_num_msg($connection);

/* this will do : */
$connection imap_open('{}INBOX''foo''secret'OP_HALFOPEN.);
$num_mgs imap_num_msg($connection);

2007-09-08 11:06:38
By default, imap_open() will retry an incorrect password 3 times before giving up.  This is a feature built into the c-client library intended for interactive mail clients (which can prompt the end user for a new username/password combo.)

The new optional parameter "$n_retries" allows PHP to override the default retry limit.  There is absolutely no reason to leave this at default, or to set it to any value other than 1.  This is especially important if the mail server you're using locks users out after too many login failures.
2007-09-27 11:50:44
Works with Gmail's new IMAP function for personal and for Google Apps.

$mbox = imap_open ("{}INBOX", "", "password")
     or die("can't connect: " . imap_last_error());
2007-10-31 13:50:28
I was trying imap_open() function but I was continuously getting this error:

Array ( [0] => [CLOSED] IMAP connection broken (server response) )

I was finally able to solve this problem (which is a very common problem as I saw it on the net but could not find any solution to it) so I'm posting my solution here which I hope will be useful to others.

I used stunnel program ( and made changes in the stunnel.conf file as follows:

I added these lines:
accept = localhost:143
connect  = imapserver:993
client = yes
sslVersion = TLSv1

This will map insecure imap connection from localhost:143 to imapserver:993 (IMAP with SSL).

After this I tried this code and it worked fine:


$imap = @imap_open("{localhost:143}INBOX"$user$pass);

and I was able to do away with the errors.

A more detailed post about it can be found here:,190628.0.html
2008-04-11 17:39:13
In my case, e-mail host was the IMAP enabled.
So, just use the imap_open as the very simple form like:

$mailbox = "{}INBOX";
$user = ""; 
$pass = "mypassword"; 

$connection = imap_open($mailbox,$user,$pass) or die(imap_last_error()."<br>Connection Faliure!");

2008-04-25 13:56:06
My script kept on timing out, even though the syntax was spot on... ultimately, I figured out that the port was blocked by my webhost, where I ran this on a shared server...

I post this just in case you miss this obvious, like I did.
2009-07-04 01:45:14
imap_open is very simple to use, but struggles a litte bit on setups with ssl and tls.

this are tested examples for different hosts and protocols.

uncomment the host/protocol line and fill in correct username and password.



# localhost pop3 with and without ssl
# $authhost="{localhost:995/pop3/ssl/novalidate-cert}";
# $authhost="{localhost:110/pop3/notls}";

# localhost imap with and without ssl
# $authhost="{localhost:993/imap/ssl/novalidate-cert}";
# $authhost="{localhost:143/imap/notls}";
# $user="localuser";

# localhost nntp with and without ssl
# you have to specify an existing group, control.cancel should exist
# $authhost="{localhost:563/nntp/ssl/novalidate-cert}control.cancel";
# $authhost="{localhost:119/nntp/notls}control.cancel";

# pop3 without ssl
# $authhost="{}";
# $user="";

# goggle with pop3 or imap
# $authhost="{}";
# $authhost="{}";
# $user="";

$user="username like above";

if (
$mbox=imap_open$authhost$user$pass ))
        } else

2010-01-31 10:16:42
Make sure your PHP is enabled with imap via the phpinfo() function

'--with-imap-dir=/opt/lampp' '--with-imap-ssl' '--with-imap=/opt/lampp'


IMAP c-Client Version 2007e
SSL Support Yes

I noticed that my apache script was working but my cli script was not. Turns out my php cli executable didn't have imap setup so I had to use another php cli executable.
2010-03-02 21:39:57
// You can break out the variables for $mailserver, $port, $user and
// $pass without passing brackets into functions this way. Be sure to use
// the dots to append connection strings, ie "stuff". $variable ."STUFF"
// otherwise will go to imap_open with wrong variable type. :)

if (
$mbox=imap_open"{" $mailserver ":" $port "}INBOX"$user$pass ))
 {  echo 
$check imap_mailboxmsginfo($mbox);
"Date: "     $check->Date    "<br />\n" ;
"Driver: "   $check->Driver  "<br />\n" ;
"Unread: "   $check->Unread  "<br />\n" ;
"Size: "     $check->Size    "<br />\n" ;
 } else { exit (
"Can't connect: " imap_last_error() ."\n");  echo "FAIL!\n";  };
2010-08-25 15:34:45
if u ever get something like this:

Notice: Unknown: IMAP protocol error: Invalid system flag in Store command (errflg=2) in Unknown on line 0

Notice: Unknown: Invalid system flag in Store command (errflg=2) in Unknown on line 0

This Error occurs if u want to set a flag 2 times. Just check ur manually flag Settings.

2010-08-26 02:34:04
"Couldn't open stream {}INBOX" 

Solved by only replacing with localhost, php and IMAP server both in same machine, not through Proxy or anything. Weird!
2010-09-07 15:32:36
"{}INBOX" 'login' 'password' );

Got this error:
"Couldn't open stream {}INBOX" 

Solved by adding the flag "novalidate-cert":
"{}INBOX" 'login' 'password' );

2010-11-09 19:23:58
For those having issues with Gmail (my problem was : "too many login failures" on a webserver, but no problem on localhost..), instead of opening with :

$inbox = imap_open($hostname,$username,$password,NULL,1) or die('Cannot connect to Gmail: ' . imap_last_error());

Use :

$inbox = imap_open($hostname,$username,$password,NULL,1) or die('Cannot connect to Gmail: ' . print_r(imap_errors()));

You will be able to see the full list of errors that happened, and hopefully it will guide you to an answer.
In my case, Google wanted me to unlock my account by typing in a captcha. But this error wasn't clearly shown through imap_last_error().

2011-05-02 16:05:14
I managed to use this function against Exchange 2010 without recompiling to disable kerberos

It's important to me that php installs per the standard package (yum install php)

Exchange 2010 triggers kerberos in php, and you require the kinit thing (search around google for "imap_open kinit exchange 2010" and you will find this)

To get it working I had to:
1. setup the krb5.conf file correctly
2. do a kinit username@DOMAIN.DOM with a valid username / password
3. rename the ticket file to reflect the user id of apache (usually 48)
4. fix ownership
   chown apache.apache /tmp/krb5cc_48

but the exchange server will use the kerberos ticket and not the username password - unless you use ssl


$imap_pass "password";
$imap_server "{w2010kExchangeServer:993/novalidate-cert/ssl}";

$mbox imap_open("{$imap_server}INBOX"$imap_user$imap_pass);

$sorted_mbox imap_sort($mboxSORTDATE0);
$totalrows imap_num_msg($mbox);

$startvalue 0;
    while (
$startvalue $totalrows) {

$headers imap_fetchheader($mbox$sorted_mbox$startvalue ] );
$subject = array();
preg_match_all('/^Subject: (.*)/m'$headers$subject);
$subject[1][0] . "\n";

One small step for php / exchange, one Giant leap for David  ....
2011-05-10 08:28:10
If your connection is too slow, try it with port and without domain.

//Normal connection
$mailbox imap_open("{SERVER}INBOX"$username$password);

//Faster connection
$mailbox imap_open("{SERVER:143}INBOX"$username$password);

//Very slow connection
$mailbox imap_open ("{SERVER.DOMAIN}INBOX""DOMAIN/".$username$password);
2011-06-13 10:12:05
Since Version 5.3.2 there's a 6th parameter available to disable authentication with GSSAPI or NTLM:

imap_open("{w2010ExchangeServer:993/imap/ssl}"$user$passwordNULL1, array('DISABLE_AUTHENTICATOR' => 'GSSAPI'));

This solves the problem with Exchange 2010 for me. As a reference see
2011-07-01 09:41:06
If you are accessing a local mailbox file, i.e. imap_open('/var/mail/www-data', '', ''), you may be restricted in what files you can access.

If PHP IMAP was compiled with the restrictBox option (which I believe most packages are these days), you can only access files relative to $HOME. Paths starting with '/' or '../' will be rejected.
2011-12-12 10:20:05
Thank you for this completely non-obvious tip, which solved the problem for me. To help search engines find this tip: the resulting error is "PHP Warning:  imap_open(): Couldn't open stream /home/your-directory/the-file-name in the-script-name on line XX"

If you include:  $str = imap_errors();  echo("imap_errors():\n");  print_r($str);
you will see:
    [0] => Can't open mailbox /home/your-directory/the-file-name: no such mailbox
2012-02-07 16:50:30
One of the issues with gmail IMAP SSL authentication is related to Google's account security.

Once you get the login error once, sign out of all your google accounts. Then, visit this link:

Log in with the account you're attempting to access via imap.

Follow the steps and you'll then be able to login in to gmail with php imap.

It's visually shown here:
2014-01-10 20:35:21
If your opening and closing of connection is too slow, the issue might be with DNS servers. You should add the IP addresses of IMAP servers to your hosts file.

It's explained here in more details
2014-04-22 04:50:40
 validate SSL certificate does not support Subject Alternative Name (SAN) certificate. It only validate against the Subject/Common name.
2014-05-22 07:14:27
Do not bother using "/debug" flag in $mailbox or OP_DEBUG in $options. They do not do anything.

When you set either one, the underlying IMAP c-client library will gather protocol debugging data and pass it back to PHP.
However, the debug handler defined by PHP is an empty function, it doesn't do anything.

So unless you're using a customized version of the IMAP extension that does something with that handler (mm_dlog), there is no point using "/debug" or OP_DEBUG.
2014-06-01 05:09:02
Subfolders of INBOX have to be seperate by dot like this: 'INBOX.test'
$mailbox = '{}INBOX.test'
2014-08-29 11:15:40
The error: Unknown: Mailbox is empty (errflg=1) in Unknown on line 0
appears when:

1)  use imap_open to connect 
2) then use imap_search ALL to retrieve emails

but there are no messages available. To avoid this error, check first the number of messages in a mailbox using imap_status. Only if there are messages available then you can use the imap_search.
2015-01-07 15:57:20

I was struggling with the Gmail Imap/pop connection. It keeps saying too many failed login connections were made.

Thing I did:
Clicked "Turn on"
> worked!

So last step could be used but remember your account will be at a certain security risk. Anyway it comes in handy to develop...
2015-03-29 22:14:36
An old archived 2006 PHP script to retrieve IMAP POP3 email into a MySQL database and as files is at:
2015-10-07 12:45:00
If you get slow imap4/pop3 authentication step 
i.e. 5-10 sec just for response, maybe you are connecting to an imap server which is advertising GSSAPI auth mechanism.
Martin Eckardt note could help to speed it up.
imap_open("{imap server with GSSAPI :993/imap/ssl}"$user$passwordNULL1, array('DISABLE_AUTHENTICATOR' => 'GSSAPI'));

Disable GSSAPI if you dont use it.
If your imap/pop server is Dovecot
auth_mechanisms = plain login gssapi
-> auth_mechanisms = plain login
2016-03-18 17:36:22
This code demonstrates features that are not well documented at this time. The main feature is that the selected mailbox in imap_open (or reopen)  and the specified mailbox in other imap functions are unrelated.  It has been tested with Gmail and with a Dovecot IMAP server.  The mailbox separator depends on the server. Gmail: "/"  Dovecot: "."  If you want to test with Gmail, you need to turn on "Access for less secure apps" in your account.
// Change these.
$server    "{}"
$email     ""
$password  "password";
// The code assumes that the folders Test/Sub1/Sub11, etc. exist. 
$selected  "{$server}Test/Sub1/Sub12";
$conn      imap_open($selected$email $password);

// This returns the $specified mailbox and its sub mailboxes, 
  // even if the $specified mailbox is outside the $selected mailbox. 
$specified "{$server}Test/Sub1"
$boxes     imap_list($conn$specified '*');
// This appends the message in the $specified mailbox. 
  // It ignores the $selected mailbox. 
"Subject: test\r\n"
"this is a test message, please ignore\r\n");

// This changes the $selected mailbox
$selected "{$server}Test/Sub1"

// This moves a message from the $selected to the $specified mailbox
  // In this case, the specified mailbox does not include the server. 
imap_mail_move ($conn "1" "Test"); 
// If you executed this code with a real IMAP server, 
  // the message is now in the Test mailbox !
2017-03-11 21:02:22
Function to test most of the possible options of a connection:

function imapConfig($options, $i=0, $till = array()) {
            return $till;
            $till[] = '';
        $opt = $options[$i];
        $new = array();
        foreach($till as $t) {
            foreach($opt as $o) {
                    $new[] = $t;
                    $new[] = $t.'/'.$o;
        return imapConfig($options, $i+1, $new);

function imap_test($server, $port, $dir, $username, $passw) {
        $options = array();
        //$options[] = array('debug');
        $options[] = array('imap', 'imap2', 'imap2bis', 'imap4', 'imap4rev1', 'pop3'); //nntp
        $options[] = array('', 'norsh');
        $options[] = array('', 'ssl');
        $options[] = array('', 'validate-cert', 'novalidate-cert');
        $options[] = array('', 'tls', 'notls');
        $configOptions = imapConfig($options);
        foreach($configOptions as $c) {
            $mbox = @imap_open("{".$server.":".$port.$c."}".$dir, $username, $passw);
            echo "<b>{".$server.":".$port.$c."}".$dir."</b> ... ";
            if (false !== $mbox) {
                echo '<span style="color: green"> success</span>';
            else {
                echo '<span style="color: red"> failed</span>';
            echo '<br>';

imap_test('', 143, 'INBOX', 'username', 'pwd');
2018-01-11 08:28:19
On Windows, this function does not use certificates in directories listed by openssl_get_cert_locations(): it use system's certificates store. If you want to use a certificate signed by a test authority, you must add root certificate of your test authority to Window's certificates store.
2018-11-03 20:18:22
If you get Kerberos errors like:
« Notice: Unknown: Kerberos error: Credentials cache file '/tmp/krb5cc_0123' not found (try running kinit) ».

Try to add as a $param:

imap_open('{mail.domain.tld:993/imap/ssl}' 'username' 'password'null1, array('DISABLE_AUTHENTICATOR' => 'GSSAPI'));
2018-11-18 09:35:33

    Поддержать сайт на родительском проекте КГБ