我需要通过imap / php搜索gmail消息(google apps for work)。但是,imap_search criterias不足以捕获相关邮件。
我使用的代码如下所示:
$imap = imap_open("{imap.gmail.com:993/imap/ssl}Label1/label2", $user_email, $user_passwd);
$msg_list = imap_search($imap, 'TEXT "Delivered-To: username+label@gmail.com"');
imap_close($imap);
imap_search调用没有返回任何内容。
我做了一些研究,似乎我可以基于" Delivered-To"来过滤消息。标题字段来自gmail search syntax X-GM-RAW
,但我无法实现这一点,我尝试了所有这些调用(以及更多):
$msg_list = imap_search($imap, 'UID SEARCH X-GM-RAW "deliveredto:username+label@gmail.com"');
$msg_list = imap_search($imap, 'SEARCH X-GM-RAW "deliveredto:username+label@gmail.com"');
$msg_list = imap_search($imap, 'X-GM-RAW "deliveredto:username+label@gmail.com"');
但它没有用,有人知道我的代码有什么问题吗?
答案 0 :(得分:1)
好的,要么我不知道如何提问,SOers忙,要么我提出疑难问题。
无论如何,现在我知道PHP内置的imap_ *函数不处理直接的IMAP命令,所以我不得不使用zend框架(对我的需求来说太重),或者直接通过套接字连接到imap。 / p>
我选择了第二个选项,代码如下(code stolen from here and adapted for my own needs),万一有人需要它:
<?php
// Open a socket
if (!($fp = fsockopen('ssl://imap.gmail.com', 993, $errno, $errstr, 15))) die("Could not connect to host");
// Set timout to 1 second
if (!stream_set_timeout($fp, 1)) die("Could not set timeout");
// Fetch first line of response and echo it
echo fgets($fp);
// =========================================
fwrite($fp, "0001 LOGIN user.name@gmail.com YOUR_PASSWORD_HERE_WITHOUT_QUOTES\r\n");
// ie. fwrite($fp, "0001 LOGIN super.dude@gmail.com pass123\r\n");
// Keep fetching lines until response code is correct
while ($line = trim(fgets($fp)))
{
echo "Line = [$line]\n";
$line = preg_split('/\s+/', $line, 0, PREG_SPLIT_NO_EMPTY);
$code = $line[0];
if (strtoupper($code) == '0001') {
break;
}
}
// =========================================
fwrite($fp, "0002 SELECT Inbox\r\n");
// Keep fetching lines until response code is correct
while ($line = trim(fgets($fp)))
{
echo "Line = [$line]\n";
$line = preg_split('/\s+/', $line, 0, PREG_SPLIT_NO_EMPTY);
$code = $line[0];
if (strtoupper($code) == '0002') {
break;
}
}
// =========================================
fwrite($fp, "0003 SEARCH X-GM-RAW \"deliveredto:user.name+someLabel@gmail.com\"\r\n");
// Keep fetching lines until response code is correct
while ($line = fgets($fp))
{
echo "Line = [$line]\n";
$line = preg_split('/\s+/', $line, 0, PREG_SPLIT_NO_EMPTY);
$code = $line[0];
if (strtoupper($code) == '0003') {
break;
}
}
fclose($fp);
echo "I've finished!";
?>
瞧!只需复制和粘贴,现在您可以直接从PHP访问gmail语法! (如果你愿意,嘿投票:p)