1
votes

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.

3
You could accomplish this without any code at all, by using rules in gmail.Mogsdad
@Mogsdad Using rules in gmail only allows us to forward mail from specific email addresses, e.g. [email protected]. 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
Not so - you can filter on "from:@companyA.com". GMail does substring searches.Mogsdad
@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
@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 InboxNguyen Anh

3 Answers

0
votes

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
    }
0
votes

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 protected]", {subject: subject})}

    threadsToCheck[i].addLabel(labelChecked);


  }  
}
0
votes

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)