Google Scripts for Gmail


Here you can find a few Gmail related scripts.
Archive non read emails in Inbox
This script archive every email in your inbox that is not read, keeping your inbox clean. You can set it up to run it periodically, like for instance, the first day of every month.
function archiveInbox() {
// Every thread in your Inbox that is read.
var threads = GmailApp.search("label:Inbox is:read");
  for (var i = 0; i < threads.length; i++) {
    threads[i].moveToArchive();
  }
}
Copy attached files to Google Drive
This script send attached files from selected emails directly to Google Drive. You need to create a gmail label (like "GoogleDrive") and label the emails you need the attachments from with it. You also need to create a folder in Google Drive's root (like "Gmail") in which attached files will be saved. You can have it running periodically every "x" minutes.
function sendToGDrive() {  
  var gLabel  = "GoogleDrive";
  var gFolder = "Gmail";
  var threads = GmailApp.search("label:" + gLabel, 0, 5);  
  var folder  = getFolder(gFolder);  
  for (var x=0; x<threads.length; x++) {  
    var messages = threads[x].getMessages();
    for (var y=0; y<messages.length; y++) {    
      var att = messages[y].getAttachments();    
      for (var z=0; z<att.length; z++) {
        try {
          var file = folder.createFile(att[z]);
          Utilities.sleep(1000);
        }
        catch (e) {
          GmailApp.sendEmail(
            Session.getActiveUser().getUserLoginId(),
            "Error: " + e.message
          );
        }
      }    
    }  
    GmailApp.getUserLabelByName(gLabel)
      .removeFromThread(threads[x]);
  }
}

function getFolder(parent) {
  var parentFolder, searchFolder = DriveApp.getFoldersByName(parent);
  if (searchFolder.hasNext()) {
    parentFolder = searchFolder.next();
  } else {
    parentFolder = DriveApp.createFolder(parent);
  }
  return parentFolder;
}
Gmail no response label
This script goes through your Gmail Inbox and finds recent emails where you were the last respondent. It applies a nice label to them, so you can see them in Priority Inbox or do something else. To remove and ignore an email thread, just remove the unrespondedLabel and apply the ignoreLabel. This is most effective when paired with a time-based script trigger. For installation instructions, read this blog post: http://jonathan-kim.com/2013/Gmail-No-Response/
// Edit these to your liking.
var unrespondedLabel = 'No Response',
ignoreLabel = 'Ignore No Response',
minTime = '3d',
maxTime = '15d';

// Mapping of Gmail search time units to milliseconds.
var UNIT_MAPPING = {
  h: 36e5, // Hours
  d: 864e5, // Days
  w: 6048e5, // Weeks
  m: 263e7, // Months
  y: 3156e7 // Years
};

var ADD_LABEL_TO_THREAD_LIMIT = 100;
function main() {
  processUnresponded();
  cleanUp();
}

function processUnresponded() {
  var threads = GmailApp.search('yourSearch' + ' older_than:' + minTime + ' newer_than:' + maxTime),
      threadMessages = GmailApp.getMessagesForThreads(threads),
      unrespondedThreads = [],
      minTimeAgo = new Date();
  minTimeAgo.setTime(subtract(minTimeAgo, minTime));
  Logger.log('Processing ' + threads.length + ' threads.');

  // Filter threads where I was the last respondent.
  threadMessages.forEach(function(messages, i) {
  var thread = threads[i],
      lastMessage = messages[messages.length - 1],
      lastFrom = lastMessage.getFrom(),
      lastTo = lastMessage.getTo(), // I don't want to hear about it when I am sender and receiver
      lastMessageIsOld = lastMessage.getDate().getTime() < minTimeAgo.getTime();
    if (isMe(lastFrom) && !isMe(lastTo) && lastMessageIsOld && !threadHasLabel(thread, ignoreLabel)) {
      unrespondedThreads.push(thread);
    }
  })

  // Mark unresponded in bulk.
  markUnresponded(unrespondedThreads);
  Logger.log('Updated ' + unrespondedThreads.length + ' messages.');
}

