前提条件有时会失败,有时会通过

时间:2019-01-29 18:43:20

标签: google-apps-script

我正在尝试从Gmail帐户获取消息。我的身份验证有效,有时代码将正常运行并获取我请求的消息ID。但是有时候不会。似乎完全是随机的,一个小时有效,第二小时返回

"error": {
"errors": [
{
     "domain": "global",
     "reason": "failedPrecondition",
     "message": "Bad Request"
     }
 ],
    "code": 400,
    "message": "Bad Request"
 }

}

其他时间,它可以正常工作并发送消息ID。为什么行为不一致?

function getEmails(email, searchEmail) {

    Logger.log('starting getEmails');
    var emailGetSuccessfully = false;
    var service = getDomainWideDelegationService('Gmail: ', email);
    if (!service.hasAccess()) {

         Logger.log('failed to authenticate as user ' + email);
         Logger.log(service.getLastError());
         emailGetSuccessfully = service.getLastError();
         return emailGetSuccessfully;

     } else Logger.log('successfully authenticated as user ' + email);

    var requestBody                = {};
    requestBody.headers            = {'Authorization': 'Bearer ' + 
    service.getAccessToken()};
    requestBody.contentType        = "application/json";
    requestBody.method             = "GET";
    requestBody.muteHttpExceptions = true;

    var emailForUrl = encodeURIComponent(email);

    var url = 'https://www.googleapis.com/gmail/v1/users/me/messages?maxResults=1&q=to:' + searchEmail + ' OR from:' + searchEmail; //maxResults=1&
    var emailGetSuccessfully = UrlFetchApp.fetch(url, requestBody);
    var JSONemails = JSON.parse(emailGetSuccessfully);
    Logger.log(emailGetSuccessfully);
    var messages = JSONemails['messages']


    if (!messages) {return [email, "FAILED", 0, 0]; }

    var messageID = messages[0]['id'];
    var url = 'https://www.googleapis.com/gmail/v1/users/'+email+'/messages/'+messageID;
    var msgRequest = UrlFetchApp.fetch(url, requestBody);
    var msgInfo = JSON.parse(msgRequest);
    var headerInfo = msgInfo['payload']['headers'];
    var date = convertDate(msgInfo['internalDate']);
    var toFrom = toFroms(cleanJSON(headerInfo));
    var to = toFrom[0];
    var from = toFrom[1];
    var cc = toFrom[2];

    return [from, to, cc, date];
}

0 个答案:

没有答案