将POP(Gmail)邮件高效保存到MySQL数据库的最佳方法

4 投票
1 回答
5278 浏览
提问于 2025-04-18 18:17

我需要对从Gmail收到的邮件进行查询。因为我在使用Google商务应用,所以我可以通过POP和IMAP来访问这些邮件。为了避免使用API,我想直接把邮件下载到MySQL数据库里。最终,我会展示一些使用统计和指标给客户关系管理系统(CRM),但现在我只需要定期下载邮件(每5分钟一次)。

补充信息:我使用的是Ubuntu 14.04。我打算用PHP来构建我的应用,但为了简单起见,我也可以用bash或Python脚本来抓取所有邮件。现在我对工具没有太多要求。

我遇到了一些很老旧的PHP脚本,但我想知道有没有更新一点的选择:

http://www.phpclasses.org/package/3324-PHP-Retrieve-e-mail-messages-into-a-MySQL-database.html http://www.phpclasses.org/package/2-PHP-Access-to-e-mail-mailboxes-using-the-POP3-protocol.html

附言:我本来打算使用像WebMail Lite或Roundcube这样的开源邮件客户端,但它们似乎并没有把邮件保存到数据库里。我觉得它们可能会使用API,这样可能让我获取到我需要的统计数据,但我还是在想有没有更高效的解决方案。

1 个回答

7

对于这么简单的事情,你其实不需要一个完整的库。

$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'myemail@gmail.com';
$password = 'mypassword';
$inbox = imap_open($hostname,$username,$password);
$emails = imap_search($inbox,'ALL');
foreach($emails as $e){
    $overview = imap_fetch_overview($inbox,$e,0);
    $message = imap_fetchbody($inbox,$e,2);
    // the body of the message is in $message
    $details = $overview[0];
    // you can do a var_dump($details) to see which parts you need
    //then do whatever to insert them into your DB
}

撰写回答