Deprecated: The each() function is deprecated. This message will be suppressed on further calls in /home/zhenxiangba/zhenxiangba.com/public_html/phproxy-improved-master/index.php on line 456
PHP: imap_open - Manual
[go: Go Back, main page]

PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

imap_ping" width="11" height="7"/> <imap_num_recent
Last updated: Mon, 05 Feb 2007

view this page in

imap_open

(PHP 4, PHP 5)

imap_open — メールボックスへの IMAP ストリームをオープンする

説明

resource imap_open ( string mailbox, string username, string password [, int options] )

mailbox への IMAP ストリームをオープンします。

この関数は、POP3 や NNTP サーバへのストリームをオープンする際にも使用可能です。 しかし、いくつかの関数および機能は IMAP サーバでしか利用できません。

パラメータ

mailbox

メールボックス名(mailbox)は、サーバ名の部分と使用するサーバにおける メールボックスへのパスから構成されます。特別な名前 INBOX は、 カレントユーザの個人メールボックスを意味します。 ASCII 空間で出力可能な文字以外の外国文字を含むメールボックス名は imap_utf7_encode() でエンコードする必要があります。

サーバ部は '{' および '}' で括られ、サーバ名または IP アドレス、オプションの ':' から始まるポート指定子、('/' で始まる)オプションのプロトコル指定子 から構成されます。

サーバ部は、全ての mailbox パラメータで必須です。

{ で始まる名前はすべてリモート名で、 "{" remote_system_name [":" port] [flags] "}" [mailbox_name] のような形式となります。

  • remote_system_name - Internet ドメイン名 あるいは括弧でかこまれたサーバの IP アドレス。
  • port - オプションの TCP ポート番号。デフォルトは そのサービスのデフォルトポート。
  • flags - オプションのフラグ。以下の表を参照ください。
  • mailbox_name - リモートメールボックス名。デフォルトは INBOX 。

表 140. オプションのフラグ名

フラグ説明
/service=serviceメールボックスにアクセスするサービス。デフォルトは "imap" 。
/user=userサーバへのログイン時のユーザ名。
/authuser=userリモートの認証ユーザ。指定されていた場合は、このユーザのパスワードが 認証に使用されます(例: administrator)。
/anonymous匿名ユーザとしてアクセスします。
/debugプロトコルの通信内容をアプリケーションのデバッグログに記録します。
/secureネットワーク越しにプレーンテキストのパスワードを送信しません。
/imap, /imap2, /imap2bis, /imap4, /imap4rev1/service=imap と同じです。
/pop3/service=pop3 と同じです。
/nntp/service=nntp と同じです。
/norsh事前に認証済みの IMAP セッションを確立する際に、rsh や ssh を使用しません。
/sslセッションの暗号化に SSL(Secure Socket Layer)を使用します。
/validate-certTLS/SSL サーバの証明書を検証します(デフォルトの挙動です)。
/novalidate-certTLS/SSL サーバの証明書を検証しません。サーバが自己証明の 証明書を使用している際に必要となります。
/tlsセッションの暗号化に start-TLS の使用を強制し、それを サポートしていないサーバとの接続を拒否します。
/notlsたとえサーバがそれをサポートしていたとしても、 セッションで start-TLS による暗号化を使用しません。
/readonly読み込み専用でのメールボックスのオープンを要求します(IMAP のみ。 NNTP では無視され、SMTP および POP3 ではエラーとなります)。


username

ユーザ名。

password

username のパスワード。

options

options はビットマスクであり、以下の組み合わせとなります。

  • OP_READONLY - メールボックスを読み込み専用でオープンします。
  • OP_ANONYMOUS - news に関して .newsrc を使用せず、更新もしません(NNTP のみ)。
  • OP_HALFOPEN - IMAP 及び NNTP 名について、 接続をオープンしますがメールボックスはオープンしません。
  • CL_EXPUNGE - メールボックスを閉じる際に、 自動的にメールボックスを削除します(imap_delete() および imap_expunge() も参照ください)。
  • OP_DEBUG - プロトコルネゴシエーションをデバッグします。
  • OP_SHORTCACHE - 短い(elt-only)キャッシングを行います。
  • OP_SILENT - イベントを受信しません(内部で使用します)。
  • OP_PROTOTYPE - ドライバのプロトタイプを返します。
  • OP_EXPUNGE - リサイクルストリームを削除します。
  • OP_SECURE - セキュアでない認証を行いません。

返り値

成功した場合は IMAP ストリームを、失敗した場合は FALSE を返します。

例 962. imap_open() のさまざまな使用例

<?php
// ローカルマシンのポート 143 で稼動している IMAP サーバに接続するには
// 以下のようにします。
$mbox = imap_open("{localhost:143}INBOX", "user_id", "password");

// ローカルマシンのポート 110 で稼動している POP3 サーバに接続するには、
$mbox = imap_open ("{localhost:110/pop3}INBOX", "user_id", "password");

// SSL IMAP あるいは POP3 サーバに接続するには、プロトコル指定のあとに
// /ssl を追加します。
$mbox = imap_open ("{localhost:993/imap/ssl}INBOX", "user_id", "password");

// 自分でサインした証明書で SSL IMAP あるいは POP3 サーバに接続するには、
// プロトコル指定のあとに /ssl/novalidate-cert を追加します。
$mbox = imap_open ("{localhost:995/pop3/ssl/novalidate-cert}", "user_id", "password");

// ローカルマシンのポート 119 で稼動している NNTP サーバに接続するには、
$nntp = imap_open ("{localhost:119/nntp}comp.test", "", "");
// リモートサーバに接続する際は、"localhost" を接続したいサーバの
// 名前または IP アドレスに置き換えます。
?>

例 963. imap_open() の例

<?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
"コールが失敗しました<br />\n";
} else {
   foreach (
$folders as $val) {
       echo
$val . "<br />\n";
   }
}

