29.7.2 查看邮箱内容
使用display_list()函数,可以查看邮箱的内容。该函数将显示邮箱中所有消息的列表。该函数的代码如程序清单29-8所示。
程序清单29-8 output_fns.php文件中的display_list()函数——显示所有邮箱消息
function display_list($auth_user,$accountid){
//show the list of messages in this mailbox
global$table_width;
if(!$accountid){
echo"<p style=\"padding-bottom:100px\">No mailbox selected.</p>";
}else{
$imap=open_mailbox($auth_user,$accountid);
if($imap){
echo"<table width=\"".$table_width."\"cellspacing=\"0\"
cellpadding=\"6\"border=\"0\">";
$headers=imap_headers($imap);
//we could reformat this data,or get other details using
//imap_fetchheaders,but this is not a bad summary so we
//just echo each
$messages=sizeof($headers);
for($i=0;$i<$messages;$i++){
echo"<tr><td bgcolor=\"";
if($i%2){
echo"#ffffff";
}else{
echo"#ffffcc";
}
echo"\"><a href=\"index.php?action=view-message&messageid="
.($i+1)."\">";
echo$headers[$i];
echo"</a></td></tr>\n";
}
echo"</table>";
}else{
$account=get_account_settings($auth_user,$accountid);
echo"<p style=\"padding-bottom:100px\">Could not open mail
box".$account['server'].".</p>";
}
}
}
在这个函数中,我们实际上已开始使用了PHP的IMAP函数。该函数的两个关键部分是打开邮箱和阅读消息标题。
我们通过调用mail_fns.php文件中的open_mailbox()函数来打开用户的账户邮箱。函数代码如程序清单29-9所示。
程序清单29-9 mail_fns.php文件中的open_mailbox()函数——这个函数连接到用户邮箱
function open_mailbox($auth_user,$accountid){
//select mailbox if there is only one
if(number_of_accounts($auth_user)==1){
$accounts=get_account_list($auth_user);
$_SESSION['selected_account']=$accounts[0];
$accountid=$accounts[0];
}
//connect to the POP3 or IMAP server the user has selected
$settings=get_account_settings($auth_user,$accountid);
if(!sizeof($settings)){
return 0;
}
$mailbox='{'.$settings[server];
if($settings[type]=='POP3'){
$mailbox.='/pop3';
}
$mailbox.=':'.$settings[port].'}INBOX';
//suppress warning,remember to check return value
@$imap=imap_open($mailbox,$settings['remoteuser'],
$settings['remotepassword']);
return$imap;
}
实际上,我们是使用imap_open()函数来打开邮箱的。函数原型如下:
int imap_open(string mailbox,string username,string password[,int options])
该函数所需的参数如下所示:
■mailbox——这个字符串应包括服务器名和邮箱名,以及可选的端口号和协议。该字符串的格式如下所示:
{hostname/protocol:port}boxname
如果没有指定协议,则默认为IMAP。在我们编写的代码中,可以看到,如果用户为某一特定账户指定了POP3协议,我们就会指定为POP3。
例如,要使用默认端口从本地机器读取邮件,对于IMAP协议,我们使用如下所示的邮箱:
{localhost:143}INBOX
对于POP3协议,我们使用如下所示的邮箱:
{localhost/pop3:110}INBOX
■username——该账户的用户名。
■password——该账户的密码。
也可通过提交可选的标记来指定某些选项,例如,以只读方式打开邮箱。
值得注意的是,我们在将邮箱名称字符串传递给imap_open()函数打开之前,是一段一段地将它组织起来的。因此,在构造该串时,必须仔细一些,因为在PHP中包含“{$”的字符串会引起问题。
如果邮箱可以成功打开,该函数调用将返回一个IMAP流,如果不能成功打开则返回false。
当完成对一个IMAP流的操作时,可以调用imap_close(imap_stream)函数关闭它。在这个函数中,IMAP流被传回至主程序。接着,我们使用imap_headers()函数获得要显示的电子邮件标题:
$headers=imap_headers($imap);
这个函数将返回我们已经连接的邮箱所有消息的标题信息。这些信息以数组的形式返回,每条消息占一行。我们并没有对这些消息进行格式化处理。每条消息在输出中将占用一行,可从图29-5看到其输出形式。
可以通过使用imap_headers()函数来得到关于电子邮件标题的更多信息,该函数与imap_header()名称类似,因此易发生混淆。在本示例中,imap_headers()函数给出的详细信息对我们的项目目标来说已经足够了。