function subtract(date, timeStr) {
  // Takes a date object and subtracts a Gmail-style time string (e.g. '5d').
  // Returns a new date object.
  var re = /^([0-9]+)([a-zA-Z]+)$/,
      parts = re.exec(timeStr),
      val = parts && parts[1],
        unit = parts && parts[2],
          ms = UNIT_MAPPING[unit];
  return date.getTime() - (val * ms);
}

function isMe(fromAddress) {
  var addresses = getEmailAddresses();
  for (i = 0; i < addresses.length; i++) {
    var address = addresses[i],
        r = RegExp(address, 'i');
    if (r.test(fromAddress)) {
      return true;
    }
  }
  return false;
}

function getEmailAddresses() {
  // Cache email addresses to cut down on API calls.
  if (!this.emails) {
    Logger.log('No cached email addresses. Fetching.');
    var me = Session.getActiveUser().getEmail(),
        emails = GmailApp.getAliases();
    emails.push(me);
    this.emails = emails;
    Logger.log('Found ' + this.emails.length + ' email addresses that belong to you.');
  }
  return this.emails;
}

function threadHasLabel(thread, labelName) {
  var labels = thread.getLabels();
  for (i = 0; i < labels.length; i++) {
    var label = labels[i];
    if (label.getName() == labelName) {
      return true;
    }
  }
  return false;
}

function markUnresponded(threads) {
  var label = getLabel(unrespondedLabel);
  // addToThreads has a limit of 100 threads. Use batching.
  if (threads.length > ADD_LABEL_TO_THREAD_LIMIT) {
    for (var i = 0; i < Math.ceil(threads.length / ADD_LABEL_TO_THREAD_LIMIT); i++) {
      label.addToThreads(threads.slice(100 * i, 100 * (i + 1)));
    }
  } else {
    label.addToThreads(threads);
  }
}

function getLabel(labelName) {
  // Cache the labels.
  this.labels = this.labels || {};
  label = this.labels[labelName];
  if (!label) {
    Logger.log('Could not find cached label "' + labelName + '". Fetching.', this.labels);
    var label = GmailApp.getUserLabelByName(labelName);
    if (label) {
      Logger.log('Label exists.');
    } else {
      Logger.log('Label does not exist. Creating it.');
      label = GmailApp.createLabel(labelName);
    }
    this.labels[labelName] = label;
  }
  return label;
}

