需要“All Mail”文件夹的句柄才能删除旧邮件

时间:2015-06-24 19:19:40

标签: google-apps-script

我创建了一个脚本,可以删除超过400天(约13个月)的邮件。我搜索了可用的GS帮助,找不到获取“All Mail”文件夹句柄的方法,这是我要删除邮件的地方。有没有办法做到这一点,我没有看到?

4 个答案:

答案 0 :(得分:1)

执行搜索。它的工作方式与GMail UI相同。

var threads = GmailApp.search('older_than:400d … plus whatever other criteria you want');

它将提供与GMail相同的结果,即使用All Mail作为搜索存储库。

如果您要查找尚未归档到任何标签中的邮件,请将广告'has:nouserlabels'作为标准,但要注意线程是棘手的问题,特别是当过滤器在没有标签的会话中自动标记传入邮件时等

如果可能会返回大量结果,则此调用可能需要分页。

<强>更新 循环查看结果,使用.getLastMessageDate()

检查返回的每个线程中的最后一条消息是否也符合您的年龄标准

答案 1 :(得分:1)

在GMail中,“All Mail”不是文件夹,也不是用户标签。这就是你的所有邮件。

如果您的目标是识别具有特定年龄的所有消息,则GMail服务中没有方法可以执行此操作。但是,您可以使用GMail API列出所有邮件,并通过提供查询字符串来过滤结果。

这是一个能够做到这一点的功能。但请注意......它可以详尽地列出您的所有消息,如果有足够的消息,它将超出您的执行限制。

/**
 * Retrieve Messages in user's mailbox matching query.
 *
 * @param  {String} query  String used to filter the Messages listed.
 * @param  {String} userId (optional) User's email address. Default: The special 
 *                         value 'me' is used to indicate the authenticated user.
 */
function listMessages(query, userId) {
  query = query || '';
  userId = userId || 'me';
  var msglist = [];

  // see https://developers.google.com/gmail/api/v1/reference/users/messages/list
  var url = 'https://www.googleapis.com/gmail/v1/users/${userId}/messages'
    .replace("${userId}", userId) // The user's email address. The special value me can be used to indicate the authenticated user.
  var headers = {
    Authorization: 'Bearer ' + ScriptApp.getOAuthToken()
  };
  var request = {
    'q': query
  };
  var params = {
    method: "get",
    contentType: "application/json",
    headers: headers,
    muteHttpExceptions: true
  };

  do {

    // For GET, params must be URI Encoded in URL.
    var urlPlus = url + "?" + serializeParams(request);

    //var check = UrlFetchApp.getRequest(urlPlus, params); // for debugging
    var response = UrlFetchApp.fetch(urlPlus, params);

    var result = response.getResponseCode();
    if (result == '200') { // OK
      var resp = JSON.parse(response.getContentText());
      msglist = msglist.concat(resp.messages);
      request.pageToken = resp.nextPageToken;
    } else {
      // This is only needed when muteHttpExceptions == true
      var err = JSON.parse(response.getContentText());
      throw new Error('Error (' + result + ") " + err.error.message);
    }

  } while (resp.nextPageToken);

  return msglist;
}


// From http://stackoverflow.com/a/23639793
function serializeParams( obj ) {
  var str = Object.keys(obj).map(function(key) {
    return key + '=' + obj[key];
  }).join('&');
  return encodeURIComponent(str);
}

所以你的删除功能就像这样:

function deleteOldMessages( ageInDays ) {
  if (!ageInDays || typeof ageInDays !== "number")
    throw new TypeError( "Expecting number" );

  // Build query and get all matching messages
  var query =  "older_than:{$age}d".replace("{$age}",ageInDays);
  var messages = listMessages(query);

  for (var i=0; i<messages.length; i++) {
    GmailApp.getMessageById(messages[i].id).moveToTrash();
  }
}

答案 2 :(得分:1)

感谢您的信息。能够构建一个完全符合我想要的功能。

function delOldMail() {
  var email = Session.getActiveUser().getEmail();
  var subject = 'GS delOldMail: ' + Session.getActiveUser();
  var body = 'Messages Deleted:';
  var breakPoint = 50;
  var breakCntr = 0;

  var threads = GmailApp.search('!is:starred older_than:400d');
  if (threads.length > 0) {

    for (var delCntr = 0; delCntr < threads.length; delCntr++) {      
      var message = threads[delCntr].getMessages()[0];
      var messageId = message.getId();
      var messageById = GmailApp.getMessageById(messageId);
      var messagedate = messageById.getDate();

      var seqnum = "0000" + delCntr;
      var seqstrt = seqnum.length - 4;
      var body = body + "\n  threads: " + seqnum.substr(seqstrt,4) + " " + threads[delCntr].getFirstMessageSubject() + ':::' + messagedate;

      if (breakCntr = breakPoint) {
        breakPoint = breakPoint + 50
        Utilities.sleep(1000);
        }
      var breakCntr = breakCntr++
      threads[delCntr].moveToTrash();
    }
  } else {
    var body = body + '\n Nothing to delete today ...';
  }
  GmailApp.sendEmail(email, subject, body);
}

答案 3 :(得分:0)

对于邮件的批量处理,最好使用完整的又名&#34; Advanced&#34; Gmail api 。确保首先在&#34;资源 - >高级Google服务&#34; 下启用此功能。

// set MAX_RUNS according to 6min script execution limit
var MAX_RUNS=1;
var MAX_RESULTS = 10;
function ScanMessages() {
  var messageList = {'nextPageToken' : null};
  for(var i = 0; i < MAX_RUNS; i++){
    var options = {
      maxResults: MAX_RESULTS,
      // set this to your desired date range
      q: 'before after:2015/12/25 before:2016/1/1'
    };
    // init nextPageToken
    if(messageList.nextPageToken != null){
      options.pageToken = messageList.nextPageToken;
    }
    // Use the "advanced" Gmail API to get messages directly.
    messageList = Gmail.Users.Messages.list('YOURGMAIL@gmail.com', options);
    if(messageList.messages == undefined || messageList.messages.length < 1){
     continue; 
    }
    for(var j = 0; j < messageList.messages.length; j++){
      var curMessage = GmailApp.getMessageById(messageList.messages[j].id);
      //curMessage.moveToTrash();
      Logger.log("deleting message: " + JSON.stringify({subject: curMessage.getSubject(), date: curMessage.getDate()}));
    }
  }  
}