Search code examples
google-apps-scriptgmail

Transfer all mails of specific label to another mail (apps script)


I'd like to create a script to transfer emails from a specific label to another email address.

I've started to write my code but there must be an error somewhere as I'm not getting any mail from my Logger.log.

Can you please help me with this?

function searchLabels() {
   // 1. Declaration of constants and variables
   const ui = SpreadsheetApp.getUi();
   var label, threads, msgs;
   var mail = "test@123.com"

   // 2. Get messages from label
   label = ui.prompt("Write your label here : ");
   threads = GmailApp.search('label:' + label.getResponseText());
   msgs = GmailApp.getMessagesForThreads(threads);

   // 3. Transfer msgs to another mail
   for (let i = 0; i < msgs.length; i ++){
     GmailApp.sendEmail(mail,msgs[i]);
   }
 }

Solution

  • The official document of getMessagesForThreads(threads) says as follows.

    Return GmailMessage[][] — an array of arrays of messages, where each item in the outer array corresponds to a thread and the inner array contains the messages in that thread

    In your script, msgs[i] is an array including the messages. And also, in the case of GmailApp.sendEmail(mail,msgs[i]);, the arguments are sendEmail(recipient, subject, body, options). I thought that this might be the reason for your current issue.

    And, when you want to transfer the messages, I thought that forward(recipient) of Class GmailMessage might be able to be used.

    If you want to achieve "Transfer all mails of specific label to another mail" by including these modification points, how about the following modification?

    From:

    for (let i = 0; i < msgs.length; i ++){
      GmailApp.sendEmail(mail,msgs[i]);
    }
    

    To:

    for (let i = 0; i < msgs.length; i++) {
      for (let j = 0; j < msgs[i].length; j++) {
        msgs[i][j].forward(mail);
      }
    }
    

    or

    msgs.forEach(thread => {
      thread.forEach(message => {
        message.forward(mail);
      });
    });
    

    References: