PHP imap_headerinfo检查是否存在

时间:2014-01-07 17:34:45

标签: php

我正在使用PHP函数imap_open来获取每封电子邮件的标题:

$header=imap_headerinfo($inbox,$email_number);
然后我在CC的电子邮件地址上运行一个foreach循环:

foreach ($header->cc as $cc_extra) {

}

如何在运行foreach循环之前检查$header->cc中是否有任何内容?

注意: - $inbox是邮箱的连接字符串 - $email_number是每封电子邮件的电子邮件号码

2 个答案:

答案 0 :(得分:0)

您可以使用issetis_array的组合,如下所示:

$header=imap_headerinfo($inbox,$email_number);
// ...
if(isset($header->cc) && is_array($header->cc)) {
  foreach ($header->cc as $cc_extra) {
  }
}

isset将测试变量是否设置为null is_array将测试该变量实际上是array

修改

或者,如this SO answer所示,您可以在foreach内明确地将变量转换为数组,例如,

foreach ((array)$header->cc as $cc_extra) {
}

答案 1 :(得分:0)

我使用下一个代码:

$connection = imap_open("{192.168.1.170:993/imap/ssl/novalidate-cert}INBOX", $send_from_our, $send_from_pass) or die('Cannot connect to your sever: ' . imap_last_error());
$emails = imap_search($connection, 'UNSEEN');
$unread = 0;
$count = imap_num_msg($connection);

for ($msgno = 1; $msgno <= $count; $msgno++) {
    $cc='';
    $to='';
    $headers = imap_headerinfo($connection, $msgno);           
    if ($headers->Unseen == 'U') {
        $unread++;
        if (isset($headers->cc) && is_array($headers->cc)) {
            foreach ($headers->cc as $cc_extra) {
                $mailbox_cc=strtolower($cc_extra->mailbox);
                $host_cc=strtolower($cc_extra->host);
                $cc .= $mailbox_cc . "@" . $host_cc .',';
            }
            $cc= rtrim($cc, ',');
        }
        if (isset($headers->to) && is_array($headers->to)) {
            foreach ($headers->to as $to_extra) {
                $mailbox_to=strtolower($to_extra->mailbox);
                $host_to=strtolower($to_extra->host);
                if ($mailbox_to=='$MY_EMAIL_NAME' and $host_to='$MY_HOST_NAME') {
                    continue;
                }
                $to .=$mailbox_to . "@" . $host_to.',';
            }
            $to=rtrim($to, ',');
        }
        $fromaddr = $headers->from[0]->mailbox . "@" . $headers->from[0]->host;
        $full_reply_to=rtrim($fromaddr.','.$cc.','.$to, ',');

此代码接收来自maibox的所有未读电子邮件,并将每封电子邮件的CC和TO(不包括我的自我地址)的所有地址放入$ full_reply_to