function cleanUp() {
  var label = getLabel(unrespondedLabel),
      iLabel = getLabel(ignoreLabel),
      threads = label.getThreads(),
      expiredThreads = [],
      expiredDate = new Date();
  expiredDate.setTime(subtract(expiredDate, maxTime));
  if (!threads.length) {
    Logger.log('No threads with that label');
    return;
  } else {
    Logger.log('Processing ' + threads.length + ' threads.');
  }
  threads.forEach(function(thread) {
    var lastMessageDate = thread.getLastMessageDate();
    // Remove all labels from expired threads.
    if (lastMessageDate.getTime() < expiredDate.getTime()) {
      Logger.log('Thread expired');
      expiredThreads.push(thread);
    } else {
      Logger.log('Thread not expired');
    }
  });
  label.removeFromThreads(expiredThreads);
  iLabel.removeFromThreads(expiredThreads);
  Logger.log(expiredThreads.length + ' unresponded messages expired.');
}
Personalized Spam label
Sometimes you receive email messages that are not Spam, but you have no interest in keeping them forever. To remove them from your Inbox, you just have to create a Gmail label: "Delete Me", and create the necessary filters to add this label to wherever email you consider as deletable. You can have this script running once per day or as you consider best.
function archiveDeleteMe() {
  var threads = GmailApp.search("label:Inbox label:delete-me");
  for (var i = 0; i < threads.length; i++) {
    threads[i].moveToArchive();
}
}
Sending to Trash Delete Me labeled emails
Now that your "Delete Me" labeled emails are archived, it is time to send them to trash, but just those older that "x" days (30 days in below example). You can have the script running once per month for instance.
function cleanUp() {
  var threads = GmailApp.search("label:delete-me older_than:30d");
  Logger.log(threads.length+' threads found');
  var batchSize = 100 // Process up to 100 threads at once
  for (var j = 0; j < threads.length; j+=batchSize) {
    GmailApp.moveThreadsToTrash(threads.slice(j, j+batchSize));
  }
  var threads = GmailApp.search("label:delete-me older_than:30d");
  Logger.log(threads.length+' threads found');
  for (var i = 0; i < threads.length; i++) {
   threads[i].moveToTrash();
  }
}
Delete emails in Trash older than "x" days
Supposedly, emails older than 30 days in Trash are automatically deleted, but as you can see by yourself, that is not always the case. To effectively delete emails in Trash older than "x" days (60 days in below script), you just need to have it running periodically.
function cleanUp() {
  var threads = GmailApp.search("in:trash older_than:60d");
  Logger.log(threads.length+' threads found');
  for (var i = 0; i < threads.length; i++) {
    Gmail.Users.Threads.remove("me", threads[i].getId());
  }
}
Delete emails with attachments older than "x" days
Attachments can consume a lot of space over time. Next script adds label "Delete Me" to emails with attachments older than 600 days (2 years aprox.). Above scripts manage what happen to them after the label is applied. I have it running once per month.
function DeletingMailwithAttach() {
  var threads = GmailApp.search("has:attachment -is:important -label:starred -label:Delete-me older_than:600d");
  var myLabel = GmailApp.getUserLabelByName('Delete me');
  var batchSize = 100 // Process up to 100 threads at once
  for (var j = 0; j < threads.length; j+=batchSize) {
    myLabel.addToThreads(threads.slice(j, j+batchSize));
  }
}
Get links from Emails
In some emails you can have some links you want to recover, for instance, when you receive rss feeds directly to your Inbox using a service like Blogtrottr from a download center. You can use the following script to save the links directly to a file ("links.txt") in Google Drive, and do whatever you want to do with them afterwards.
function GetLinksfromEmail(){
  var links = '';
  var threads = GmailApp.search('yoursearch');  
  if (threads.length>0){
    Logger.log(threads.length + ' threads found');
    for (var i = 0; i < threads.length; i++) {  
      var messages = threads[i].getMessages();
      for (var j = 0; j < messages.length; j++) {    
        var mailBody = messages[0].getPlainBody();  
        var maillinks = getLinks(mailBody);
        for (var k = 0; k < maillinks.length; k++ ){
          if (maillinks[k]){
            var links = links + '\n' + maillinks[k];          
          }
        }
      }  
      threads[i].markRead();    
    }      
    var links = revomeduplicatedlines(links);  
    var thefile = DriveApp.getFilesByName("links.txt");
    if (thefile.hasNext()) {
      var file = thefile.next();
      var contentBlob = file.getAs('text/plain');
      var content = contentBlob.getDataAsString();  
      var newcontent = content + '\n' + links;      
    }      
    var fixcontent = newcontent.replace(/,,,,/g, '');
    file.setContent(fixcontent);  
  }
  else {Logger.log('no threads found');}
}

function getLinks(string){
  var re = /\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'"".,<>?«»“”‘’]))/i;
  return re.exec(string);  
}

function revomeduplicatedlines(string){
  var array = string.split('\n');
  Logger.log(array);
  var newarray = [];
  newarray.push(array[0]);

  for (var i = 1; i<array.length; i++){
     if (newarray.toString().indexOf(array[i])>=0){
        Logger.log('duplicate line found');
      }    
      else {
        Logger.log('not duplicate line found');
        newarray.push(array[i]);
      }
    }  
  var newstring = newarray.toString().replace(/,/g, '\n');
  return newstring;
  }
