Search code examples
javascriptgoogle-apps-scriptgmail-api

Gmail auto reply script- how to stop multiple replies?


I have a auto reply script to reply to evry email that i recived, with a attached file

var file = DriveApp.getFileById('file_id').getAs('application/pdf')
function reply() {
  var label = GmailApp.getUserLabelByName('new-mail');
  var messages = label.getThreads();
      for (let mess of messages) {
        if (mess.getMessageCount() == 1) {
           mess.reply('attached',{
           attachments:[file]
           });
  
          mess.removeLabel(label);
        }
          else mess.removeLabel(label)
      }
}

now, i want to reply to the sender only once a day, that meens that it won't send the auto reply message to senders that have already received it today how i should do it?


Solution

  • You can use Properties Service to save all the email addresses that you already replied to.

    Sample Code:

    function initializeLogs(){
      //Get Script properties
      var scriptProperties = PropertiesService.getScriptProperties();
      scriptProperties.setProperty('email','');
    }
    
    function reply() {
      
      //Get Script properties
      var scriptProperties = PropertiesService.getScriptProperties();
      var emailLogs = scriptProperties.getProperty('email');
      Logger.log(emailLogs);
      var label = GmailApp.getUserLabelByName('new-mail');
      var messages = label.getThreads();
      
      for (let mess of messages) {
        if (mess.getMessageCount() == 1) {
    
          //get email address of the message sender
          var sender = mess.getMessages()[0].getFrom();
    
          if(!emailLogs.includes(sender)){
            Logger.log(sender);
            //sender not yet in the logs, send reply
            mess.reply('attached',{
              attachments:[file]
              });
    
            mess.removeLabel(label);
    
            //add sender to the logs
            scriptProperties.setProperty('email', emailLogs+sender)
          }
        }
          else mess.removeLabel(label)
      }
    }
    

    Pre-requisite:

    1. Run initializeLogs() once to initialize email key with an empty string.
    2. Create a Time-driven trigger to call initializeLogs() daily (which aims to reset your list of replied emails on a daily basis

    enter image description here

    enter image description here

    What it does?

    1. As mentioned, initializeLogs() will create an email key with the value of an empty string '' using setProperty(key, value)
    2. For reply(). First get the current email logs using getProperty(key)
    3. Get the sender of the email
    4. Check if the sender already exist in the email logs string using string.includes(). If user exist, do not send a reply
    5. If user doesn't exist, send a reply and append the current sender's email address to the email logs.