ºÝºÝߣ

ºÝºÝߣShare a Scribd company logo
do something useful with 
Apps Script in 5 minutes 
7. Log who you sent emails to in a sheet 
Bruce McPherson 
www.mcpher.com
Snippet objectives 
¡ñ Use the lessons learned in ¡®using a spreadsheet as a 
database¡¯ 
¡ñ Search email for a particular topic and write recipient 
details to a sheet 
¡ñ Learn about exponential backoff and Array functions 
Libraries used 
¡ñ database abstraction 
¡ñ driver sheet 
¡ñ useful snippets
Add libraries to script 
¡ñ create a spreadsheet 
¡ñ get its id 
¡ñ create a script 
¡ñ Open resources 
¡ñ Add references to libraries 
MHfCjPQlweartW45xYs6hFai_d-phDA33 
Mrckbr9_w7PCphJtOzhzA_Cz3TLx7pV4j 
Mcbr-v4SsYKJP7JMohttAZyz3TLx7pV4j
layout what you are going to do 
function myFunction() { 
// get all email threads matching search query 
// extract the messages and recipients for each thread 
// open a sheet 
// clear sheet 
// write results 
}
get all matching email threads 
For this example, we¡¯ll keep it simple - if you expected many results you¡¯d need to handle continuation as by default this 
only returns a chunk of the matching queries. 
What you¡¯ll get back is an array of GMailThread 
// get all email threads matching search query 
var threads = GmailApp.search("The Excel Liberation forum has moved to a Google+ community");
set up exponential backoff 
Getting messages within threads is rate limited in Google Apps Script. If we ask for too many too quickly, it will fail. 
Exponential backoff is a technique that recovers from errors like this and tries again. You¡¯ll only be able to process 
about 300 messages within the 6 minute GAS execution quota 
var emails = threads.reduce ( function (p,c) { 
// get messages within each thread and append each recipient 
cUseful.rateLimitExpBackoff(function () { 
}); 
return p; 
},[]);
get the message threads 
Each thread can contain multiple messages, go through them using Array.forEach() to extract info from each method 
var emails = threads.reduce ( function (p,c) { 
// get messages within each thread and append each recipient 
cUseful.rateLimitExpBackoff(function () { 
c.getMessages().forEach(function(d) { 
}); 
}); 
return p; 
},[]);
Map the recipients 
Each message can contain multiple recipients in the To: property. These are comma separated so we can use String. 
split(¡°,¡±) to create an array, then Array.Map() to transform each item and extract the summary information we need into 
a new object. Finally these are appended to the growing array being built up by .reduce() 
var emails = threads.reduce ( function (p,c) { 
// get messages within each thread and append each recipient 
cUseful.rateLimitExpBackoff(function () { 
c.getMessages().forEach(function(d) { 
cUseful.arrayAppend(p, d.getTo().split(",").map(function(e) { 
return {to:e,subject:d.getSubject(),dateSent:d.getDate().toString(),from:d.getFrom()}; 
})); 
}); 
}); 
return p; 
},[]);
Open sheet 
Using database abstraction, open a sheet as a database. 
// open a new sheet 
var handler = new cDbAbstraction.DbAbstraction(cDriverSheet, { 
"siloid": "emails", 
"dbid": "1yTQFdN_O2nFb9obm7AHCTmPKpf5cwAd78uNQJiCcjPk" 
}); 
and remove any data already there 
// remove anything already there 
var result = handler.remove(); 
if (handler.handleCode < 0) throw JSON.stringify(result);
Log the results 
Using Array.sort() , sort by recipient email address then write the results to a sheet 
// sort and log results 
var result = handler.save(emails.sort(function (a,b) { 
return a.to > b.to ? 1 : (a.to < b.to ? -1 : 0) ; 
})); 
if (handler.handleCode < 0) throw JSON.stringify(result);
Run and authorize it
Here¡¯s the result
The whole thing 
function myFunction() { 
// get all matching emails 
var threads = GmailApp.search( 
"The Excel Liberation forum has moved to a Google+ community"); 
var emails = threads.reduce ( function (p,c) { 
// get messages within each thread and append each recipient 
cUseful.rateLimitExpBackoff(function () { 
c.getMessages().forEach(function(d) { 
cUseful.arrayAppend(p, d.getTo().split(",").map(function(e) { 
return { 
to:e, 
subject:d.getSubject(), 
dateSent:d.getDate().toString(), 
from:d.getFrom() }; 
})); 
}); 
}); 
return p; 
},[]); 
// open a new sheet 
var handler = new cDbAbstraction.DbAbstraction ( 
cDriverSheet, { 
"siloid": "emails", 
"dbid": "1yTQFdN_O2nFb9obm7AHCTmPKpf5cwAd78uNQJiCcjPk" 
}); 
if (!handler.isHappy()) throw 'could not open sheet'; 
// remove anything already there 
var result = handler.remove(); 
if (handler.handleCode < 0) throw JSON.stringify(result); 
// sort and log results 
var result = handler.save(emails.sort(function (a,b) { 
return a.to > b.to ? 1 : (a.to < b.to ? -1 : 0) ; 
})); 
if (handler.handleCode < 0) throw JSON.stringify(result); 
}
Homework 
Apps Script quota prevents you dealing with 
more than about 300 threads within the 
execution time quota. 
Figure out how to deal with more than that 
using search(query, start, max) and running the 
task several times
Follow up materials 
Take a copy of this script 
Take a copy of these slides 
Join me on G+, or the G+ community 
More on desktop liberation 
More on database abstraction 
More 5 minute things