Get important emails with no response back to your inbox
You probably know a Chrome extension called Boomerang. The idea is to get important emails with no response back to your Inbox. For get this to work, you need to create first a label "Boomerang", and sublabels "Returned", "01 day", "02 days", "03 days", "01 week", "02 weeks" and "01 month", or any sublabel for the amount of time you want to receive the emails. Next, to the email you want to follow, you add the corresponding sublabel. When the emails get back to your Inbox, it does with label "Boomerang/Returned". I have this running every day at 7AM and 9PM.
function Boomerang() {
  var labels = [];
  labels[0]=['01-day','1d','01 day'];
  labels[1]=['02-days','2d','02 days'];
  labels[2]=['03-days','3d','03 days'];
  labels[3]=['01-week','7d','01 week'];
  labels[4]=['02-weeks','14d','02 weeks'];
  labels[5]=['01-month','30d','01 month'];
  for (var j = 0; j<6;j++){
    var search = 'label:Boomerang-' + labels[j][0] + ' older_than:' + labels[j][1];  
    var threads = GmailApp.search(search);
    var mylabel = 'Boomerang/' + labels[j][2];  
    var myLabel = GmailApp.getUserLabelByName(mylabel);
    for (var i = 0; i < threads.length; i++) {
      threads[i].markUnread();
      threads[i].moveToInbox();
      threads[i].markImportant();
    }
  }
  myLabel.removeFromThreads(threads);
  var myLabel = GmailApp.getUserLabelByName('Boomerang/Returned');
  myLabel.addToThreads(threads);
}
Remove Boomerang label when the email have a response.
If you get a response before the time you set with the Boomerang label, then the correct thing to do is to remove the label from the email. I have this running every minute.
function removefromboomerangReturnedifReplied() {
  var labels = [];
  labels[0]=['01-day','01 day'];
  labels[1]=['02-days','02 days'];
  labels[2]=['03-days','03 days'];
  labels[3]=['01-week','01 week'];
  labels[4]=['02-weeks','02 weeks'];
  labels[5]=['01-month','01 month'];
  // Returned replied by me
  var threads = GmailApp.search("label:Boomerang-Returned is:read");
  var myLabel = GmailApp.getUserLabelByName('Boomerang/Returned');
  myLabel.removeFromThreads(threads);
  //Replied by the other one before it gets returned
  for (var i = 0; i<6;i++){
    var search = 'label:Boomerang-' + labels[i][0] + ' is:unread';
    var threads = GmailApp.search(search);
    if (threads.length>0){
      var mylabel = 'Boomerang/' + labels[i][2];  
      var myLabel = GmailApp.getUserLabelByName(mylabel);
      myLabel.removeFromThreads(threads);
    }
  }
}
Gmail to Evernote.
If you have an Evernote account, you probably know that you can create notes trough emails sent to your Evernote email. You have to create a label called "Evernote" and as many sublabels as books you have in Evernote or just those you want to send notes to. This script finds gmail threads labeled with a Evernote sublabel and forward last message to evernote mail address and removes Evernote sublabel. For more info see http://www.harryonline.net/evernote/send-google-mail-to-evernote/226.
/**
* ---GMail to Evernote---
*
*  Copyright (c) 2012,2013 Harry Oosterveen
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/

/**
*  @author  Harry Oosterveen <mail@harryonline.net>
*  @version 4
*  @since   2012-11-12
*/

/**
*  Find threads labeled with Evernote or sublabel
*  Forward last message to evernote mail address and removes Evernote label or sublabel
*  See http://www.harryonline.net/evernote/send-google-mail-to-evernote/226
*  See https://support.evernote.com/ics/support/KBAnswer.asp?questionID=547
*/

var version = 4;
// Variables for user properties
var evernoteMail, cfg={};
// Sheet for log entries
var logSheet;
// Email of user
var userMail = Session.getActiveUser().getEmail();
var webInterface = false;

