tags:

views:

178

answers:

3

I receive many emails whose contents are of the same pattern, e.g.

Name: XXX
Phone: XXX
Bio: XXX
......

I want to write a PHP script to parse these emails and save the data into a database. I tried to use file_get_contents() to get the contents of these emails.

The problem is that, it requires authentication to access to my emails. Even though I have signed into my email account on the server (localhost actually), file_get_contents() still return the webpage that prompts me to sign in.

So how to access the contents of my emails with a PHP script?

EDIT: it is a gmail account.
The following code does not work.

$login_url = 'https://www.google.com/accounts/ServiceLoginAuth';
$gmail_url = 'https://mail.google.com/';
$cookie_file = dirname(__FILE__) . '/cookie.txt';

$ch = curl_init();

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);

curl_setopt($ch, CURLOPT_URL, $gmail_url);
// not sure how to set this option
curl_setopt($ch, CURLOPT_REFERER, $login_url);

$output = curl_exec($ch);
curl_close($ch);

echo $output;
A: 

I suspect you are trying to access a secure protocol (https) using file_get_contents. For this to work, you should have authentication and openssl extension uncommented in php.ini file. Otherwise the file_get_contents would raise an error that it could not locate the file/url.

Sarfraz
Yes, it is https protocal. And openssl extension is already enabled.
powerboy
@powerboy: Are you using IIS server?
Sarfraz
@Sarfraz: No, it is apache on windows
powerboy
@powerboy: Could you try the `curl` extension instead of `file_get_contents`
Sarfraz
@Sarfraz: Sure. I am going to try it now.
powerboy
@Sarfraz: I tried cURL. I used CURLOPT_COOKIEFILE and CURLOPT_COOKIEJAR to save and send cookies. But the problem is, after clicking "sign in" button, the browser leave localhost and direct to google account website, therefore no useful cookies can be saved in CURLOPT_COOKIEFILE.
powerboy
+1  A: 

You could try using libgmailer http://gmail-lite.sourceforge.net/wordpress/index.php/about/libgmailer/

nico
I will definitely try libgmailer. But I am curious about how can it do this? I mean, how can it get contents of a remote webpage that require authentication?
powerboy
@powerboy: You can send cookies to it. Now, I have never really messed with GMail, but I assume you could directly set the proper cookie he is expecting and connect to the inbox page.You can do that using `fsockopen` or using cURL.
nico
+2  A: 

Enable imap on gmail and use the old fashion php imap library.
http://mail.google.com/support/bin/answer.py?hl=en&answer=75725
http://php.net/manual/en/book.imap.php

RandyMorris