More Related Content

What's hot (20)

PPTX
Google apps script database abstraction exposed version
Bruce McPherson
?
PPTX
Introduction tomongodb
Lee Theobald
?
PDF
Do something in 5 with gas 9-copy between databases with oauth2
Bruce McPherson
?
PDF
Data backup
Mu Chun Wang
?
TXT
Code
mimidas
?
PPTX
Dbabstraction
Bruce McPherson
?
PPTX
Goa tutorial
Bruce McPherson
?
KEY
¥¯¥Ã¥¯¥Ñ¥Ã¥É ¤Î¤»¤ë¥¢¥×¥ê
Takuto Nishioka
?
KEY
Ajax - a quick introduction
Stefan Pettersson
?
PPTX
Data visualization by Kenneth Odoh
pyconfi
?
PDF
Javascript Continues Integration in Jenkins with AngularJS
Ladislav Prskavec
?
TXT
New text document
Tam Ngo
?
PPTX
Database connectivity in python
baabtra.com - No. 1 supplier of quality freshers
?
PDF
Testowanie JavaScript
Tomasz Bak
?
PDF
JSLab. §¥§à§Þ§ß§Ú§Ü§à§Ó §£§Ú§ä§Ñ§Ý§Ú§Û. "ES6 §Ô§Ö§ß§Ö§â§Ñ§ä§à§â§í §Ú Koa.js"
GeeksLab Odessa
?
PPTX
Synapse india dotnet development overloading operater part 4
Synapseindiappsdevelopment
?
PDF
G* on GAE/J Ìô‘龎
Tsuyoshi Yamamoto
?
PDF
VBA API for scriptDB primer
Bruce McPherson
?
PDF
G*¤Ê¥¯¥é¥¦¥É ¡«ë…¤Î¤«¤Ê¤¿¤Ë¡«
Tsuyoshi Yamamoto
?
PDF
Web Scrapping with Python
Miguel Miranda de Mattos
?
Google apps script database abstraction exposed version
Bruce McPherson
?
Introduction tomongodb
Lee Theobald
?
Do something in 5 with gas 9-copy between databases with oauth2
Bruce McPherson
?
Data backup
Mu Chun Wang
?
Code
mimidas
?
Dbabstraction
Bruce McPherson
?
Goa tutorial
Bruce McPherson
?
¥¯¥Ã¥¯¥Ñ¥Ã¥É ¤Î¤»¤ë¥¢¥×¥ê
Takuto Nishioka
?
Ajax - a quick introduction
Stefan Pettersson
?
Data visualization by Kenneth Odoh
pyconfi
?
Javascript Continues Integration in Jenkins with AngularJS
Ladislav Prskavec
?
New text document
Tam Ngo
?
Database connectivity in python
baabtra.com - No. 1 supplier of quality freshers
?
Testowanie JavaScript
Tomasz Bak
?
JSLab. §¥§à§Þ§ß§Ú§Ü§à§Ó §£§Ú§ä§Ñ§Ý§Ú§Û. "ES6 §Ô§Ö§ß§Ö§â§Ñ§ä§à§â§í §Ú Koa.js"
GeeksLab Odessa
?
Synapse india dotnet development overloading operater part 4
Synapseindiappsdevelopment
?
G* on GAE/J Ìô‘龎
Tsuyoshi Yamamoto
?
VBA API for scriptDB primer
Bruce McPherson
?
G*¤Ê¥¯¥é¥¦¥É ¡«ë…¤Î¤«¤Ê¤¿¤Ë¡«
Tsuyoshi Yamamoto
?
Web Scrapping with Python
Miguel Miranda de Mattos
?

Similar to Do something in 5 with gas 7-email log (11)

PDF
UiPath Studio Web workshop series - Day 8
DianaGray10
?
PPTX
Google Apps Script the Authentic{ated} Mobile Playground
Martin Hawksey
?
PDF
Extending Google Apps/Spreadsheet using Google Apps Script
Dipali Vyas
?
PDF
Enterprise workflow with Apps Script
ccherubino
?
PPT
GAS Session
BVCOE
?
PDF
Google apps script
Simon Su
?
PPTX
Google Apps Script for Beginners- Amazing Things with Code
Laurence Svekis ?
?
PDF
App script
Choong Ping Teo
?
PDF
Google: Drive, Documents and Apps Script - How to work efficiently and happily
Alessandra Santi
?
PDF
Power your apps with Gmail, Google Drive, Calendar, Sheets, ºÝºÝߣs, Apps Scri...
wesley chun
?
PDF
Programming Google apps with the G Suite APIs
DevFest DC
?
UiPath Studio Web workshop series - Day 8
DianaGray10
?
Google Apps Script the Authentic{ated} Mobile Playground
Martin Hawksey
?
Extending Google Apps/Spreadsheet using Google Apps Script
Dipali Vyas
?
Enterprise workflow with Apps Script
ccherubino
?
GAS Session
BVCOE
?
Google apps script
Simon Su
?
Google Apps Script for Beginners- Amazing Things with Code
Laurence Svekis ?
?
App script
Choong Ping Teo
?
Google: Drive, Documents and Apps Script - How to work efficiently and happily
Alessandra Santi
?
Power your apps with Gmail, Google Drive, Calendar, Sheets, ºÝºÝߣs, Apps Scri...
wesley chun
?
Programming Google apps with the G Suite APIs
DevFest DC
?
Ad

Recently uploaded (20)

PDF
5991-5857_Agilent_MS_Theory_EN (1).pdf. pdf
NohaSalah45
?
PDF
Business Automation Solution with Excel 1.1.pdf
Vivek Kedia
?
PPTX
RESEARCH-FINAL-GROUP-3, about the final .pptx
gwapokoha1
?
PPTX
Indigo dyeing Presentation (2).pptx as dye
shreeroop1335
?
PDF
SaleServicereport and SaleServicereport
2251330007
?
PPTX
Generative AI Boost Data Governance and Quality- Tejasvi Addagada
Tejasvi Addagada
?
PDF
ilide.info-tg-understanding-culture-society-and-politics-pr_127f984d2904c57ec...
jed P
?
PPTX
Monitoring Improvement ( Pomalaa Branch).pptx
fajarkunee
?
PPTX
Artificial intelligence Presentation1.pptx
SaritaMahajan5
?
PDF
NSEST - 2025-Brochure srm institute of science and technology
MaiyalaganT
?
PDF
Informatics Market Insights AI Workforce.pdf
karizaroxx
?
PDF
NVIDIA Triton Inference Server, a game-changing platform for deploying AI mod...
Tamanna36
?
PDF
¶Ù²¹³Ù¨¤²¹²¹²¹²¹²¹²¹²¹²¹²¹±ð²Ô²µ¾±²Ô±ð±ð±ð±ð±ð±ð±ð±ð±ð±ð±ð±ð±ð±ð±ð±ð±ð±ð±ð±ð±ð±ð±ð
juadsr96
?
PPTX
Krezentios memories in college data.pptx
notknown9
?
PDF
Exploiting the Low Volatility Anomaly: A Low Beta Model Portfolio for Risk-Ad...
Bradley Norbom, CFA
?
PPTX
Daily, Weekly, Monthly Report MTC March 2025.pptx
PanjiDewaPamungkas1
?
PPT
intro to AI dfg fgh gggdrhre ghtwhg ewge
traineramrsiam
?
PDF
Microsoft Power BI - Advanced Certificate for Business Intelligence using Pow...
Prasenjit Debnath
?
PPTX
Project_Update_Summary.for the use from PM
Odysseas Lekatsas
?
PDF
TESDA License NC II PC Operations TESDA, Office Productivity
MELJUN CORTES
?
5991-5857_Agilent_MS_Theory_EN (1).pdf. pdf
NohaSalah45
?
Business Automation Solution with Excel 1.1.pdf
Vivek Kedia
?
RESEARCH-FINAL-GROUP-3, about the final .pptx
gwapokoha1
?
Indigo dyeing Presentation (2).pptx as dye
shreeroop1335
?
SaleServicereport and SaleServicereport
2251330007
?
Generative AI Boost Data Governance and Quality- Tejasvi Addagada
Tejasvi Addagada
?
ilide.info-tg-understanding-culture-society-and-politics-pr_127f984d2904c57ec...
jed P
?
Monitoring Improvement ( Pomalaa Branch).pptx
fajarkunee
?
Artificial intelligence Presentation1.pptx
SaritaMahajan5
?
NSEST - 2025-Brochure srm institute of science and technology
MaiyalaganT
?
Informatics Market Insights AI Workforce.pdf
karizaroxx
?
NVIDIA Triton Inference Server, a game-changing platform for deploying AI mod...
Tamanna36
?
¶Ù²¹³Ù¨¤²¹²¹²¹²¹²¹²¹²¹²¹²¹±ð²Ô²µ¾±²Ô±ð±ð±ð±ð±ð±ð±ð±ð±ð±ð±ð±ð±ð±ð±ð±ð±ð±ð±ð±ð±ð±ð±ð
juadsr96
?
Krezentios memories in college data.pptx
notknown9
?
Exploiting the Low Volatility Anomaly: A Low Beta Model Portfolio for Risk-Ad...
Bradley Norbom, CFA
?
Daily, Weekly, Monthly Report MTC March 2025.pptx
PanjiDewaPamungkas1
?
intro to AI dfg fgh gggdrhre ghtwhg ewge
traineramrsiam
?
Microsoft Power BI - Advanced Certificate for Business Intelligence using Pow...
Prasenjit Debnath
?
Project_Update_Summary.for the use from PM
Odysseas Lekatsas
?
TESDA License NC II PC Operations TESDA, Office Productivity
MELJUN CORTES
?
Ad

Do something in 5 with gas 7-email log

  • 1. do something useful with Apps Script in 5 minutes 7. Log who you sent emails to in a sheet Bruce McPherson www.mcpher.com
  • 2. Snippet objectives ¡ñ Use the lessons learned in ¡®using a spreadsheet as a database¡¯ ¡ñ Search email for a particular topic and write recipient details to a sheet ¡ñ Learn about exponential backoff and Array functions Libraries used ¡ñ database abstraction ¡ñ driver sheet ¡ñ useful snippets
  • 3. Add libraries to script ¡ñ create a spreadsheet ¡ñ get its id ¡ñ create a script ¡ñ Open resources ¡ñ Add references to libraries MHfCjPQlweartW45xYs6hFai_d-phDA33 Mrckbr9_w7PCphJtOzhzA_Cz3TLx7pV4j Mcbr-v4SsYKJP7JMohttAZyz3TLx7pV4j
  • 4. layout what you are going to do function myFunction() { // get all email threads matching search query // extract the messages and recipients for each thread // open a sheet // clear sheet // write results }
  • 5. get all matching email threads For this example, we¡¯ll keep it simple - if you expected many results you¡¯d need to handle continuation as by default this only returns a chunk of the matching queries. What you¡¯ll get back is an array of GMailThread // get all email threads matching search query var threads = GmailApp.search("The Excel Liberation forum has moved to a Google+ community");
  • 6. set up exponential backoff Getting messages within threads is rate limited in Google Apps Script. If we ask for too many too quickly, it will fail. Exponential backoff is a technique that recovers from errors like this and tries again. You¡¯ll only be able to process about 300 messages within the 6 minute GAS execution quota var emails = threads.reduce ( function (p,c) { // get messages within each thread and append each recipient cUseful.rateLimitExpBackoff(function () { }); return p; },[]);
  • 7. get the message threads Each thread can contain multiple messages, go through them using Array.forEach() to extract info from each method var emails = threads.reduce ( function (p,c) { // get messages within each thread and append each recipient cUseful.rateLimitExpBackoff(function () { c.getMessages().forEach(function(d) { }); }); return p; },[]);
  • 8. Map the recipients Each message can contain multiple recipients in the To: property. These are comma separated so we can use String. split(¡°,¡±) to create an array, then Array.Map() to transform each item and extract the summary information we need into a new object. Finally these are appended to the growing array being built up by .reduce() var emails = threads.reduce ( function (p,c) { // get messages within each thread and append each recipient cUseful.rateLimitExpBackoff(function () { c.getMessages().forEach(function(d) { cUseful.arrayAppend(p, d.getTo().split(",").map(function(e) { return {to:e,subject:d.getSubject(),dateSent:d.getDate().toString(),from:d.getFrom()}; })); }); }); return p; },[]);
  • 9. Open sheet Using database abstraction, open a sheet as a database. // open a new sheet var handler = new cDbAbstraction.DbAbstraction(cDriverSheet, { "siloid": "emails", "dbid": "1yTQFdN_O2nFb9obm7AHCTmPKpf5cwAd78uNQJiCcjPk" }); and remove any data already there // remove anything already there var result = handler.remove(); if (handler.handleCode < 0) throw JSON.stringify(result);
  • 10. Log the results Using Array.sort() , sort by recipient email address then write the results to a sheet // sort and log results var result = handler.save(emails.sort(function (a,b) { return a.to > b.to ? 1 : (a.to < b.to ? -1 : 0) ; })); if (handler.handleCode < 0) throw JSON.stringify(result);
  • 13. The whole thing function myFunction() { // get all matching emails var threads = GmailApp.search( "The Excel Liberation forum has moved to a Google+ community"); var emails = threads.reduce ( function (p,c) { // get messages within each thread and append each recipient cUseful.rateLimitExpBackoff(function () { c.getMessages().forEach(function(d) { cUseful.arrayAppend(p, d.getTo().split(",").map(function(e) { return { to:e, subject:d.getSubject(), dateSent:d.getDate().toString(), from:d.getFrom() }; })); }); }); return p; },[]); // open a new sheet var handler = new cDbAbstraction.DbAbstraction ( cDriverSheet, { "siloid": "emails", "dbid": "1yTQFdN_O2nFb9obm7AHCTmPKpf5cwAd78uNQJiCcjPk" }); if (!handler.isHappy()) throw 'could not open sheet'; // remove anything already there var result = handler.remove(); if (handler.handleCode < 0) throw JSON.stringify(result); // sort and log results var result = handler.save(emails.sort(function (a,b) { return a.to > b.to ? 1 : (a.to < b.to ? -1 : 0) ; })); if (handler.handleCode < 0) throw JSON.stringify(result); }
  • 14. Homework Apps Script quota prevents you dealing with more than about 300 threads within the execution time quota. Figure out how to deal with more than that using search(query, start, max) and running the task several times
  • 15. Follow up materials Take a copy of this script Take a copy of these slides Join me on G+, or the G+ community More on desktop liberation More on database abstraction More 5 minute things