imap_open
(PHP 4, PHP 5)
imap_open — Open an IMAP stream to a mailbox
Описание
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.
Список параметров
- mailbox
-
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) - username
-
The user name
- password
-
The password associated with the username
- options
-
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
- n_retries
-
Number of maximum connect attempts
Возвращаемые значения
Returns an IMAP stream on success or FALSE on error.
Список изменений
Версия | Описание |
---|---|
5.2.0 | n_retries added |
Примеры
Пример #1 Different use of imap_open()
<?php
// 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
<?php
$mbox = imap_open("{imap.example.org:143}", "username", "password");
echo "<h1>Mailboxes</h1>\n";
$folders = imap_listmailbox($mbox, "{imap.example.org:143}", "*");
if ($folders == false) {
echo "Call failed<br />\n";
} else {
foreach ($folders as $val) {
echo $val . "<br />\n";
}
}
echo "<h1>Headers in INBOX</h1>\n";
$headers = imap_headers($mbox);
if ($headers == false) {
echo "Call failed<br />\n";
} else {
foreach ($headers as $val) {
echo $val . "<br />\n";
}
}
imap_close($mbox);
?>
- PHP Руководство
- Функции по категориям
- Индекс функций
- Справочник функций
- Расширения для работы с почтой
- IMAP, POP3 и NNTP
- imap_8bit
- imap_alerts
- imap_append
- imap_base64
- imap_binary
- imap_body
- imap_bodystruct
- imap_check
- imap_clearflag_full
- imap_close
- imap_create
- imap_createmailbox
- imap_delete
- imap_deletemailbox
- imap_errors
- imap_expunge
- imap_fetch_overview
- imap_fetchbody
- imap_fetchheader
- imap_fetchmime
- imap_fetchstructure
- imap_fetchtext
- imap_gc
- imap_get_quota
- imap_get_quotaroot
- imap_getacl
- imap_getmailboxes
- imap_getsubscribed
- imap_header
- imap_headerinfo
- imap_headers
- imap_last_error
- imap_list
- imap_listmailbox
- imap_listscan
- imap_listsubscribed
- imap_lsub
- imap_mail_compose
- imap_mail_copy
- imap_mail_move
- imap_mail
- imap_mailboxmsginfo
- imap_mime_header_decode
- imap_msgno
- imap_num_msg
- imap_num_recent
- imap_open
- imap_ping
- imap_qprint
- imap_rename
- imap_renamemailbox
- imap_reopen
- imap_rfc822_parse_adrlist
- imap_rfc822_parse_headers
- imap_rfc822_write_address
- imap_savebody
- imap_scan
- imap_scanmailbox
- imap_search
- imap_set_quota
- imap_setacl
- imap_setflag_full
- imap_sort
- imap_status
- imap_subscribe
- imap_thread
- imap_timeout
- imap_uid
- imap_undelete
- imap_unsubscribe
- imap_utf7_decode
- imap_utf7_encode
- imap_utf8
Коментарии
You can do
<? $foo = imap_errors(); ?>
to clear unwanted warning messages like 'Mailbox is empty'
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() )
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
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.
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..
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"
:)
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";
}
?>
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
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/
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.
Subfolders of INBOX have to be seperate by dot like this: 'INBOX.test'
$mailbox = '{example.example.com:143/imap/novalidate-cert}INBOX.test'
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.
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 !
?>
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');
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'));
?>
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.
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
``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