使用 PHP 获取 Gmail API 的所有收件箱邮件

Get all inbox messages with Gmail API using PHP

如何使用 Gmail API 和 PHP 获取所有收件箱邮件?我只能得到消息 ID,除此之外别无他法。我需要获取主题、发件人和消息文本。

 $list = $gmail->users_messages->listUsersMessages('me',['maxResults' => 10000, 'q' => 'category:primary']);
    $messageList = $list->getMessages();

    $client->setUseBatch(true);
    $batch = new Google_Http_Batch($client);

    foreach($messageList as $mlist){
        $batch->add($gmail->users_messages->get('me',$mlist->id, ['format' => 'raw']),$mlist->id);
    }

    $batchMessages = $batch->execute();
    $inboxMessage = [];


    foreach($batchMessages as $dMessage){
        $messageId = $dMessage->id;
        $messageSnippet = $dMessage->snippet;

        $dcMessage = base64url_decode($dMessage->getRaw());

        $params['include_bodies'] = true;  
        $params['decode_bodies'] = true;  
        $params['decode_headers'] = true;  

        $mimeDecode = new Mail_mimeDecode($dcMessage);
        $mimeSubject = $mimeDecode->decode($params)->headers['subject'];



        $inboxMessage[] = [
            'messageId' => $messageId,
            'messageSubject' => $messageSubject
        ];
    }

我就是这样做的。

$list = $gmail->users_messages->listUsersMessages('me', [
    'maxResults' => 10,
    'q' => $search
]);

$messageList = $list->getMessages();
$inboxMessage = [];

foreach($messageList as $mlist){
    $optParamsGet2['format'] = 'full';
    $single_message = $gmail->users_messages->get('me', $mlist->id, $optParamsGet2);
    
    $message_id = $mlist->id;
    $headers = $single_message->getPayload()->getHeaders();
    $snippet = $single_message->getSnippet();

    foreach($headers as $single) {
        if ($single->getName() == 'Subject') {
            $message_subject = $single->getValue();
        } elseif ($single->getName() == 'Date') {
            $message_date = $single->getValue();
            $message_date = date('M jS Y h:i A', strtotime($message_date));
        } elseif ($single->getName() == 'From') {
            $message_sender = $single->getValue();
            $message_sender = str_replace('"', '', $message_sender);
        }
    }
  

    $inboxMessage[] = [
        'messageId' => $message_id,
        'messageSnippet' => $snippet,
        'messageSubject' => $message_subject,
        'messageDate' => $message_date,
        'messageSender' => $message_sender
    ];
}