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

时间:2015-02-07 22:50:10

标签: php gmail-api

如何使用带有PHP的Gmail API获取所有收件箱邮件?我可以获得消息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
        ];
    }

1 个答案:

答案 0 :(得分:8)

这就是我做到的。

    $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();

            }

            else if ($single->getName() == 'Date') {

                $message_date = $single->getValue();
                $message_date = date('M jS Y h:i A', strtotime($message_date));
            }

            else if ($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
        ];

    }