Batch fetching messages performance

前端 未结 4 1617
你的背包
你的背包 2021-02-10 09:27

I need to get the last 100 messages in the INBOX (headers only). For that I\'m currently using the IMAP extension to search and then fetch the messages. This is done with two re

4条回答
  •  粉色の甜心
    2021-02-10 10:05

    Great reply!
    If somebody wants to use a raw function in php to make batch requests for fetching emails corresponding to message ids, please feel free to use mine.

    function perform_batch_operation($auth_token, $gmail_api_key, $email_id, $message_ids, $BOUNDARY = "gmail_data_boundary"){
        $post_body = "";
        foreach ($message_ids as $message_id) {
            $post_body .= "--$BOUNDARY\n";
            $post_body .= "Content-Type: application/http\n\n";
            $post_body .= 'GET https://www.googleapis.com/gmail/v1/users/'.$email_id.
                    '/messages/'.$message_id.'?metadataHeaders=From&metadataHeaders=Date&format=metadata&key='.urlencode($gmail_api_key)."\n\n";
        }
        $post_body .= "--$BOUNDARY--\n";
    
        $headers = [ 'Content-type: multipart/mixed; boundary='.$BOUNDARY, 'Authorization: OAuth '.$auth_token  ];
    
        $curl = curl_init();
        curl_setopt($curl,CURLOPT_URL, 'https://www.googleapis.com/batch' );
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl,CURLOPT_CONNECTTIMEOUT , 60 ) ;
        curl_setopt($curl, CURLOPT_TIMEOUT, 60 ) ;
        curl_setopt($curl,CURLOPT_POSTFIELDS , $post_body);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER,TRUE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        $tmp_response =  curl_exec($curl);
        curl_close($curl);
        return $tmp_response;
    
    }
    

    FYI the above function gets just the headers for the emails, in particular the From and Date fields, please adjust according to the api documentation https://developers.google.com/gmail/api/v1/reference/users/messages/get

提交回复
热议问题