SlideShare a Scribd company logo
1 of 15
Download to read offline
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

Google apps script database abstraction exposed version
Google apps script database abstraction   exposed versionGoogle apps script database abstraction   exposed version
Google apps script database abstraction exposed versionBruce McPherson
 
Introduction tomongodb
Introduction tomongodbIntroduction tomongodb
Introduction tomongodbLee Theobald
 
Do something in 5 with gas 9-copy between databases with oauth2
Do something in 5 with gas 9-copy between databases with oauth2Do something in 5 with gas 9-copy between databases with oauth2
Do something in 5 with gas 9-copy between databases with oauth2Bruce McPherson
 
クックパッド のせるアプリ
クックパッド のせるアプリクックパッド のせるアプリ
クックパッド のせるアプリTakuto Nishioka
 
Data visualization by Kenneth Odoh
Data visualization by Kenneth OdohData visualization by Kenneth Odoh
Data visualization by Kenneth Odohpyconfi
 
Javascript Continues Integration in Jenkins with AngularJS
Javascript Continues Integration in Jenkins with AngularJSJavascript Continues Integration in Jenkins with AngularJS
Javascript Continues Integration in Jenkins with AngularJSLadislav Prskavec
 
New text document
New text documentNew text document
New text documentTam Ngo
 
Testowanie JavaScript
Testowanie JavaScriptTestowanie JavaScript
Testowanie JavaScriptTomasz Bak
 
JSLab. Домников Виталий. "ES6 генераторы и Koa.js"
JSLab. Домников Виталий. "ES6 генераторы и Koa.js"JSLab. Домников Виталий. "ES6 генераторы и Koa.js"
JSLab. Домников Виталий. "ES6 генераторы и Koa.js"GeeksLab Odessa
 
Synapse india dotnet development overloading operater part 4
Synapse india dotnet development overloading operater part 4Synapse india dotnet development overloading operater part 4
Synapse india dotnet development overloading operater part 4Synapseindiappsdevelopment
 
VBA API for scriptDB primer
VBA API for scriptDB primerVBA API for scriptDB primer
VBA API for scriptDB primerBruce McPherson
 
G*なクラウド ~雲のかなたに~
G*なクラウド ~雲のかなたに~G*なクラウド ~雲のかなたに~
G*なクラウド ~雲のかなたに~Tsuyoshi Yamamoto
 

What's hot (20)

Google apps script database abstraction exposed version
Google apps script database abstraction   exposed versionGoogle apps script database abstraction   exposed version
Google apps script database abstraction exposed version
 
Introduction tomongodb
Introduction tomongodbIntroduction tomongodb
Introduction tomongodb
 
Do something in 5 with gas 9-copy between databases with oauth2
Do something in 5 with gas 9-copy between databases with oauth2Do something in 5 with gas 9-copy between databases with oauth2
Do something in 5 with gas 9-copy between databases with oauth2
 
Data backup
Data backupData backup
Data backup
 
Code
CodeCode
Code
 
Dbabstraction
DbabstractionDbabstraction
Dbabstraction
 
Goa tutorial
Goa tutorialGoa tutorial
Goa tutorial
 
クックパッド のせるアプリ
クックパッド のせるアプリクックパッド のせるアプリ
クックパッド のせるアプリ
 
Ajax - a quick introduction
Ajax - a quick introductionAjax - a quick introduction
Ajax - a quick introduction
 
Data visualization by Kenneth Odoh
Data visualization by Kenneth OdohData visualization by Kenneth Odoh
Data visualization by Kenneth Odoh
 
Javascript Continues Integration in Jenkins with AngularJS
Javascript Continues Integration in Jenkins with AngularJSJavascript Continues Integration in Jenkins with AngularJS
Javascript Continues Integration in Jenkins with AngularJS
 
New text document
New text documentNew text document
New text document
 
RxSubject And Operators
RxSubject And OperatorsRxSubject And Operators
RxSubject And Operators
 
