The code have been tested that all the message_id,uid,subject gmail header info can be inserted into my sqlite3 database.
<?php
$db='/home/email.db';
// function get_gmail can get all the message_id,uid,subject gmail header info.
function get_gmail(){
$email_data=array();
$hostname = '{imap.gmail.com:993/imap/ssl}';
$username = 'xxxx@gmail.com';
$password = 'yyyy';
$inbox = imap_open($hostname,$username,$password);
$nums=imap_num_msg($inbox);
for ($i=1;$i<=$nums;$i++){
$overview = imap_fetch_overview($inbox, $i, 0);
$x1 = $overview[0]->message_id;
$x2 = $overview[0]->uid;
$x3 = $overview[0]->subject;
$email_data[]=array($x1,$x2,$x3);
}
imap_close($inbox);
return $email_data;
}
//function insert_data can insert all the data into my sqlite3 database.
function insert_data($array){
Global $db;
$dbh=new PDO("sqlite:{$db}");
$dbh->beginTransaction();
$sql = "INSERT INTO gmail(message_id,uid,subject) VALUES (?,?,?)";
$query = $dbh->prepare($sql);
foreach($array as $item){
$query->execute($item);
}
$dbh->commit();
$dbh->beginTransaction();
$dbh=null;
}
$data=get_gmail();
insert_data($data);
?>
A problem remains ,for example a email's subject is '=?GB2312?B?zbO8xtGnu/m0ocq10bXP7sS/?='
,it was inserted into sqlite3 as the form
'=?GB2312?B?zbO8xtGnu/m0ocq10bXP7sS/?='
,i changed it into chinese characters in the form of utf-8 with the following code.
<?php
$db='/home/email.db';
function get_gmail(){
mb_internal_encoding('UTF-8');
$email_data=array();
$hostname = '{imap.gmail.com:993/imap/ssl}';
$username = 'xxxx@gmail.com';
$password = 'yyyy';
$inbox = imap_open($hostname,$username,$password);
$nums=imap_num_msg($inbox);
for ($i=1;$i<=$nums;$i++){
$overview = imap_fetch_overview($inbox, $i, 0);
$x1 = $overview[0]->message_id;
$x2 = $overview[0]->uid;
$x3 = $overview[0]->subject;
$x3 = mb_decode_mimeheader($x3);
$email_data[]=array($x1,$x2,$x3);
}
imap_close($inbox);
return $email_data;
}
function insert_data($array){
Global $db;
$dbh=new PDO("sqlite:{$db}");
$dbh->beginTransaction();
$sql = "INSERT INTO gmail(message_id,uid,subject) VALUES (?,?,?)";
$query = $dbh->prepare($sql);
foreach($array as $item){
$query->execute($item);
}
$dbh->commit();
$dbh->beginTransaction();
$dbh=null;
}
$re=get_gmail();
insert_data($re);
?>
There are two problems to be solved.
1.mb_decode_mimeheader
Not all the subject in MIME RFC 2047 format need to be changed , strings begins with =?GB2312
will be changed.
How to add a if-else structure to do the job?
2.The insert_data function can't be run .
PHP Fatal error: Call to a member function execute() on a non-object in on line 49
Some bug in $query->execute($item);
,Why the statement can be run when not to change the string with mb_decode_mimeheader function?