PHP Conference Kansai 2025

imap_open

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_openAbre un flujo IMAP hacia un buzón de correo

Descripción

imap_open(
    string $mailbox,
    string $user,
    string $password,
    int $flags = 0,
    int $retries = 0,
    array $options = []
): IMAP\Connection|false

Abre un flujo IMAP hacia el buzón de correo mailbox.

Esta función también puede ser utilizada para abrir flujos en servidores POP3 y NNTP, pero algunas funciones y características solo están disponibles con servidores IMAP.

Parámetros

mailbox

Un nombre de buzón de correo está compuesto por una dirección de servidor y una dirección de buzón en ese servidor. La palabra reservada INBOX representa el buzón de correo del usuario actual. Los nombres de buzones de correo que contienen caracteres especiales (fuera del espacio ASCII) deben ser codificados con imap_utf7_encode().

Advertencia

El paso de datos no confiables a este parámetro es inseguro, a menos que imap.enable_insecure_rsh esté inhabilitado.

La dirección del servidor, entre llaves '{' y '}', está compuesta por el nombre del servidor o su dirección IP, una especificación de protocolo (comenzando por '/') y un puerto opcional (especificado con ':').

Esta parte es obligatoria en los parámetros del buzón de correo.

Todos los nombres que comienzan con { son nombres remotos y tienen la forma "{" nombre_sistema_remoto [":" puerto] [flags] "}" [nombre_buzon] donde :

  • remote_system_name : Nombre de dominio de Internet o una dirección IP de servidor entre comillas.
  • puerto : número de puerto TCP (opcional), el valor por defecto es el valor del puerto para este servicio.
  • flags : opciones, ver la tabla siguiente.
  • mailbox_name : nombre del buzón remoto, por defecto : INBOX

Flags opcionales para los nombres
Flag Descripción
/service=service servicio para el acceso al buzón, por defecto : "imap"
/user=user nombre del usuario remoto para la identificación en el servidor
/authuser=user usuario remoto de identificación; si se especifica, este será el nombre del usuario cuya contraseña se utiliza (e.g. administrador)
/anonymous acceso remoto anónimo
/debug la telemetría de registro del protocolo en los logs de depuración de la aplicación
/secure no transmite una contraseña en claro a través de la red
/imap, /imap2, /imap2bis, /imap4, /imap4rev1 equivalente a /service=imap
/pop3 equivalente a /service=pop3
/nntp equivalente a /service=nntp
/norsh no utilizar rsh o ssh para establecer una sesión de pre identificación IMAP
/ssl utiliza Secure Socket Layer para cifrar la sesión
/validate-cert valida los certificados desde el servidor TLS/SSL (es el comportamiento por defecto)
/novalidate-cert no valida los certificados desde el servidor TLS/SSL, necesario si el servidor utiliza certificados autofirmados
/tls fuerza el uso de start-TLS para cifrar la sesión y rechaza las conexiones a los servidores que no lo soportan
/notls no utiliza start-TLS para cifrar la sesión, incluso con los servidores que lo soportan
/readonly solicita acceso de solo lectura en el buzón (solo IMAP; ignorado en NNTP, y un error con SMTP y POP3)

user

El nombre de usuario

password

La contraseña asociada con el usuario user

flags

flags es una máscara de bits, que puede tomar uno o varios de los siguientes valores :

  • OP_READONLY : Abre un buzón de correo en modo de solo lectura
  • OP_ANONYMOUS : No utilizar, o modificar el fichero .newsrc para las noticias (solo NNTP)
  • OP_HALFOPEN : Para los nombres IMAP y NNTP, abre una conexión pero no abre un buzón de correo.
  • CL_EXPUNGE : Elimina automáticamente el buzón de correo de la lista, al finalizar el flujo (ver también imap_delete() y imap_expunge())
  • OP_DEBUG : negociaciones de depuración del protocolo
  • OP_SHORTCACHE : Caché corta (elt solamente)
  • OP_SILENT : No transmitir los eventos (uso interno)
  • OP_PROTOTYPE : Devuelve el prototipo del controlador
  • OP_SECURE : No realizar identificaciones no seguras

retries

El número máximo de intentos de conexión.

options

Parámetros de conexión; las claves pueden ser utilizadas para definir uno o varios parámetros de conexión :

  • DISABLE_AUTHENTICATOR - Desactiva las propiedades de autenticación

Valores devueltos

Devuelve una instancia de IMAP\Connection en caso de éxito, o false en caso de error.

Historial de cambios

Versión Descripción
8.1.0 Ahora devuelve una instancia de IMAP\Connection ; anteriormente, un recurso era devuelto.

Ejemplos

Ejemplo #1 Diferentes usos de imap_open()

<?php
// Para conectarse a un servidor IMAP funcionando en el puerto 143 de la
// máquina local, haga esto :
$mbox = imap_open("{localhost:143}INBOX", "user_id", "password");

// Para conectarse a un servidor POP3 funcionando en el puerto 110 del
// servidor local, haga esto :
$mbox = imap_open ("{localhost:110/pop3}INBOX", "user_id", "password");

// Para conectarse a un servidor SSL IMAP o POP3, añada /ssl
// después de la especificación del protocolo :
$mbox = imap_open ("{localhost:993/imap/ssl}INBOX", "user_id", "password");

// Para conectarse a un servidor SSL IMAP o POP3 con un certificado autofirmado
// añada /ssl/novalidate-cert después del protocolo :
$mbox = imap_open ("{localhost:995/pop3/ssl/novalidate-cert}", "user_id", "password");

// Para conectarse a un servidor NNTP que funciona en
// el puerto 119 de la máquina local se puede utilizar el comando:
$nntp = imap_open ("{localhost:119/nntp}comp.test", "", "");

// Para conectarse a un servidor remoto, reemplace "localhost" por
// el nombre o la dirección IP de la máquina.
?>

Ejemplo #2 Ejemplo con imap_open()

<?php
$mbox
= imap_open("{imap.example.org:143}", "username", "password");

echo
"<h1>Buzones de correo</h1>\n";
$folders = imap_listmailbox($mbox, "{imap.example.org:143}", "*");

if (
$folders == false) {
echo
"Llamada fallida<br />\n";
} else {
foreach (
$folders as $val) {
echo
$val . "<br />\n";
</foreach>
}

echo
"<h1>Encabezados en INBOX</h1>\n";
$headers = imap_headers($mbox);

if (
$headers == false) {
echo
"Llamada fallida<br />\n";
} else {
foreach (
$headers as $val) {
echo
$val . "<br />\n";
}
}

imap_close($mbox);
?>

Ver también

add a note

User Contributed Notes 19 notes

up
28
php at dsgvoseidank dot de
2 years ago
Google dropped the support of user/password authentication as of 30 may 2022.
imap_open can not be used anymore, without the support of xoauth2.
https://support.google.com/accounts/answer/6010255

There is a ToDo from 2020 that didn't make it.
https://wiki.php.net/todo/ext/imap/xoauth2

The only way is to switch to a third party lib. "php-imap"
This is so sad.
up
9
neekToO
2 years ago
To reply to "dsgvoseidank" saying it doesnt work anymore with Gmail :

As today 26 august 2022 it is still working but you need to use google parameters to generate a password for your app on a 2FA account
up
13
kay at rrr dot de
15 years ago
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.

Kay

<?php

#######
# 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";

######
# web.de pop3 without ssl
# $authhost="{pop3.web.de:110/pop3/notls}";
# $user="kay.marquardt@web.de";

#########
# goggle with pop3 or imap
# $authhost="{pop.gmail.com:995/pop3/ssl/novalidate-cert}";
# $authhost="{imap.gmail.com:993/imap/ssl/novalidate-cert}";
# $user="username@gmail.com";

$user="username like above";
$pass="yourpass";

if (
$mbox=imap_open( $authhost, $user, $pass ))
{
echo
"<h1>Connected</h1>\n";
imap_close($mbox);
} else
{
echo
"<h1>FAIL!</h1>\n";
}

?>
up
12
jeff at newscloud dot com
11 years ago
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:
http://www.google.com/accounts/DisplayUnlockCaptcha

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:
http://jeffreifman.com/filtered-open-source-imap-mail-filtering-software-for-php/configuring-gmail/
up
13
guilherme dot geronimo at gmail dot com
14 years ago
Using:
<?php
imap_open
( "{server.example.com:143}INBOX" , 'login' , 'password' );
?>

Got this error:
"Couldn't open stream {server.example.com:143}INBOX"

Solved by adding the flag "novalidate-cert":
<?php
imap_open
( "{server.example.com:143/novalidate-cert}INBOX" , 'login' , 'password' );
?>

=D
up
6
hashampel at yahoo dot de
10 years ago
Subfolders of INBOX have to be seperate by dot like this: 'INBOX.test'
$mailbox = '{example.example.com:143/imap/novalidate-cert}INBOX.test'
up
4
dominic_mayers at yahoo dot com
8 years ago
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.

<?php
// Change these.
$server = "{imap.gmail.com:993/imap/ssl/novalidate-cert}";
$email = "example@gmail.com";
$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 , '*');
print_r($boxes);

// This appends the message in the $specified mailbox.
// It ignores the $selected mailbox.
imap_append($conn, $specified
, "From: me@example.com\r\n"
. "To: you@example.com\r\n"
. "Subject: test\r\n"
. "\r\n"
. "this is a test message, please ignore\r\n");

// This changes the $selected mailbox
$selected = "{$server}Test/Sub1";
imap_reopen($conn, $selected);

// 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");
imap_expunge($conn);
imap_close($conn);
// If you executed this code with a real IMAP server,
// the message is now in the Test mailbox !
?>
up
4
me at achronos dot ca
10 years ago
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.
up
1
LANGE.LUDO
6 years ago
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:
<?php array('DISABLE_AUTHENTICATOR' => 'GSSAPI') ?>

eg.
<?php
$imap_stream
= imap_open('{mail.domain.tld:993/imap/ssl}' , 'username' , 'password', null, 1, array('DISABLE_AUTHENTICATOR' => 'GSSAPI'));
?>
up
1
Lisboa
10 years ago
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.
up
2
Anonymous
7 years ago
Function to test most of the possible options of a connection:

function imapConfig($options, $i=0, $till = array()) {
if(sizeof($options)==$i)
return $till;

if(sizeof($till)==0)
$till[] = '';

$opt = $options[$i];
$new = array();
foreach($till as $t) {
foreach($opt as $o) {
if(strlen($o)==0)
$new[] = $t;
else
$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('mail.server.de', 143, 'INBOX', 'username', 'pwd');
up
2
liamr at umich dot edu
20 years ago
To authenticate using kerberos V / GSSAPI, you might need to add "user=" to the connection string.. eg:

$mbox = imap_open( "\{imap.example.com:143/imap/notls/user=" . $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.
up
2
shaikh_zaid at yahoo dot com
19 years ago
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="{mail.domain.com:143/imap/notls}";
or
$mailbox="{mail.domain.com:110/pop3/notls}"; This works...

Some mail server requires you to provide username@domain.com so you can always use. user@doamin.com

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

Some server may ask for username as "user=user@domain.com"

:)
up
3
frederik at roal dot no
23 years ago
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() )
up
2
rvarkelen AT hortimax.nl
21 years ago
In order to make a IMAP connection to a Microsoft Exchange Server 5.5, I used this connection-string :

<?php
if(imap_open ("{192.168.1.6:143/imap}Inbox", "DOMAIN/USERNAME/ALIAS", "PASSWORD"))
{
echo
'Connection success!';
}
else
{
echo
'Connection failed';
}
?>

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

Regards
up
2
brojann at netscape dot com
23 years ago
You can do

<? $foo = imap_errors(); ?>

to clear unwanted warning messages like 'Mailbox is empty'
up
1
m dot stoel at cyberkinetic dot nl
20 years ago
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..
up
1
jab_creations at yahoo dot com
3 months ago
I was receiving the following error while trying to add the /secure flag and verify that the /ssl flag was using TLS 1.2 instead of the very outdated SSL protocol:

PHP Request Shutdown: Can't do secure authentication with this server (errflg=2)

I ended up having to call my host to get help as there were literally only five pages in the search engines with the error. The mailbox configuration:

Before / incorrect / error:
<?php
$server_folder
= '{mail.example.com:993/imap/ssl/secure}';
?>

After / correct / connected:
<?php
$server_folder
= '{mail.example.com:993/ssl/imap/secure}';
?>

The /ssl and /imap flags were not in the correct order. Here is the thing, the flags listed above do NOT mention a strict chronological order of flags and are themselves no listed in the chronological order. So that right there is a bug report needed for the documentation though hopefully this comment will spare someone the aggravation for seemingly random errors. Good luck!
up
0
Stefano
2 years ago
``There is one thing I learned over the years,
if someone says: "it's not possible", prove them wrong.`` ~ Stefano Kocka '99

test date: 2022-11-20
php version: PHP 8.0.10 (cli)
extension=imap
extension=openssl

imap: IMAP c-Client Version => 2007f
SSL Support => enabled

https://support.google.com/accounts/answer/185833?hl=en

<?php
$cnx
= '{imap.gmail.com:993/imap/ssl/readonly}';
$mbox = imap_open($cnx, 'user@gmail.com', 'MyAppPassword');
$folders = imap_listmailbox($mbox, $cnx, '*');
print_r($folders);
/*
Array
(
[0] => {imap.gmail.com:993/imap/ssl/readonly}INBOX
[1] => {imap.gmail.com:993/imap/ssl/readonly}LABEL1
[2] => {imap.gmail.com:993/imap/ssl/readonly}LABEL2
[3] => {imap.gmail.com:993/imap/ssl/readonly}Queue
[4] => {imap.gmail.com:993/imap/ssl/readonly}[Gmail]/All
[5] => {imap.gmail.com:993/imap/ssl/readonly}[Gmail]/Drafts
[6] => {imap.gmail.com:993/imap/ssl/readonly}[Gmail]/Sent
[7] => {imap.gmail.com:993/imap/ssl/readonly}[Gmail]/Spam
[8] => {imap.gmail.com:993/imap/ssl/readonly}[Gmail]/Starred
[9] => {imap.gmail.com:993/imap/ssl/readonly}[Gmail]/Trash
)
*/
?>
Kind regards
To Top