Database connectivity in python
Database connectivity in pythonDatabase connectivity in python
Database connectivity in python
 
Testowanie JavaScript
Testowanie JavaScriptTestowanie JavaScript
Testowanie JavaScript
 
JSLab. Домников Виталий. "ES6 генераторы и Koa.js"
JSLab. Домников Виталий. "ES6 генераторы и Koa.js"JSLab. Домников Виталий. "ES6 генераторы и Koa.js"
JSLab. Домников Виталий. "ES6 генераторы и Koa.js"
 
Synapse india dotnet development overloading operater part 4
Synapse india dotnet development overloading operater part 4Synapse india dotnet development overloading operater part 4
Synapse india dotnet development overloading operater part 4
 
G* on GAE/J 挑戦編
G* on GAE/J 挑戦編G* on GAE/J 挑戦編
G* on GAE/J 挑戦編
 
VBA API for scriptDB primer
VBA API for scriptDB primerVBA API for scriptDB primer
VBA API for scriptDB primer
 
G*なクラウド ~雲のかなたに~
G*なクラウド ~雲のかなたに~G*なクラウド ~雲のかなたに~
G*なクラウド ~雲のかなたに~
 

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

Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs偉格 高
 
Php Reusing Code And Writing Functions
Php Reusing Code And Writing FunctionsPhp Reusing Code And Writing Functions
Php Reusing Code And Writing Functionsmussawir20
 
Salesforce, APEX Concepts
Salesforce, APEX ConceptsSalesforce, APEX Concepts
Salesforce, APEX ConceptsGaurish Goel
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIEduardo Bergavera
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7Vince Vo
 
Getting started with ES6
Getting started with ES6Getting started with ES6
Getting started with ES6Nitay Neeman
 
Symfony messenger - PHPers Summit 2019
Symfony messenger - PHPers Summit 2019Symfony messenger - PHPers Summit 2019
Symfony messenger - PHPers Summit 2019Michał Kurzeja
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойSigma Software
 
Intro to ES6 and why should you bother !
Intro to ES6 and why should you bother !Intro to ES6 and why should you bother !
Intro to ES6 and why should you bother !Gaurav Behere
 
Enterprise workflow with Apps Script
Enterprise workflow with Apps ScriptEnterprise workflow with Apps Script
Enterprise workflow with Apps Scriptccherubino
 
node.js, javascript and the future
node.js, javascript and the futurenode.js, javascript and the future
node.js, javascript and the futureJeff Miccolis
 

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

Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs
 
Matlab functions
Matlab functionsMatlab functions
Matlab functions
 
Php Reusing Code And Writing Functions
Php Reusing Code And Writing FunctionsPhp Reusing Code And Writing Functions
Php Reusing Code And Writing Functions
 
Salesforce, APEX Concepts
Salesforce, APEX ConceptsSalesforce, APEX Concepts
Salesforce, APEX Concepts
 
WD programs descriptions.docx
WD programs descriptions.docxWD programs descriptions.docx
WD programs descriptions.docx
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part II
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7
 
Getting started with ES6
Getting started with ES6Getting started with ES6
Getting started with ES6
 
Celery with python
Celery with pythonCelery with python
Celery with python
 
Week 12 code
Week 12 codeWeek 12 code
Week 12 code
 
Symfony messenger - PHPers Summit 2019
Symfony messenger - PHPers Summit 2019Symfony messenger - PHPers Summit 2019
Symfony messenger - PHPers Summit 2019
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
 
Intro to ES6 and why should you bother !
Intro to ES6 and why should you bother !Intro to ES6 and why should you bother !
Intro to ES6 and why should you bother !
 
Ajax chap 5
Ajax chap 5Ajax chap 5
Ajax chap 5
 
Enterprise workflow with Apps Script
Enterprise workflow with Apps ScriptEnterprise workflow with Apps Script
Enterprise workflow with Apps Script
 
Django Good Practices
Django Good PracticesDjango Good Practices
Django Good Practices
 