function readEvernote()
{
  getUserProperties_();
  checkVersion_();
 
  // obtenemos la fecha de hoy y le damos formato
  var hoy = new Date(); //No necesita datejs
  var fecha = Utilities.formatDate(hoy,Session.getTimeZone(), "yyyy/MM/dd");
  //var mes = Utilities.formatDate(hoy,Session.getTimeZone(), "MM");
  //var dia = Utilities.formatDate(hoy,Session.getTimeZone(), "dd");
  //var fecha = ano+"/"+mes+"/"+dia;


  // Field that can be copied to Evernote
  var hdrFields = { bcc:'Bcc', cc:'Cc', date:'Date', from:'From', replyto:'ReplyTo', subject:'Subject', to:'To' };
 
  try {
    // Catch errors, usually connecting to Google mail
   
    // Label for messages sent to Evernote
    if( cfg.sent_label != '' ) {
      var sentLabel = GmailApp.getUserLabelByName(cfg.sent_label );
    }

    // Find GMail userlabels and filter those that start with 'Evernote'
    var labels = GmailApp.getUserLabels();
    for( var i=0; i < labels.length; i ++ ) {
      var labelPath = labels[i].getName().split('/');
      if( labelPath[0] == cfg.nbk_label && labels[i].getName() != cfg.sent_label ) {
        // Get threads
        var threads = labels[i].getThreads();
        for( var j=0;  j < threads.length;j ++ ) {
          var subject = threads[j].getFirstMessageSubject();
          // Read last mail
          var lastMsg = threads[j].getMessages().pop();
          if( lastMsg.getTo() != evernoteMail ) {
            if( labelPath.length > 1 ) {
              // Add label name (last element) as inbox
              subject += ' !' + fecha + ' @' + labelPath[labelPath.length-1];
            }
            if( cfg.tag != '' ) {
              subject += ' #' + cfg.tag;
            }
            // Read tags from mail
            var msgLabels = threads[j].getLabels();
            for( var k=0; k < msgLabels.length; k ++ ) {
              var msgLabelPath = msgLabels[k].getName().split('/');
              if( msgLabelPath[0] != cfg.nbk_label &&
                 msgLabels[k].getName() != cfg.sent_label &&
                ( cfg.tag_label == '' || msgLabelPath[0] == cfg.tag_label ) ) {
                  subject += ' #' + msgLabelPath.pop();
                }
            }
            // Put header info and link(s) before message body
            var fields = cfg.fields.toLowerCase().split(/[, ]+/);
            var header = '';
            for( var f=0; f < fields.length;  f ++ ) {
              var fldName = hdrFields[fields[f]];
              if( fldName != undefined ) {
                eval( sprintf_( 'var fldValue = lastMsg.get%s();', fldName));
                if( fldValue != '' ) {
                  header += sprintf_( "%s: %s\n", fldName, fldValue );
                }
              }
            }
            header = htmlEncode_( header );
           
            var msgId = lastMsg.getId();
            if( cfg.nacct > 0 ) {
              header += createLink_(mailUrl_( msgId, 0 )) ;
              for( var u=1; u < cfg.nacct; u ++ ) {
                header += ' - ' + createLink_( mailUrl_( msgId, u ), 'user '+ u );
              }
              header += sprintf_( " (%s)\n", userMail );
            }
            if( header != '' ) {
              var body = sprintf_( '<div style="%s">%s</div>%s', cfg.hdrcss, header.replace( /\n/g, "<br/>" ), lastMsg.getBody());
            } else {
              var body = lastMsg.getBody();
            }
            GmailApp.sendEmail(evernoteMail, subject, '', {htmlBody:body, attachments:lastMsg.getAttachments() })
            log_( subject );
            if( sentLabel != undefined ) {
              threads[j].addLabel(sentLabel);
            }
            if( cfg.keep_sent == 'off' ) {
              // Remove message just sent to Evernote
              var sentResults = GmailApp.search("label:sent " + subject, 0, 1);
              if( sentResults.length > 0 ) {
                var sentMsg = sentResults[0].getMessages().pop();
                if( sentMsg.getTo() == evernoteMail ) {
                  sentMsg.moveToTrash();
                }
              }
            }
          }
          // Remove label from thread
          threads[j].removeLabel(labels[i]);        
          //label.removeFromThreads(threads[j]);  
          // Add "Delete me" label from thread
          var deleteme = GmailApp.getUserLabelByName('Delete me');
          deleteme.addToThreads(threads[j]);
       
          Utilities.sleep(1000);
        }
      }
    }
  } catch( e ) {
    Logger.log( '%s: %s %s', e.name, e.message, e.stack );
  }
}

