Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to save POP (Gmail) emails to MySQL database [closed]

I need to run queries on emails I receive from Gmail. I have POP and IMAP access to it as I am running Google Business Apps. To avoid API usage, I am interested in simply downloading emails to a MySQL database. Ultimately, I'm going to show usage stats and metrics for a CRM but for now I just need to get them downloading regularly (once every 5 minutes).

Additional Information: I am using Ubuntu 14.04. My app is going to be built with PHP but for the sake of simplicity, I would be fine with grabbing all the emails with a bash or Python script. I'm not picky at this point.

I've come across some very dated PHP scripts but I would like to know if there is anything a bit more up to date:

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

P.S. I was going to use an open-source email client like WebMail Lite or Roundcube but they don't seem to be saving the emails to a database though I think they might actually use an API which could possibly allow me to get the stats I need but again, I was thinking there would be a more efficient solution.

like image 710
sparecycle Avatar asked Mar 18 '23 16:03

sparecycle


1 Answers

You don't need a whole library for something so simple.

$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = '[email protected]';
$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
}
like image 133
I wrestled a bear once. Avatar answered Mar 23 '23 23:03

I wrestled a bear once.