Well You Ought To Know (WYOTK) FP&A Automation Series
Well You Ought To Know (WYOTK) FP&A Automation SeriesWell You Ought To Know (WYOTK) FP&A Automation Series
Well You Ought To Know (WYOTK) FP&A Automation Series
 
node.js, javascript and the future
node.js, javascript and the futurenode.js, javascript and the future
node.js, javascript and the future
 
JavaScript Lessons 2023
JavaScript Lessons 2023JavaScript Lessons 2023
JavaScript Lessons 2023
 
SOLID Java Code
SOLID Java CodeSOLID Java Code
SOLID Java Code
 

Recently uploaded

VIP High Class Call Girls Bikaner Anushka 8250192130 Independent Escort Servi...
VIP High Class Call Girls Bikaner Anushka 8250192130 Independent Escort Servi...VIP High Class Call Girls Bikaner Anushka 8250192130 Independent Escort Servi...
VIP High Class Call Girls Bikaner Anushka 8250192130 Independent Escort Servi...Suhani Kapoor
 
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...Suhani Kapoor
 
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...Suhani Kapoor
 
Low Rate Call Girls Bhilai Anika 8250192130 Independent Escort Service Bhilai
Low Rate Call Girls Bhilai Anika 8250192130 Independent Escort Service BhilaiLow Rate Call Girls Bhilai Anika 8250192130 Independent Escort Service Bhilai
Low Rate Call Girls Bhilai Anika 8250192130 Independent Escort Service BhilaiSuhani Kapoor
 
Industrialised data - the key to AI success.pdf
Industrialised data - the key to AI success.pdfIndustrialised data - the key to AI success.pdf
Industrialised data - the key to AI success.pdfLars Albertsson
 
Aminabad Call Girl Agent 9548273370 , Call Girls Service Lucknow
Aminabad Call Girl Agent 9548273370 , Call Girls Service LucknowAminabad Call Girl Agent 9548273370 , Call Girls Service Lucknow
Aminabad Call Girl Agent 9548273370 , Call Girls Service Lucknowmakika9823
 
Customer Service Analytics - Make Sense of All Your Data.pptx
Customer Service Analytics - Make Sense of All Your Data.pptxCustomer Service Analytics - Make Sense of All Your Data.pptx
Customer Service Analytics - Make Sense of All Your Data.pptxEmmanuel Dauda
 
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...Jack DiGiovanna
 
04242024_CCC TUG_Joins and Relationships
04242024_CCC TUG_Joins and Relationships04242024_CCC TUG_Joins and Relationships
04242024_CCC TUG_Joins and Relationshipsccctableauusergroup
 
PKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptxPKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptxPramod Kumar Srivastava
 
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...Sapana Sha
 
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM TRACKING WITH GOOGLE ANALYTICS.pptx
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM  TRACKING WITH GOOGLE ANALYTICS.pptxEMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM  TRACKING WITH GOOGLE ANALYTICS.pptx
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM TRACKING WITH GOOGLE ANALYTICS.pptxthyngster
 
B2 Creative Industry Response Evaluation.docx
B2 Creative Industry Response Evaluation.docxB2 Creative Industry Response Evaluation.docx
B2 Creative Industry Response Evaluation.docxStephen266013
 
Full night 🥵 Call Girls Delhi New Friends Colony {9711199171} Sanya Reddy ✌️o...
Full night 🥵 Call Girls Delhi New Friends Colony {9711199171} Sanya Reddy ✌️o...Full night 🥵 Call Girls Delhi New Friends Colony {9711199171} Sanya Reddy ✌️o...
Full night 🥵 Call Girls Delhi New Friends Colony {9711199171} Sanya Reddy ✌️o...shivangimorya083
 
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Log Analysis using OSSEC sasoasasasas.pptx
Log Analysis using OSSEC sasoasasasas.pptxLog Analysis using OSSEC sasoasasasas.pptx
Log Analysis using OSSEC sasoasasasas.pptxJohnnyPlasten
 
VIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service Amravati
VIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service AmravatiVIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service Amravati
VIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service AmravatiSuhani Kapoor
 

Recently uploaded (20)

VIP High Class Call Girls Bikaner Anushka 8250192130 Independent Escort Servi...
VIP High Class Call Girls Bikaner Anushka 8250192130 Independent Escort Servi...VIP High Class Call Girls Bikaner Anushka 8250192130 Independent Escort Servi...
VIP High Class Call Girls Bikaner Anushka 8250192130 Independent Escort Servi...
 
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
 
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
 
Low Rate Call Girls Bhilai Anika 8250192130 Independent Escort Service Bhilai
Low Rate Call Girls Bhilai Anika 8250192130 Independent Escort Service BhilaiLow Rate Call Girls Bhilai Anika 8250192130 Independent Escort Service Bhilai
Low Rate Call Girls Bhilai Anika 8250192130 Independent Escort Service Bhilai
 
Industrialised data - the key to AI success.pdf
Industrialised data - the key to AI success.pdfIndustrialised data - the key to AI success.pdf
Industrialised data - the key to AI success.pdf
 
Aminabad Call Girl Agent 9548273370 , Call Girls Service Lucknow
Aminabad Call Girl Agent 9548273370 , Call Girls Service LucknowAminabad Call Girl Agent 9548273370 , Call Girls Service Lucknow
Aminabad Call Girl Agent 9548273370 , Call Girls Service Lucknow
 
VIP Call Girls Service Charbagh { Lucknow Call Girls Service 9548273370 } Boo...
VIP Call Girls Service Charbagh { Lucknow Call Girls Service 9548273370 } Boo...VIP Call Girls Service Charbagh { Lucknow Call Girls Service 9548273370 } Boo...
VIP Call Girls Service Charbagh { Lucknow Call Girls Service 9548273370 } Boo...
 
Customer Service Analytics - Make Sense of All Your Data.pptx
Customer Service Analytics - Make Sense of All Your Data.pptxCustomer Service Analytics - Make Sense of All Your Data.pptx
Customer Service Analytics - Make Sense of All Your Data.pptx
 
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
 
04242024_CCC TUG_Joins and Relationships
04242024_CCC TUG_Joins and Relationships04242024_CCC TUG_Joins and Relationships
04242024_CCC TUG_Joins and Relationships
 
PKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptxPKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptx
 
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
 
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM TRACKING WITH GOOGLE ANALYTICS.pptx
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM  TRACKING WITH GOOGLE ANALYTICS.pptxEMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM  TRACKING WITH GOOGLE ANALYTICS.pptx
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM TRACKING WITH GOOGLE ANALYTICS.pptx
 
B2 Creative Industry Response Evaluation.docx
B2 Creative Industry Response Evaluation.docxB2 Creative Industry Response Evaluation.docx
B2 Creative Industry Response Evaluation.docx
 
Full night 🥵 Call Girls Delhi New Friends Colony {9711199171} Sanya Reddy ✌️o...
Full night 🥵 Call Girls Delhi New Friends Colony {9711199171} Sanya Reddy ✌️o...Full night 🥵 Call Girls Delhi New Friends Colony {9711199171} Sanya Reddy ✌️o...
Full night 🥵 Call Girls Delhi New Friends Colony {9711199171} Sanya Reddy ✌️o...
 
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
 
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝
 
Log Analysis using OSSEC sasoasasasas.pptx
Log Analysis using OSSEC sasoasasasas.pptxLog Analysis using OSSEC sasoasasasas.pptx
Log Analysis using OSSEC sasoasasasas.pptx
 
VIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service Amravati
VIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service AmravatiVIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service Amravati
VIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service Amravati
 
E-Commerce Order PredictionShraddha Kamble.pptx
E-Commerce Order PredictionShraddha Kamble.pptxE-Commerce Order PredictionShraddha Kamble.pptx
E-Commerce Order PredictionShraddha Kamble.pptx
 

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