/**
*  Check version with latest version, and send information email when update is available
*  - version ( global var): currently running version
*  - userVersion {version, lastCheck}: last version that user has been informed about
*  - newVersion {version, info}: current version as read from Internet
*/
function checkVersion_()
{
  var mSecDay = 86400000;
  var curDate = new Date();
  var curTime = curDate.getTime();
  if( cfg.version == 0 ) {
    // Spread version checking over the day to avoid all users checking at the same time
    var nextCheck = curTime - Math.floor( Math.random() * mSecDay );
    var userVersion = { nextCheck:nextCheck, version:0 };
  } else {
    var userVersion = JSON.parse( cfg.version );
  }
 
  if( curTime > userVersion.nextCheck ) {
    // Read latest version from Internet
    try {
      var response = UrlFetchApp.fetch("http://gs.harryonline.net/gm2en.json");
      var newVersion = JSON.parse( response.getContentText() );
      if( userVersion.version < newVersion.version  ) {
        // User has not been informed of new version yet
        var message = [];
        if( userVersion.version < Math.floor( newVersion.version )) {
          message.push( "A new version of the Gmail to Evernote script has been released." );
        }
        var doSend = false;
        if( newVersion.info != "" ) {
          // Relevant information for all users
          message.push( newVersion.info );
          doSend = true;
        }
        if( version < Math.floor( newVersion.version )) {
          // Old version, user running own copy, inform only on updates; fractions are used to send announcements
          message.push( "You can find the latest version at http://bit.ly/gmailevernote or https://github.com/harryonline/gmailevernote." );
          doSend = true;
        }
        if( doSend ) {
          sendEmail_( 'update', message.join( "\n\n" ));
        }
        userVersion.version = newVersion.version;
      }
    } catch(e) {
      Logger.log( '%s: %s %s', e.name, e.message, e.stack );
    }
    userVersion.nextCheck += mSecDay;
    UserProperties.setProperty('gm2en_version', Utilities.jsonStringify( userVersion ));
  }
}

/**
*  Read user properties, check and create default values if necessary
*/
function getUserProperties_()
{
 
  var userProps = UserProperties.getProperties();
 
  evernoteMail = userProps['evernoteMail'];
  if( evernoteMail == undefined ) {
    findEvernoteMail_();
  }
 
  // Global variables and default settings
  // Read from user properties, otherwise use defaults
 
  var props = {
'tag' : '',
'log' : '',
'nacct' : 1,
'fields' : 'From, To, Cc, Date',
'hdrcss' : 'border-bottom:1px solid #ccc;padding-bottom:1em;margin-bottom:1em;',
'version' : 0,
'nbk_label' : 'Evernote',
'tag_label' : '',
'sent_label' : '',
    'keep_sent' : 'off',
    'version' : 0
  };
 
  for( var p in props ) {
    var key = 'gm2en_' + p;
    if( userProps[key] == undefined ) {
      switch( p ) {
        case 'log' :
          // Create new log sheet
          cfg[p] = createLogSheet_();
          break;
       
        default:
          // Use default value
          cfg[p] = props[p];
      }
      UserProperties.setProperty(key, cfg[p]);
    } else {
      cfg[p] = userProps[key];
    }
  }
}


