Search code examples
google-apps-scriptgmail

How to avoid auto-forwarding duplicate emails in Gmail


My company has a shared Gmail address for 3 departments in the company, each department handling different works.

When our clients send emails to the shared address, they will first be read by a responsible person in the administrative office and then be forwarded manually to 3 email addresses of the 3 departments for handling. The process is so laborious. In addition, the person may forget to forward the emails and when the person is out of her cubicle, emails will not be forwarded.

We wish to replace the manual process by the automatic forwarding by Google Script. Emails will be automatically forwarded based on the clients of each department. Let say, if the email address of the sender contain "@company_A.com", it will be auto-forwarded to department 1.

We think we could achieve that by using Google script so that the script will get the address of the sender, check if it contains certain strings, and forward the emails that meet conditions. We would like to get the 50 newest messages in the inbox and check.

However, we are stuck with a problem: if each time we check 50 latest messages, how could we avoid forwarding the already forwarded messages from the previous time.

Thank you for any suggestion.


Solution

  • The simplest way is to use a label you would add to the transferred messages.

    I recently published such a script that does exactly what you ask for , well almost...

    Instead of taking the 50 last messages I'd suggest to work on a date criteria, it seems more logical and less time consuming. You will see in the code I've shown that I use advanced search in gmail, this tool is quite powerful (doc here) and you will easily adapt it to your situation.

    Question : Gmail not forwarding some messages

    code :

        function transferEmails() {
          Logger.clear();
          var trfTo = "[email protected]";
          var trf = GmailApp.getUserLabelByName('transférés');
          if(trf==null){
            trf = GmailApp.createLabel('transférés');
          }
          var today = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "yyyy/MM/dd")
    // note the minus sign before label to exclude threads having this label
          var threadsToday = GmailApp.search("after:"+today+" -label:transférés in:inbox" );
    
          Logger.log("today day = "+new Date().getDate());
          Logger.log('Threads today : '+threadsToday.length);
          var count = 0;
          for(var n=0;n<threadsToday.length;n++){
            threadsToday[n].addLabel(trf);
            var msg = threadsToday[n].getMessages();
            if(msg==null){continue};
            for(var m=0;m<msg.length;m++){
              if(msg[m].isInTrash()||msg[m].getFrom().indexOf(Session.getActiveUser().getEmail())>-1){continue};
              Logger.log("msg from : "+msg[m].getFrom());
              count++;
              var ori = msg[m].getFrom();
              var sujet = msg[m].getSubject();
              Logger.log('this thread ('+sujet+') has '+msg.length+' messages');
              if(msg[m].getDate().getDate()==new Date().getDate()){  // if message was sent today
                Logger.log(sujet+' du '+msg[m].getDate()+'  >> transfert message Nr '+count+'\n\n');
                try{
                  msg[m].forward(trfTo,{name:ori,replyTo:ori});
                }catch(err){
                  GmailApp.sendEmail(Session.getActiveUser().getEmail(), "Erreur de transfert, message de "+ori+" avec le sujet "+sujet
                                               +" n'a pas été transféré","Erreur de transfert, message de "+ori+" avec le sujet "+sujet+" n'a pas été transféré") ERROR MSG : "+err;
                           }
              }else{
                Logger.log(sujet+' du '+msg[m].getDate()+'  >> pas transféré');
              }
            } 
          }
         GmailApp.sendEmail("[email protected]","log transfert", Logger.getLog());// I use my address to keep an eye on what happens
        }