ItGo.me Focus on IT Recommend

Home > google apps script - How to avoid auto-forwarding duplicate emails in Gmail

google apps script - How to avoid auto-forwarding duplicate emails in Gmail

2020阿里云最低价产品入口,含代金券(新老用户有优惠),
入口地址https://www.aliyun.com/minisite/goods

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

When our clients send emails to the
 d 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.

google-apps-script gmail
|
  this question
asked Jun 25 '15 at 16:50 Nguyen Anh 8 2      You could accomplish this without any code at all, by using rules in gmail. –  Mogsdad Jun 26 '15 at 2:42      @Mogsdad Using rules in gmail only allows us to forward mail from specific email addresses, e.g. Myname@companyA.com. If a client company has, let say, 100 individual email addresses, we have to input 100 emails in the rules. Using google script, we could check if a message's sender contains "@companyA.com" and forward it accordingly. –  Nguyen Anh Jun 26 '15 at 5:41      Not so - you can filter on "from:@companyA.com". GMail does substring searches. –  Mogsdad Jun 26 '15 at 12:36      @Mogsdad I just check my Gmail and searching for "from:@companyA.com" works. So I could use filters in Gmail and do not need to use Google script. Thank for your help! –  Nguyen Anh Jun 26 '15 at 16:14      @Mogsdad I found an advantage of using google script over rules in Gmail. When a message is accidentally put into Spam, it will not be auto forwarded even if you move it back to Inbox. Using script, I can auto forward it when I move it back to Inbox –  Nguyen Anh Jun 27 '15 at 1:09  |  show more comments

3 Answers
3

---Accepted---Accepted---Accepted---

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 = "theNewRecipentAddress@domain.com";
      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("myAddressOusideOfDomain@gmail.com","log transfert", Logger.getLog());// I use my address to keep an eye on what happens
    }

|
  this answer
edited Jun 25 '15 at 17:18 answered Jun 25 '15 at 17:00 Serge insas 29.3k 3 31 63      Working with date condition and use a label "checked" for inbox mails is a great idea. Thank you very much. –  Nguyen Anh Jun 26 '15 at 2:39

 | 

Below is my code using date condition and label to automatically forward messages. I also want to ask if there is any way to make forwarding condition shorter (I use indexOf methods and have to specify each condition for forwarding: either contains "companyA.com" or either contains "companyB.com" or contains "companyC.com"

function Auto_forward() {
var labelChecked = GmailApp.getUserLabelByName("test_checked");
  var threadsToCheck = GmailApp.search('in:inbox -label:test_checked newer_than:10h');


  for (var i=0; i<threadsToCheck.length; i++) {
    var message = threadsToCheck[i].getMessages()[0];
    var addressToCheck = message.getFrom();
    var subject = message.getSubject();

    if (addressToCheck.toLowerCase().indexOf("@companyA.com") > -1 || addressToCheck.toLowerCase().indexOf("@companyB.com") > -1)    


    {
      message.forward("email@example.com", {subject: subject})}

    threadsToCheck[i].addLabel(labelChecked);


  }  
}

|
  this answer
answered Jun 26 '15 at 16:36 Nguyen Anh 8 2

 | 

Sometimes, the best program is no program.

GMail's filters already provide the ability to identify incoming mail that meets the criteria you've described. Refer to Advanced Search. For your needs, the from: search allows matching on substrings, including a domain that would cover an entire company:

from:(@company_A.com)

Since filters apply only to the inbox, any messages that are first redirected by other filters or moved to the spam folder automatically will be missed by the filter. That could be avoided by ensuring that your filter order is set to avoid such conflicts, and that the domains you're interested in are in your allowed senders list.

If you are concerned that you may have missed such messages, you can search in the UI anytime for them:

(in:inbox OR in:spam) from:(@company_A.com)

|
  this answer
answered Jun 27 '15 at 12:57 Mogsdad 26.4k 9 63 134

 | 

Recommend:google apps script - Searching emails in gmail based on time

or the time zone difference Please note that the local time zone, calendar, gmail etc. is correctly configured for my timezone, so the emails that I see in my inbox are correctly timed. Only the search is creating an issue. answer 1 >>acce

oriUlr:http://stackoverflow.com/questions/31056232/how-to-avoid-auto-forwarding-duplicate-emails-in-gmail

------splitte line----------------------------