echo
"<h1>INBOX のヘッダ</h1>\n";
$headers = imap_headers($mbox);

if (
$headers == false) {
   echo
"コールが失敗しました<br />\n";
} else {
   foreach (
$headers as $val) {
       echo
$val . "<br />\n";
   }
}

imap_close($mbox);
?>

参考

imap_close()



add a note add a note User Contributed Notes
imap_open
Amit
12-Sep-2006 02:25
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.

http://bugs.php.net/bug.php?id=36496&edit=1
shaikh_zaid at yahoo dot com
11-Jul-2006 10:20
I have seem people using "." within imap_open. I would suggest not to use "." operator for concatanation just format the strings separtately from imap_open.
shaikh_zaid at yahoo dot com
05-Apr-2006 03:55
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"

:)
admin at webes dot es
04-Feb-2006 08:03
Just a note concerning "empty mailbox" error in case it helps somebody out there.

whenever the mailbox was empty, I kept on getting errors of the type "Warning: imap_header()..." as there were no messages to read headers of.

Reading through here I sussed that the first entry in "imap_errors()" gives you a clear "Mailbox is empty" if this is the case.

Knowing this, I can now code for not continuing with headers, etc if the mailbox is empty, something like:

$foo = imap_errors();
if($foo[0] !== "Mailbox is empty"){check headeres etc... };

Cheers
Simon F
13-Dec-2005 11:52
I had to use /novalidate-cert

strace php test.php on the CLI proves invalauble to work out exaclty which set of options I needed.
admin at sellchain dot com
09-Dec-2005 01:36
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.

Http://www.sellchain.com/phPOP3/phPOP3.txt

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!

Enjoyz;)
admin at sellchain dot com
08-Dec-2005 07:54
Regarding PHP.net's CONNECT TO POP3 SERVER command above, I have a modification for some people that might help..

For my mail server, it only accepts mail.server.com types of addresses, so if you are having trouble, try using this method:

$mailbox = imap_open ("{mail.YOURSITE.com:110/pop3}INBOX", "YOURUSERNAME", "YOURPASSWORD");
03-Aug-2005 11:13
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...
avizion at relay dot dk
12-May-2005 07:30
For FreeBSD users...

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

mail/php5-imap
security/php5-openssl

Cheers :)

 - avizion
MaartenKoops.NL
10-May-2005 02:56
Somtimes when you can't connect whit IMAP of POP3 use as username (when connecting like imap_open) user@domain.td.

This workt fine with me. Greetings, Maarten Koops.
m dot stoel at cyberkinetic dot nl
28-Apr-2005 02:50
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..
thushara dot perera at unilink dot lk
26-Feb-2005 02:19
Warning: imap_open() [function.imap-open]: Couldn't open stream {xx.xx.x.xxx:143}INBOX

correct the connection string as :
{xx.xx.x.xxx:143/notls}INBOX
info at infosoporte.com
25-Feb-2005 11:14
I can connect to my email server with no problem using regular usernames and passwords but.... in my server the usernames are long.. like name.surname1.surname2@subdomain.domain.com , 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());

returns

Too many login failures

when the username is over 40 chars. Just remember that if you plan to use long usernames.
elizar.palad
14-Dec-2004 03:22
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...

poploginname@domain.com

not

emailaddress@domain.com..
gasaunde at vcu dot edu
14-Dec-2004 04:35
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
cg at compile dot ch
20-Sep-2004 09:16
If you use cyrus, passwords shadow via saslauth, check this:

> =====IMAPD.conf======
> configdirectory:        /var/imap
> partition-default:      /var/spool/imap
> sievedir:              /var/imap/sieve
> tls_cert_file:          /etc/cyrusimapd/server.crt
> tls_key_file:          /etc/cyrusimapd/server.key
> admins:                cyrus
> hashimapspool:          yes
> allowanonymouslogin:    no
> allowplaintext:        yes
> unixhierarchysep:      0
> servername:            mail.garage.com
> sasl_pwcheck_method:    saslauthd
> mech_list: plain login

