【发布时间】:2011-02-05 17:02:14
【问题描述】:
我正在研究一个应用程序,以根据到达 Gmail 的新 IMAP 电子邮件触发 PHP 脚本。知道新电子邮件已到达 Gmail IMAP 帐户的最佳方法是什么?除了配置一个 cron 作业,我什么都想不出来。我在 Linux (Ubuntu) 机器上运行 PHP + Nginx。
【问题讨论】:
我正在研究一个应用程序,以根据到达 Gmail 的新 IMAP 电子邮件触发 PHP 脚本。知道新电子邮件已到达 Gmail IMAP 帐户的最佳方法是什么?除了配置一个 cron 作业,我什么都想不出来。我在 Linux (Ubuntu) 机器上运行 PHP + Nginx。
【问题讨论】:
我发现这正是蜂窝公司开发人员用来验证其客户 gmail 的方式。
好吧,开始正常连接,然后:
$t1=time();//mark time in
$tt=$t1+(60*1);//total time = t1 + n seconds
do{
if(isset($t2)) unset($t2);//clean it at every loop cicle
$t2=time();//mark time
if(imap_num_msg($imap)!=0){//if there is any message (in the inbox)
$mc=imap_check($imap);//messages check
//var_dump($mc); die;//vardump it to see all the data it is possible to get with imap_check() and them customize it for yourself
}else echo 'No new messagens';
sleep(rand(7,13));//Give Google server a breack
if(!@imap_ping($imap)){//if the connection is not up
//start the imap connection the normal way like you did at first
}
}while($tt>$t2);//if the total time was not achivied yet, get back to the beginning of the loop
就是这样。
顺便说一下,这里有一些关于 IMAP 工作原理的有用信息。我的观点是:由于 IMAP 可以维持几乎一种“实时同步”连接,如果您不想配置 MTA 来接收电子邮件(如我),那么 IMAP 是获取“电子邮件推送”的真正选择"给你。
【讨论】:
只有两种方法可以从电子邮件帐户获取信息,连接到它,定期阅读(例如,通过 cron-job)以获取新消息,或者将电子邮件转发到您自己的服务器,该服务器通过管道传输新电子邮件进入 PHP 脚本。
Zend_Mail,Zend 框架的一部分有 Zend_Mail_Storage_Imap(可以在没有其他 MVC 结构的情况下使用),可以连接到 Gmail 以轮询帐户。
【讨论】: