Friday, July 31, 2015

Forward Mails Based on Search Criteria

Have you ever wanted to forward all mails that matching a search expression? That option is not available through the Gmail interface but it is relatively easy to do that with a script.

An example of the script is as follow:

function forwardMail() {
  var threads ="before:2009/07/01 after:2009/06/30"); // second search string.
  for (var i in threads) {
    var lastMsg = threads[i].getMessageCount(); //get last message
    var messages = threads[i].getMessages();
    var message = messages[0]; //first mail in the thread
    //var message = messages[lastMsg-1]; // last mail in the thread


In the example above, you can use messages[0] to select the first message in a thread or messages[lastMsg-1] for the last message in a thread.  The last message will usually contains most of the replies of the threads if the participants are the same throughout the thread conversations.

To make sure you get the mails you want to forward, test the search expression in Gmail first.

Wednesday, July 15, 2015

Using MailApp.SendMail

I thought that you could only MailApp.SendMail api in Google Script with standard parameter for example:

MailApp.sendEmail(recipient, subject,body)

However, I just realize that you just need to use braces to use other advance parameters. For example to add cc, you can do the following.

function sendTestMail() 
   var toList = ""; 

   var ccList = "" 
   var subj = "Testing sendmail api"; 
   var bodyContent = "If you receive this mail, then the test is successful"
      + "<br><br>This is a second line"; 

    MailApp.sendEmail({to: toList, cc: ccList, subject: subj, htmlBody: bodyContent});