PHP 8.6维护Gmail邮件索引时,可以先用messages.list和messages.get建立基线,再用history.list查找新增、删除及标签变化。historyId不是连续序号,也不能按时间天数推算;起点过旧返回404时,应重新建立基线,而不是跳过变化继续推进游标。
索引只存需要的邮件元数据
使用php 8.6 cli和curl扩展。下面的requestjson辅助函数保存为同目录的http.php;调用方从环境变量读取已获得相应权限的令牌,不把令牌写入源码。http错误由业务脚本检查,网络超时不会自动重发写请求。
<?php
function requestJson(string $method, string $url, array $headers = [], ?array $data = null): array {
$ch = curl_init($url);
$headers[] = 'Accept: application/json';
$options = [CURLOPT_RETURNTRANSFER => true, CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_HTTPHEADER => $headers, CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_TIMEOUT => 45, CURLOPT_FOLLOWLOCATION => false,
CURLOPT_PROTOCOLS => CURLPROTO_HTTPS];
if ($data !== null) {
$headers[] = 'Content-Type: application/json';
$options[CURLOPT_HTTPHEADER] = $headers;
$options[CURLOPT_POSTFIELDS] = json_encode($data, JSON_THROW_ON_ERROR);
}
curl_setopt_array($ch, $options);
$raw = curl_exec($ch);
if ($raw === false) { throw new RuntimeException('Network request failed'); }
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
return [$status, $raw === '' ? [] : json_decode($raw, true, 512, JSON_THROW_ON_ERROR)];
}取得gmail.readonly权限的OAuth令牌。以下示例只缓存邮件ID、threadId、labelIds和historyId,不下载正文;完整邮箱可能很大,应安排在CLI任务中并设置扫描上限。state目录须私有,示例以单进程运行。

Gmail完整同步的元数据读取流程
完整基线与增量共用一个提交点
<?php
require __DIR__.'/http.php';
function gmailGet(string $path, array $query=[]): array {
[$status,$r] = requestJson('GET','https://gmail.googleapis.com/gmail/v1/users/me/'.$path.($query?'?'.http_build_query($query):''), ['Authorization: Bearer '.getenv('GMAIL_TOKEN')]);
if ($status !== 200) { throw new RuntimeException('Gmail HTTP '.$status,$status); }
return $r;
}
$db=new PDO('sqlite:'.__DIR__.'/state/gmail.sqlite');
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$db->exec('CREATE TABLE IF NOT EXISTS messages(id TEXT PRIMARY KEY,body TEXT)');
$db->exec('CREATE TABLE IF NOT EXISTS state(k TEXT PRIMARY KEY,v TEXT)');
$start=$db->query("SELECT v FROM state WHERE k='history'")->fetchColumn();
$db->beginTransaction();
try {
$ids=[]; $page=null; $next=null;
if (!$start) {
$db->exec('DELETE FROM messages');
$next=gmailGet('profile')['historyId'];
}
for($n=0;$n<1000;$n++) {
$q=$start?['startHistoryId'=>$start,'maxResults'=>500]:['maxResults'=>500];
if($page){$q['pageToken']=$page;}
$r=gmailGet($start?'history':'messages',$q);
if($start){
foreach($r['history']??[] as $h){
foreach($h['messages']??[] as $m){$ids[$m['id']]=true;}
}
$next=$r['historyId'];
}else{foreach($r['messages']??[] as $m){$ids[$m['id']]=true;}}
$page=$r['nextPageToken']??null;
if(!$page){break;}
}
if($page){throw new RuntimeException('Page limit reached');}
foreach(array_keys($ids) as $id){
try {$m=gmailGet('messages/'.rawurlencode($id),['format'=>'minimal']);}
catch(RuntimeException $e){
if($e->getCode()!==404){throw $e;}
$db->prepare('DELETE FROM messages WHERE id=?')->execute([$id]);continue;
}
$db->prepare('INSERT OR REPLACE INTO messages VALUES(?,?)')->execute([$id,json_encode($m,JSON_THROW_ON_ERROR)]);
}
$db->prepare('INSERT OR REPLACE INTO state VALUES(?,?)')->execute(['history',$next]);
$db->commit();echo "Mail index committed\n";
}catch(Throwable $e){
if($db->inTransaction()){$db->rollBack();}
if($start && $e->getCode()===404){$db->exec("DELETE FROM state WHERE k='history'");}
throw $e;
}
historyId和增量历史记录的关系
保留基线期间发生的变化
完整扫描前从profile取得historyId,扫描成功后保存这个起点,下一次增量会覆盖扫描期间的变化;按ID覆写使重复读取可合并。历史分页中的messages可能重复,因此先收集ID,再读取当前最小元数据。
使用官方Model Context Protocol PHP SDK将PHP应用程序功能暴露为MCP工具、资源和提示,用于代理工作流。
history.list返回404后,示例清除旧起点并结束,下一次任务重新全量。官方说明历史记录通常保留至少一周,但也可能更短,不能把“七天内必定有效”写成承诺。对于大邮箱,把待刷新ID和工作进度持久化,全部完成后再推进历史水位。

历史记录可用期限与404重建要求


