/**
*  Find Evernote email address by searching in previous mails
*/
function findEvernoteMail_()
{
  var threads = GmailApp.search('to:@m.evernote.com');
  for( var i=0;  i < threads.length; i ++ ) {
    var messages = threads[i].getMessages();
    for( var j=0; j < messages.length;  j ++ ) {
      var to = messages[j].getTo();
      var mail = to.match( /[\w\.]+@m\.evernote\.com/ );
      if( mail ) {
        evernoteMail = mail[0];
        UserProperties.setProperty('evernoteMail', evernoteMail);
        Logger.log( 'Evernote mail: %s', evernoteMail );
        sendEmail_( 'evernoteMail changed', 'The Gmail to Evernote script will forward messages to ' + evernoteMail );
        return;
      }
    }
  }
  evernoteMail = '';
  if( !webInterface ) {
    sendEmail_( 'evernoteMail not found', 'The Gmail to Evernote script could not find an Evernote email address. '
               + 'Please send a message to your Evernote email address and run the script again.' );
  }
}

/**
*  Add an entry to the logsheet
*  @param {string} subject
*
*/
function log_( subject )
{
  if( cfg.log != '' ) {
    try {
      if( logSheet == undefined ) {
        logSheetParts = cfg.log.split( ':' );
        var ss = SpreadsheetApp.openById(logSheetParts[0]);
        if( logSheetParts.length > 1 ) {
          logSheet = ss.getSheetByName(logSheetParts[1]);
        } else {
          logSheet = ss.getSheets()[0];
        }
      }
      logSheet.appendRow( [new Date(),
                           'Evernote:' + userMail,
                           subject ] );
    } catch(e) {
      Logger.log( '%s at line %s: %s', e.name, e.lineNumber, e.message );
    }
  } else {
    Logger.log( subject );
  }
}

/**
*  Create a new logsheet if it does not exist
*/
function createLogSheet_()
{
  var ss = SpreadsheetApp.create("Gmail to Evernote Log");
  var log = ss.getId();
  sendEmail_( 'logsheet created',
             sprintf_( "The Gmail to Evernote script has created a logsheet with ID: %s\nURL: %s" +
                      "\n\nTo change these settings, visit http://bit.ly/gmailevernote, " +
                      "go to File - Project properties, and click on the User properties tab.",
                      log, ss.getUrl() ));
  var sheet = ss.getSheets()[0];
  sheet.appendRow(['Date', 'Source','Message']);
  return log;
}

/**
*  Send an email message to the user
*/

function sendEmail_( subject, body )
{
  if( webInterface ) {
    messages.push( body );
  } else {
    var postText = "\n\nThis is an automated message from the Gmail to Evernote script.\nFor more information, visit http://www.harryonline.net/tag/gm2en .";
    GmailApp.sendEmail(userMail, 'Gmail to Evernote: ' + subject, body + postText, {noReply:true});
  }
}

/**
*  Create a HTML link
*  @param {string} url
*  @param {string} text, url will be used if text not given
*  @return {string} completed HTML <a> tag
*/

function createLink_( url, text )
{
  if( text == undefined ) {
    text = url;
  }
  return sprintf_( '<a href="%s">%s</a>', url, text );
}

/**
*  Create a Gmail url
*  @param {string} msgId message ID
*  @param {string} user user no, 0 or higher if multiple sign-in
*  @return {string} url of GMail message
*/
function mailUrl_( msgId, user )
{
  return sprintf_( 'https://mail.google.com/mail/u/%s/#inbox/%s', user, msgId );
}

/**
*  Simple alternative for php sprintf-like text replacements
*  Each '%s' in the format is replaced by an additional parameter
*  E.g. sprintf_( '<a href="%s">%s</a>', url, text ) results in '<a href="url">text</a>'
*  @param {string} format text with '%s' as placeholders for extra parameters
*  @return {string} format with '%s' replaced by additional parameters
*/
function sprintf_( format )
{
  for( var i=1; i < arguments.length; i++ ) {
    format = format.replace( /%s/, arguments[i] );
  }
  return format;
}

/**
*  Encode special HTML characters
*  From: http://jsperf.com/htmlencoderegex
*/
function htmlEncode_( html )
{
  return html.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/'/g, '&#39;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

Comentarios

Entradas populares de este blog

Google Scripts