Make this

sasl_mech_list: plain login
liamr at umich dot edu
30-Jun-2004 08:40
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.
nmmm at nmmm dot nu
23-Jun-2004 02:37
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)

source:
http://aspn.activestate.com/ASPN/CodeDoc/Mail-Cclient/Cclient.html
greenie at oddpost dot com
19-May-2004 08:01
I was trying to use the example code above to connect to a POP mailbox, but no matter how I arranged the elements of the mailbox name, the script hung on the imap_open() command, and never came back. No error message, no timeout - the browser just spins. Strangely, the same syntax worked just fine for a local mailbox.

I did some Googling, and it looks like many others are having the same problem. Finally, I got it to work using the following syntax:

$mbox = imap_open( "{yourmailserver.com/pop3:110/notls}INBOX", "username", "password" );

Note that the port information comes AFTER the "/pop3" bit, which is contrary to the examples given above. I have no idea if this is correct or not, but it works for me :)

FWIW, I'm using PHP 4.1.2.

Also - others here have suggested using the "/notls" part, but haven't explained what it does: it explicitly requests a non-SSL connection.
rleroy at avantages dot com
01-May-2004 02:15
The only way I made a connection to my IMAP server was using the following syntax ->

MAILSERVER="{imap.example.com:143/imap/notls}";

and not

MAILSERVER="{imap.example.com:143}";

That was for a REDHAT 7.1 imapd daemon.

I searched a lil bit before figuring this one out ;-)

rleroy@avantages.com
rvarkelen AT hortimax.nl
14-Jan-2004 08:03
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
marshall /AT\ pacdemon.org
04-Nov-2003 04:50
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 your.pop.host.com 110
   +OK POP3 your.pop.host.com 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 your.imap.host.com 143
   * OK [CAPABILITY IMAP4REV1...]
   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.
marshall /at/ sprux net
19-Aug-2003 08:44
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.
Kyle Putnam
15-Jun-2003 08:52
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 ;)
stefan dot greifeneder at dioezese-linz dot at
09-May-2003 10:10
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.
bill dot mccoy at pictureiq dot com
24-Apr-2003 11:29
"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: "{your.imap.host/imap/notls/norsh}".
kaper at nexgc dot com
09-Apr-2003 01:17
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: {www.server.com:110/pop3/notls}INBOX

and for imap: {www.server.com:143/notls}INBOX.
xore at hotmail dot com
02-Apr-2003 09:37
pop3 seems to like refusing connection if you have OP_READONLY set

testers: be forewarned :P
madsiuk at morellos dot net
28-Feb-2003 12:35
hi
  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.

madsiuk
russell at flora dot ca
09-Jan-2003 08:07
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.

Example: 

"{localhost:143}INBOX"

becomes:

"{localhost:143/notls}INBOX"
jpdalbec at ccNO dot ysuSPAM dot edu
18-Jun-2002 03:27
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.
fxbois at free dot fr
06-Jun-2002 03:07
Hi,
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 :
{127.0.0.1:110/pop3/notls}INBOX
hope this help
sgriffith AT dualityofman.dhs.org
15-May-2002 08:35
Just wanted to add that you cannot have any white space between your {}'s.  it took me a little while to figure that out.

"{127.0.0.1:110/pop3}INBOX" is correct

while

"{ 127.0.0.1:110/pop3 } INBOX" is not.

Also, if you forget to put INBOX, it may connect but wont return anything.

just a heads up to anyone else who might have misinterpreted the manuals instructions.
frederik at roal dot no
18-Apr-2002 01:02
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() )
brojann at netscape dot com
31-Oct-2001 07:01
You can do

<? $foo = imap_errors(); ?>

to clear unwanted warning messages like 'Mailbox is empty'
jdg11 at po dot cwru dot edu
14-Aug-2001 07:41
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.
curtis at lamere dot net
27-Jun-2001 08:16
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 = "mail.somedomina.com:110/imap";

$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("{mail.somedomain.com:110/pop3}",$username,$password)"

I discovered all of this after 3 days of trying to get all of this work on redhat 7.1.
24-May-2001 02:23
A better way to connect to a mail server would be to use uri syntax, for example:

imap://username:password@server.com:143/INBOX/message/part

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

Remember to keep your username and password hidden if your over an open network
fferreres at joydivision dot com dot ar
30-Mar-2001 12:12
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...:
".imap_last_error());
kvance at n-link dot net
10-Mar-2001 06:34
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.
bandpay at hotmail dot com
05-Dec-2000 05:59
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:

$server = "{news.servername.com/nntp:119}";
$nntp = imap_open($server,"","",OP_HALFOPEN);

and $nntp will become the connection ID.

Regards
//Babak

imap_ping" width="11" height="7"/> <imap_num_recent
Last updated: Mon, 05 Feb 2007
 
 
show source | credits | sitemap | contact | advertising | mirror sites