0% found this document useful (0 votes)
55 views96 pages

Google Apps Script Example Code

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views96 pages

Google Apps Script Example Code

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 96

Google Apps Script Coding Example Guide

Mastering Google Apps Script: A Comprehensive Guide

Google Apps Script Introduction


Introduction to CalendarApp
1: Creating an Event
2: Finding Events
3: Deleting an Event
4: Updating an Event
5: Creating a Recurring Event
6: Getting Event Details
7: Adding Guests to an Event
8: Changing Event Visibility
9: Getting Calendar ID
10: Listing All Calendars
Introduction to DocumentApp
1: Creating a New Document
2: Adding Text to a Document
3: Formatting Text
4: Inserting a Table
5: Adding a Header
6: Inserting an Image
7: Creating a Footer
8: Changing Document Properties
9: Finding and Replacing Text
10: Removing Content from a Document
Introduction to DriveApp
1: Creating a New Folder
2: Uploading a File
3: Searching for Files

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
1
4: Moving a File to a Folder
5: Sharing a File
6: Changing File Permissions
7: Deleting a File
8: Listing Files in a Folder
9: Creating a Google Docs File
10: Reading File Content
Introduction to FormApp
1: Creating a New Form
2: Adding a Multiple-Choice Question
3: Creating a Form Response
4: Adding a Section Header
5: Retrieving Form Responses
6: Adding a Date Question
7: Sending Form via Email
8: Changing Form Theme
9: Adding a Linear Scale Question
10: Deleting a Form Item
Introduction to GmailApp
1: Sending an Email
2: Searching Emails
3: Applying Labels to Emails
4: Marking Emails as Read
5: Retrieving Unread Emails
6: Sending an Email with Attachment
7: Creating a Draft Email
8: Deleting an Email Thread
9: Counting Emails from a Sender
10: Fetching Email Body Content
Introduction to MailApp

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
2
1: Sending a Basic Email
2: Sending an Email with HTML Body
3: Sending Emails to Multiple Recipients
4: Sending an Email with Cc and Bcc
5: Sending an Email with an Attachment
6: Sending an Email with Inline Images
7: Retrieving Quota Information
8: Sending a Rich Text Email
9: Setting Reply-To Address
10: Sending Email with Advanced Options
Introduction to SpreadsheetApp
1: Creating a New Spreadsheet
2: Adding Data to a Cell
3: Reading Data from a Range
4: Appending a Row of Data
5: Setting a Formula in a Cell
6: Changing Cell Background Color
7: Finding and Replacing Data
8: Adding a New Sheet
9: Protecting a Range
10: Sorting Data in a Range
Introduction to SlidesApp
1: Creating a New Presentation
2: Adding a Text Box
3: Changing Slide Background Color
4: Adding an Image
5: Duplicating a Slide
6: Adding a Slide with a Predefined Layout
7: Replacing Text in Slides
8: Creating a Hyperlink

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
3
9: Changing Text Style
10: Deleting a Slide
Introduction to ContentService
1: Serving Plain Text Content
Introduction to HtmlService
1: Creating a Simple HTML Page
2: Serving an HTML File
3: Embedding JavaScript in HTML Service
4: Using Templated HTML
5: Serving CSS with HTML
6: Communicating with Google Apps Script Functions
7: Passing Data from Client to Server
8: Incorporating Google Material Design
9: Creating a User Interface for Spreadsheet
10: Serving HTML with IFrame Sandbox Mode
Introduction to HtmlOutput
1: Creating Basic HTML Output
2: Setting the Title of HTML Output
3: Adding Inline CSS to HTML Output
4: Serving HTML Output as a Web App
5: Including JavaScript in HTML Output
6: Using Templated HTML in HTML Output
7: Serving HTML Output with Custom Fonts
8: Embedding External JavaScript and CSS
Introduction to TextOutput
1: Creating Basic Text Output
2: Setting Content Type of Text Output
3: Returning JSON Data
4: Serving Text Output as a Web App
5: Serving XML Data

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
4
6: Returning CSV Data

Google Apps Script Introduction


Welcome to the ultimate guide to mastering Google Apps Script, your key
to unlocking the full potential of automation and integration within the
Google Workspace ecosystem. In this book, we will explore the diverse
functionalities of Google Apps Script and how it empowers you to
streamline your tasks and work more efficiently across various Google
Apps.
Section 1: Introduction to CalendarApp
CalendarApp is your gateway to managing events, schedules, and
calendars programmatically. In this chapter, we will dive into essential tasks
like creating, finding, updating, and deleting events. You'll also learn how to
work with recurring events, access event details, add guests, change event
visibility, retrieve calendar IDs, and list all your calendars.
Section 2: Introduction to DocumentApp
DocumentApp allows you to create, format, and manipulate Google Docs
programmatically. This Section covers creating new documents, adding
text, formatting content, inserting tables, headers, images, footers, and
more. You'll also learn how to change document properties, find and
replace text, and remove content from documents.
Section 3: Introduction to DriveApp
DriveApp provides the tools to manage your Google Drive files and folders
programmatically. In this chapter, you'll discover how to create folders,

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
5
upload files, search for files, move them to folders, share files, change
permissions, delete files, list files in folders, create Google Docs files, and
read file content.
Section 4: Introduction to FormApp
FormApp empowers you to create and manage Google Forms
programmatically. Learn how to create new forms, add questions, manage
form responses, add section headers, retrieve responses, work with date
questions, send forms via email, change form themes, add linear scale
questions, and delete form items.
Section 5: Introduction to GmailApp
GmailApp allows you to interact with Gmail programmatically. Explore tasks
like sending emails, searching emails, applying labels, marking emails as
read, retrieving unread emails, sending emails with attachments, creating
draft emails, deleting email threads, counting emails from specific senders,
and fetching email body content.
Section 6: Introduction to MailApp
MailApp enables you to send and manage emails programmatically. Learn
how to send basic emails, craft HTML-rich emails, send emails to multiple
recipients, use Cc and Bcc, send emails with attachments and inline
images, retrieve quota information, send rich-text emails, set reply-to
addresses, and explore advanced email options.
Section 7: Introduction to SpreadsheetApp
SpreadsheetApp empowers you to work with Google Sheets
programmatically. Discover how to create new spreadsheets, add data to
cells, read data from ranges, append rows, set formulas, change cell

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
6
backgrounds, find and replace data, add new sheets, protect ranges, and
sort data in ranges.
Section 8: Introduction to SlidesApp
SlidesApp lets you create and manage Google Slides presentations
programmatically. Learn how to create new presentations, add text boxes,
change slide backgrounds, insert images, duplicate slides, use predefined
layouts, replace text in slides, create hyperlinks, change text styles, and
delete slides.
Section 9: Introduction to ContentService
ContentService is your tool for serving web content programmatically.
Explore serving plain text, JSON, HTML, and XML content. Learn to handle
POST requests, parse URL parameters, set custom response headers,
serve JSONP content, return raw HTML/JavaScript, and create
downloadable text files.
Section 10: Introduction to HtmlService
HtmlService facilitates the creation of web apps and user interfaces. Master
creating HTML pages, serving HTML files, embedding JavaScript, using
templated HTML, serving CSS, communication between client and server,
passing data, incorporating Google Material Design, and serving HTML
with IFrame sandbox mode.
Section 11: Introduction to HtmlOutput
HtmlOutput allows you to serve HTML content programmatically. Learn to
create basic HTML output, set titles, add inline CSS, serve HTML as a web
app, include JavaScript, use templated HTML, change MIME types, and

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
7
create downloadable HTML files with custom fonts and external
JavaScript/CSS.
Section 12: Introduction to TextOutput
TextOutput is your tool for serving text content programmatically. Discover
how to create basic text responses, set content types, return JSON data,
serve text as a web app, handle plain text POST requests, set character
encoding, serve XML data, create downloadable text content, add headers,
and return CSV data.

With this comprehensive guide, you'll unlock the full potential of Google
Apps Script and become a master at automating and integrating various
Google Apps to boost your productivity and streamline your workflows.
Each Section is packed with practical examples, code snippets, and
detailed explanations to ensure your success in leveraging the power of
Google Apps Script. Let's embark on this journey of automation and
efficiency together!

Introduction to CalendarApp

Apps Script Coding Questions


🚀
Mastering CalendarApp! 🚀
Exciting Insights into Google Apps Script:

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
8
Google Apps Script, particularly focusing on the versatile CalendarApp
class. Whether you're a seasoned developer or just starting, these tips are
sure to enhance your productivity and scripting prowess. 🌟
● Event Creation: Learn to create events seamlessly in your Google
Calendar. #GoogleAppsScript #EventManagement #Automation
● Event Searching: Master the art of event searching using specific
criteria. #EventSearch #CalendarApp #Scripting
● Event Deletion: Automate the process of deleting unwanted events.
#EventDeletion #GoogleCalendar #Efficiency
● Event Updates: Skillfully modify event times with simple scripts.
#CalendarUpdates #TimeManagement #GoogleScripts
● Recurring Events: Set up recurring events without hassle.
#RecurringEvents #ProductivityHacks #ScriptingLife
● Event Details Retrieval: Fetch and log event details for any given day.
#DataRetrieval #ScriptingMagic #GoogleCalendarAPI
● Guest Management: Add guests to events automatically.
#GuestManagement #AutomatedInvites #GoogleApps
● Privacy Settings: Learn to modify event visibility settings.
#PrivacyControl #CalendarSettings #TechTips
● Calendar ID Retrieval: Effortlessly find and use your calendar ID.
#CalendarID #ScriptingTools #GoogleTech
● Listing Calendars: Compile a list of all accessible calendars and their
IDs. #CalendarList #ScriptingSolutions #GoogleAPI

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
9
Each tip comes with a full explanation and code snippet, making it super
accessible for all skill levels. These insights not only make working with
Google Calendar efficient but also open doors to innovative solutions for
everyday scheduling tasks. 📅

1: Creating an Event

Question: How do you create a simple event in the user's default calendar
using Google Apps Script?

Answer:

function createEvent() {
var calendar = CalendarApp.getDefaultCalendar();
var startTime = new Date('March 15, 2024 15:00:00');
var endTime = new Date('March 15, 2024 16:00:00');
var event = calendar.createEvent('Meeting with Bob', startTime, endTime);
}

Explanation: This script uses CalendarApp.getDefaultCalendar() to get the


user's default calendar. It then defines start and end times for the event and
creates a new event titled 'Meeting with Bob'.

2: Finding Events

Question: How can you search for events with a specific title in a calendar?

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
10
Answer:

function findEvents() {
var calendar = CalendarApp.getDefaultCalendar();
var events = calendar.getEvents(new Date('March 1, 2024'), new
Date('March 31, 2024'), {search: 'Meeting'});
return events;
}

Explanation: This script searches the default calendar for events with the
word 'Meeting' in their title, between March 1, 2024, and March 31, 2024.
The getEvents() method is used with a date range and a search term.

3: Deleting an Event

Question: How do you delete an event by its title?

Answer:

function deleteEvent() {
var calendar = CalendarApp.getDefaultCalendar();
var events = calendar.getEvents(new Date('March 1, 2024'), new
Date('March 31, 2024'), {search: 'Unwanted Event'});
if (events.length > 0) {
events[0].deleteEvent();
}
}

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
11
Explanation: This code finds events titled 'Unwanted Event' and deletes the
first occurrence. It's important to handle the case where no events are
found to avoid errors.

4: Updating an Event

Question: How do you change the time of an existing event?

Answer:

function updateEventTime() {
var calendar = CalendarApp.getDefaultCalendar();
var events = calendar.getEvents(new Date('March 15, 2024'), new
Date('March 16, 2024'), {search: 'Meeting with Bob'});
if (events.length > 0) {
var newStartTime = new Date('March 15, 2024 17:00:00');
var newEndTime = new Date('March 15, 2024 18:00:00');
events[0].setTime(newStartTime, newEndTime);
}
}

Explanation: This function looks for events titled 'Meeting with Bob' and
updates the start and end times of the first matching event. It's crucial to
check that the event exists before attempting to modify it.

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
12
5: Creating a Recurring Event

Question: How do you create a weekly recurring event?

Answer:

function createRecurringEvent() {
var calendar = CalendarApp.getDefaultCalendar();
var startTime = new Date('March 15, 2024 09:00:00');
var endTime = new Date('March 15, 2024 10:00:00');
var recurrence =
CalendarApp.newRecurrence().addWeeklyRule().until(new Date('June 15,
2024'));
calendar.createEventSeries('Weekly Team Meeting', startTime, endTime,
recurrence);
}

Explanation: This script sets up a weekly recurring event named 'Weekly


Team Meeting', starting on March 15, 2024, and ending on June 15, 2024.
The newRecurrence() method is used to define the recurrence pattern.

6: Getting Event Details

Question: How can you retrieve and log the details of all events on a
specific day?

Answer:

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
13
function logEventDetails() {
var calendar = CalendarApp.getDefaultCalendar();
var events = calendar.getEventsForDay(new Date('March 15, 2024'));
for (var i = 0; i < events.length; i++) {
Logger.log('Event: ' + events[i].getTitle() + ', Time: ' +
events[i].getStartTime());
}
}

Explanation: This function retrieves all events for March 15, 2024, and logs
their title and start time. The getEventsForDay() method is used to get the
day's events.

7: Adding Guests to an Event

Question: How do you add guests to an existing event?

Answer:

function addGuestsToEvent() {
var calendar = CalendarApp.getDefaultCalendar();
var events = calendar.getEvents(new Date('March 15, 2024'), new
Date('March 16, 2024'), {search: 'Meeting with Bob'});
if (events.length > 0) {
events[0].addGuest('[email protected]');
}

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
14
}

Explanation: This script finds an event named 'Meeting with Bob' and adds
a guest with the email '[email protected]'. The addGuest() method is
used to add guests to the event.

8: Changing Event Visibility

Question: How can you change an event's visibility to private?

Answer:

function makeEventPrivate() {
var calendar = CalendarApp.getDefaultCalendar();
var events = calendar.getEvents(new Date('March 15, 2024'), new
Date('March 16, 2024'), {search: 'Meeting with Bob'});
if (events.length > 0) {
events[0].setVisibility(CalendarApp.Visibility.PRIVATE);
}
}

Explanation: This function changes the visibility of the first 'Meeting with
Bob' event to private. The setVisibility() method is employed to modify the
event's visibility setting.

9: Getting Calendar ID

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
15
Question: How do you find and log the ID of the user's default calendar?

Answer:

function logCalendarId() {
var calendar = CalendarApp.getDefaultCalendar();
Logger.log(calendar.getId());
}

Explanation: This simple script retrieves the ID of the user's default


calendar using getId() and logs it. The calendar ID is often used in more
advanced scripting scenarios.

10: Listing All Calendars

Question: How can you list all calendar names and their IDs that the user
has access to?

Answer:

function listAllCalendars() {
var calendars = CalendarApp.getAllCalendars();
for (var i = 0; i < calendars.length; i++) {
Logger.log('Calendar Name: ' + calendars[i].getName() + ', ID: ' +
calendars[i].getId());
}
}

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
16
Explanation: This script uses getAllCalendars() to retrieve all calendars the
user has access to and logs their names and IDs. This can be useful for
identifying specific calendars for more complex operations.

Introduction to DocumentApp

Apps Script DocumentApp


🌟
Mastering DocumentApp! 🌟
Unleashing the Power of Google Apps Script:

Below are some incredible insights into the world of Google Apps Script,
focusing on the amazing capabilities of the DocumentApp class. If you're
passionate about automating and enhancing your document handling,
these tips are a goldmine! 💡
● Document Creation Magic: Discover how to create Google Docs on
the fly. #GoogleAppsScript #DocumentCreation #CodingLife
● Text Addition Techniques: Learn the art of programmatically adding
text. #TextManipulation #DocumentApp #Automation
● Smart Formatting: Master the skill of formatting text with simple
scripts. #TextFormatting #GoogleDocs #Scripting

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
17
● Table Insertion: Dive into creating organized tables in documents.
#TableInsertion #DocumentAutomation #GoogleScript
● Header Hacks: Effortlessly add headers to your Google Docs.
#HeaderCreation #DocumentDesign #TechTips
● Image Implementation: Insert images with ease using URLs.
#ImageInsertion #GoogleDocsTricks #ScriptingSolutions
● Footer Fundamentals: Learn to append footers for a complete
document. #FooterAddition #GoogleDocs #ScriptingMagic
● Title Transformation: Change document titles programmatically.
#TitleManagement #DocumentApp #TechHacks
● Find and Replace: Automate text replacement in your documents.
#TextReplacement #Automation #GoogleAppsScript
● Content Cleanup: Skillfully remove specific paragraphs from a
document. #ContentManagement #Scripting #GoogleDocs
Each tip includes a full explanation and code snippet, making it super
accessible for all skill levels. Embrace these insights to revolutionize the
way you handle Google Docs, making your workflow smoother and more
efficient. 📝
1: Creating a New Document

Question: How do you create a new Google Document using Google Apps
Script?

Answer:

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
18
function createNewDocument() {
var doc = DocumentApp.create('New Document');
Logger.log(doc.getUrl());
}

Explanation: This script uses DocumentApp.create() to create a new


document titled 'New Document'. The URL of the created document is then
logged.

2: Adding Text to a Document

Question: How can you add a paragraph of text to a document?

Answer:

function addTextToDocument() {
var doc = DocumentApp.openById('YOUR_DOCUMENT_ID');
var body = doc.getBody();
body.appendParagraph('This is a new paragraph.');
}

Explanation: This code snippet opens an existing document using its ID,
gets its body, and then appends a new paragraph with the specified text.

3: Formatting Text

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
19
Question: How do you change the font size and style of a specific
paragraph?

Answer:

function formatText() {
var doc = DocumentApp.openById('YOUR_DOCUMENT_ID');
var body = doc.getBody();
var paragraph = body.getParagraphs()[0];
paragraph.setFontSize(12).setBold(true);
}

Explanation: This function accesses the first paragraph of the document's


body and changes its font size to 12 and sets it to bold.

4: Inserting a Table

Question: How can you insert a 2x2 table into a document?

Answer:

function insertTable() {
var doc = DocumentApp.openById('YOUR_DOCUMENT_ID');
var body = doc.getBody();
var table = body.appendTable([['Cell 1', 'Cell 2'], ['Cell 3', 'Cell 4']]);
}

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
20
Explanation: This script adds a table with two rows and two columns to the
document, with each cell containing predefined text.

5: Adding a Header

Question: How do you add a header to a document?

Answer:

function addHeader() {
var doc = DocumentApp.openById('YOUR_DOCUMENT_ID');
var header = doc.addHeader();
header.appendParagraph('This is a header.');
}

Explanation: This function creates a header in the document and adds a


paragraph of text to it.

6: Inserting an Image

Question: How can you insert an image into a document?

Answer:

function insertImage() {
var doc = DocumentApp.openById('YOUR_DOCUMENT_ID');
var body = doc.getBody();

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
21
var imageUrl = 'https://example.com/image.png'; // Replace with your
image URL
var image = UrlFetchApp.fetch(imageUrl).getBlob();
body.appendImage(image);
}

Explanation: This script fetches an image from a URL and inserts it into the
document's body. Note that the URL must be publicly accessible.

7: Creating a Footer

Question: How do you create a footer in a document?

Answer:

function addFooter() {
var doc = DocumentApp.openById('YOUR_DOCUMENT_ID');
var footer = doc.addFooter();
footer.appendParagraph('This is a footer.');
}

Explanation: This function adds a footer to the document and then inserts a
paragraph of text into it.

8: Changing Document Properties

Question: How can you change the title of a document?

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
22
Answer:

function changeDocumentTitle() {
var doc = DocumentApp.openById('YOUR_DOCUMENT_ID');
doc.setName('New Title');
}

Explanation: This code snippet changes the title of an open document to


'New Title'.

9: Finding and Replacing Text

Question: How do you find and replace text in a document?

Answer:

function findAndReplaceText() {
var doc = DocumentApp.openById('YOUR_DOCUMENT_ID');
var body = doc.getBody();
body.replaceText('oldText', 'newText');
}

Explanation: This script searches the entire body of the document for
'oldText' and replaces it with 'newText'.

10: Removing Content from a Document

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
23
Question: How can you delete a specific paragraph from a document?

Answer:

function deleteParagraph() {
var doc = DocumentApp.openById('YOUR_DOCUMENT_ID');
var body = doc.getBody();
var paragraph = body.getParagraphs()[1]; // assuming you want to delete
the second paragraph
paragraph.removeFromParent();
}

Explanation: This function removes the second paragraph from the


document's body. The paragraph is identified by its index in the
getParagraphs() array.

These questions and answers cover various functionalities of the


DocumentApp class in Google Apps Script, demonstrating how to
manipulate and format Google Docs documents programmatically.

Introduction to DriveApp

Apps Script DriveApp


🚀
Google Apps Script: DriveApp Mastery! 🚀
Elevating Your Google Drive Experience with

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
24
Below are some powerful insights into the DriveApp class of Google Apps
Script. If you're looking to streamline your Google Drive interactions and
automate file management, these tips will be game-changers! 💼🔧
● Folder Creation Simplified: Learn to create folders instantly.
#GoogleAppsScript #DriveApp #FolderCreation
● Effortless File Uploads: Master the art of uploading text files.
#FileUpload #DriveAutomation #CloudStorage
● File Search Wizardry: Find files by name like a pro. #FileSearch
#DriveAppMagic #GoogleDrive
● File Organization: Move files to folders with ease. #FileManagement
#DriveOrganization #ScriptingSkills
● Smart Sharing: Share files with specific users seamlessly.
#FileSharing #DriveAccess #TechSavvy
● Permission Handling: Set files to public access effortlessly.
#AccessControl #DrivePermissions #GoogleScripts
● File Deletion: Learn to delete files securely. #FileDeletion
#DriveCleanup #Automation
● Folder File Listing: List all files in a folder with a simple script.
#FileListing #DriveApp #Efficiency
● Google Docs Creation: Create Google Docs files directly in Drive.
#GoogleDocs #Scripting #DriveAppTips
● Reading File Contents: Read text file contents easily.
#ContentManagement #FileReading #GoogleDrive

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
25
Each tip comes with a comprehensive explanation and a handy code
snippet, making them accessible for all skill levels. Embrace these insights
to revolutionize your Google Drive usage, enhancing productivity and
workflow efficiency. 📊📁
1: Creating a New Folder

Question: How do you create a new folder in Google Drive using Google
Apps Script?

Answer:

function createNewFolder() {
var folder = DriveApp.createFolder('New Folder');
Logger.log(folder.getUrl());
}

Explanation: This script uses DriveApp.createFolder() to create a new


folder titled 'New Folder'. The URL of the created folder is logged for
reference.

2: Uploading a File

Question: How can you upload a text file to Google Drive?

Answer:

function uploadTextFile() {

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
26
var content = 'Hello, World!';
var file = DriveApp.createFile('Example.txt', content,
MimeType.PLAIN_TEXT);
Logger.log(file.getUrl());
}

Explanation: This code snippet creates and uploads a text file named
'Example.txt' with the content 'Hello, World!' to Google Drive. The file URL
is logged afterward.

3: Searching for Files

Question: How do you find files with a specific name in Google Drive?

Answer:

function findFiles() {
var files = DriveApp.getFilesByName('Example.txt');
while (files.hasNext()) {
var file = files.next();
Logger.log(file.getUrl());
}
}

Explanation: This function uses DriveApp.getFilesByName() to search for


all files named 'Example.txt' and logs their URLs.

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
27
4: Moving a File to a Folder

Question: How can you move a file to a specific folder?

Answer:

function moveFileToFolder(fileId, folderId) {


var file = DriveApp.getFileById(fileId);
var folder = DriveApp.getFolderById(folderId);
file.moveTo(folder);
}

Explanation: This script moves a file (identified by fileId) to a folder


(identified by folderId). getFileById() and getFolderById() are used to
reference the file and folder respectively.

5: Sharing a File

Question: How do you share a file with a specific user?

Answer:

function shareFile(fileId, userEmail) {


var file = DriveApp.getFileById(fileId);
file.addViewer(userEmail);
}

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
28
Explanation: This function shares a file (identified by fileId) with a user
(whose email is userEmail). The addViewer() method gives view access to
the specified user.

6: Changing File Permissions

Question: How can you change the sharing permissions of a file to 'public'?

Answer:

function makeFilePublic(fileId) {
var file = DriveApp.getFileById(fileId);
file.setSharing(DriveApp.Access.ANYONE, DriveApp.Permission.VIEW);
}

Explanation: This script changes the sharing settings of a file, making it


accessible to anyone with the link for viewing. The setSharing() method is
used to modify access permissions.

7: Deleting a File

Question: How do you delete a file from Google Drive?

Answer:

function deleteFile(fileId) {
var file = DriveApp.getFileById(fileId);
file.setTrashed(true);

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
29
}

Explanation: This function moves a file to the trash. The setTrashed()


method is used to mark the file as trashed.

8: Listing Files in a Folder

Question: How can you list all files in a specific folder?

Answer:

function listFilesInFolder(folderId) {
var folder = DriveApp.getFolderById(folderId);
var files = folder.getFiles();
while (files.hasNext()) {
var file = files.next();
Logger.log(file.getName());
}
}

Explanation: This script lists all files within a specified folder.


getFolderById() gets the folder, and getFiles() retrieves all files in it.

9: Creating a Google Docs File

Question: How do you create a Google Docs file in Drive?

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
30
Answer:

function createGoogleDoc() {
var doc = DocumentApp.create('New Document');
DriveApp.getFileById(doc.getId());
}

Explanation: This code snippet creates a new Google Docs file titled 'New
Document' and retrieves it using DriveApp.

10: Reading File Content

Question: How can you read the content of a text file in Drive?

Answer:

function readFileContent(fileId) {
var file = DriveApp.getFileById(fileId);
var content = file.getBlob().getDataAsString();
Logger.log(content);
}

Explanation: This function reads and logs the content of a text file.
getBlob().getDataAsString() is used to get the file's content in string format.

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
31
These questions and answers provide a comprehensive understanding of
various functionalities of the DriveApp class in Google Apps Script,
demonstrating how to manage and interact with files and folders in Google
Drive programmatically.

Introduction to FormApp

Apps Script FormApp


🌐
with Google Apps Script: Dive into FormApp! 🌐
Transforming How You Use Google Forms

Google Apps Script, zooming in on the dynamic capabilities of the


FormApp class. If you're all about optimizing your forms for efficiency and
effectiveness, these tips are just for you! 📊🖋️
● Effortless Form Creation: Discover the simplicity of creating Google
Forms. #GoogleAppsScript #FormApp #FormCreation
● Dynamic Multiple-Choice Questions: Master adding diverse
multiple-choice questions. #Questionnaire #FormBuilding #TechTips
● Automated Form Responses: Create and submit form responses
programmatically. #AutoResponse #FormAutomation #Scripting
● Section Header Addition: Organize your forms with clear section
headers. #FormOrganization #HeaderAddition #GoogleForms

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
32
● Retrieving Responses: Learn to gather and analyze form responses
efficiently. #DataCollection #ResponseAnalysis #GoogleScript
● Date Setup: Integrate date collection into your forms.
#Date#FormSetup #TechInnovation
● Form Email Distribution: Send your forms seamlessly via email.
#EmailIntegration #FormSharing #DigitalCommunication
● Form Theme Customization: Personalize your forms with unique
themes. #ThemeCustomization #FormDesign #GoogleApps
● Linear Scale Questions: Enhance your surveys with linear scale
questions. #SurveyCreation #Scale#UserFeedback
● Item Deletion in Forms: Manage your form's content effectively by
removing items. #ContentManagement #FormEditing
#ScriptingSolutions

Each tip comes with a full explanation and a code snippet, making it easy
to understand and apply. Embrace these strategies to elevate your Google
Forms, enhancing user experience and data collection accuracy. 📝📈
1: Creating a New Form

Question: How do you create a new Google Form using Google Apps
Script?

Answer:

function createNewForm() {
var form = FormApp.create('New Survey');
Logger.log(form.getPublishedUrl());

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
33
}

Explanation: This script uses FormApp.create() to create a new form titled


'New Survey'. The published URL of the form is logged for easy access.

2: Adding a Multiple-Choice Question

Question: How can you add a multiple-choice to a form?

Answer:

function addMultipleChoiceQuestion() {
var form = FormApp.openById('YOUR_FORM_ID');
form.addMultipleChoiceItem()
.setTitle('What is your favorite color?')
.setChoiceValues(['Red', 'Blue', 'Green']);
}

Explanation: This code snippet opens an existing form and adds a


multiple-choice with three options: 'Red', 'Blue', and 'Green'.

3: Creating a Form Response

Question: How do you programmatically create a response to a form?

Answer:

function createFormResponse() {

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
34
var form = FormApp.openById('YOUR_FORM_ID');
var formResponse = form.createResponse();
var items = form.getItems();
var itemResponse =
items[0].asMultipleChoiceItem().createResponse('Red');
formResponse.withItemResponse(itemResponse);
formResponse.submit();
}

Explanation: This function creates a new response to the first (assumed to


be multiple-choice) of a form, selecting 'Red' as the answer. The response
is then submitted.

4: Adding a Section Header

Question: How can you add a section header to a form?

Answer:

function addSectionHeader() {
var form = FormApp.openById('YOUR_FORM_ID');
form.addSectionHeaderItem()
.setTitle('Section 1: Personal Information');
}

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
35
Explanation: This script adds a section header titled 'Section 1: Personal
Information' to the form.

5: Retrieving Form Responses

Question: How do you retrieve all responses from a form?

Answer:

function getFormResponses() {
var form = FormApp.openById('YOUR_FORM_ID');
var responses = form.getResponses();
for (var i = 0; i < responses.length; i++) {
Logger.log(responses[i].getTimestamp());
}
}

Explanation: This function fetches all responses to the form and logs the
timestamp of each response.

6: Adding a Date Question

Question: How can you add a to collect a date?

Answer:

function addDateQuestion() {
var form = FormApp.openById('YOUR_FORM_ID');

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
36
form.addDateItem()
.setTitle('What is your birthdate?');
}

Explanation: This script adds a date to the form, asking for the respondent's
birthdate.

7: Sending Form via Email

Question: How do you send a form to an email address?

Answer:

function sendFormByEmail(email) {
var form = FormApp.openById('YOUR_FORM_ID');
MailApp.sendEmail(email, 'Please fill out this form', 'Link to the form: ' +
form.getPublishedUrl());
}

Explanation: This function sends an email with a link to the form to the
specified email address using the MailApp class.

8: Changing Form Theme

Question: How can you change the theme of a form?

Answer:

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
37
function changeFormTheme() {
var form = FormApp.openById('YOUR_FORM_ID');
form.setTheme(FormApp.Theme.CAT);
}

Explanation: This code snippet changes the theme of the form to a


predefined theme (in this case, 'CAT').

9: Adding a Linear Scale Question

Question: How do you add a linear scale to a form?

Answer:

function addLinearScaleQuestion() {
var form = FormApp.openById('YOUR_FORM_ID');
form.addLinearScaleItem()
.setTitle('Rate your satisfaction (1-5)')
.setBounds(1, 5);
}

Explanation: This function adds a linear scale to the form, with a scale from
1 to 5.

10: Deleting a Form Item

Question: How can you delete a specific item from a form?

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
38
Answer:

function deleteFormItem(itemIndex) {
var form = FormApp.openById('YOUR_FORM_ID');
var items = form.getItems();
if (items.length > itemIndex) {
form.deleteItem(items[itemIndex]);
}
}

Explanation: This script deletes an item from the form based on its index in
the item array. The existence of the item at the specified index is checked
before deletion to prevent errors.

These questions and answers cover a range of functionalities offered by


the FormApp class in Google Apps Script, showcasing how to create,
manipulate, and process Google Forms programmatically.

Introduction to GmailApp

Apps Script GmailApp


🌟
Google Apps Script: Mastering GmailApp! 🌟
Revolutionizing Email Management with

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
39
I'm excited to share some key insights into Google Apps Script, particularly
diving into the powerful GmailApp class. If you're aiming to automate and
optimize your email tasks, these tips are invaluable! 📧💻
● Seamless Email Sending: Discover the ease of sending emails
programmatically. #GoogleAppsScript #GmailApp #EmailAutomation
● Efficient Email Search: Master the technique of searching emails by
subject. #EmailSearch #Automation #TechTips
● Label Application: Learn to organize emails with custom labels.
#EmailOrganization #GmailLabels #Scripting
● Marking Read: Automate marking emails as read.
#EmailManagement #ReadStatus #GoogleScripts
● Unread Emails Tracking: Fetch all your unread emails in a snap.
#UnreadEmails #InboxManagement #TechSolutions
● Emails with Attachments: Send attachments effortlessly via email.
#EmailAttachments #DriveIntegration #ProductivityHacks
● Draft Creation: Create email drafts with just a few lines of code.
#DraftEmails #GmailApp #Coding
● Email Deletion: Manage your inbox by programmatically deleting
threads. #InboxCleanup #EmailDeletion #ScriptingMagic

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
40
● Sender Email Count: Count emails from specific senders easily.
#EmailAnalytics #SenderTracking #GmailTips
● Fetching Email Content: Retrieve the latest email content in a thread.
#EmailContent #MessageRetrieval #TechInnovation

Each tip is packed with a full explanation and a code snippet, making them
easy to understand and implement. Harness these strategies to elevate
your Gmail experience, enhancing both efficiency and effectiveness in
email handling. 🚀📬
1: Sending an Email

Question: How do you send a basic email using Google Apps Script?

Answer:

function sendEmail() {
GmailApp.sendEmail('[email protected]', 'Subject', 'Hello, this is the
email body.');
}

Explanation: This script uses GmailApp.sendEmail() to send an email to


'[email protected]' with a subject and body text. It's a straightforward
way to send emails programmatically.

2: Searching Emails

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
41
Question: How can you search for emails with a specific subject?

Answer:

function searchEmails() {
var threads = GmailApp.search('subject:"Your Subject Here"');
return threads;
}

Explanation: This code snippet uses GmailApp.search() to find all email


threads with a specific subject. The search query follows Gmail's search
syntax.

3: Applying Labels to Emails

Question: How do you apply a label to an email thread?

Answer:

function applyLabelToEmail(threadId, labelName) {


var thread = GmailApp.getThreadById(threadId);
var label = GmailApp.getUserLabelByName(labelName);
if (!label) {
label = GmailApp.createLabel(labelName);
}
thread.addLabel(label);
}

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
42
Explanation: This function adds a label to an email thread. It checks if the
label exists, creates it if it doesn't, and then applies it to the thread.

4: Marking Emails as Read

Question: How can you mark an email as read?

Answer:

function markEmailAsRead(threadId) {
var thread = GmailApp.getThreadById(threadId);
thread.markRead();
}

Explanation: This script marks a specific email thread as read using


markRead() on the thread object.

5: Retrieving Unread Emails

Question: How do you get a list of unread emails?

Answer:

function getUnreadEmails() {
var threads = GmailApp.search('is:unread');
return threads;
}

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
43
Explanation: This function fetches all unread email threads using the
search query 'is:unread'. It returns an array of thread objects.

6: Sending an Email with Attachment

Question: How can you send an email with an attachment?

Answer:

function sendEmailWithAttachment() {
var file = DriveApp.getFileById('YOUR_FILE_ID'); // Replace with your file
ID
GmailApp.sendEmail('[email protected]', 'Subject', 'Email body', {
attachments: [file.getAs(MimeType.PDF)] // Assuming the file is a PDF
});
}

Explanation: This script sends an email with a file attachment. The file is
fetched from Google Drive using its ID, and attached as a PDF.

7: Creating a Draft Email

Question: How do you create a draft email?

Answer:

function createDraft() {

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
44
GmailApp.createDraft('[email protected]', 'Draft Subject', 'This is the
draft body.');
}

Explanation: This function creates a new email draft with a specified


recipient, subject, and body.

8: Deleting an Email Thread

Question: How can you delete an email thread?

Answer:

function deleteEmailThread(threadId) {
var thread = GmailApp.getThreadById(threadId);
thread.moveToTrash();
}

Explanation: This code snippet moves an email thread to the trash using
moveToTrash() on the thread object.

9: Counting Emails from a Sender

Question: How do you count the number of emails received from a specific
email address?

Answer:

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
45
function countEmailsFromSender(senderEmail) {
var threads = GmailApp.search('from:' + senderEmail);
return threads.length;
}

Explanation: This function counts the number of email threads from a


specific sender using a 'from:' search query.

10: Fetching Email Body Content

Question: How can you fetch the body content of the latest email in a
thread?

Answer:

function fetchLatestEmailBody(threadId) {
var thread = GmailApp.getThreadById(threadId);
var messages = thread.getMessages();
var latestMessage = messages[messages.length - 1];
return latestMessage.getBody();
}

Explanation: This script retrieves the latest message from an email thread
and returns its body content. It accesses the last message in the thread's
message array.

Introduction to MailApp
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
46
Apps Script MailApp
📧
Script: Exploring MailApp! 📧
Elevate Your Email Game with Google Apps

I'm excited to share some key insights into Google Apps Script, specifically
the versatile MailApp class. If you're keen on automating and enhancing
your email operations, these tips are just for you! 🚀💻
● Simplified Email Sending: Discover the ease of sending basic emails.
#GoogleAppsScript #MailApp #EmailAutomation
● HTML Email Mastery: Dive into sending emails with HTML content.
#HTMLemails #TechTips #Scripting
● Multiple Recipients Handling: Learn to send emails to multiple people
effortlessly. #MassEmails #CommunicationSkills #GoogleScript
● Cc and Bcc Inclusion: Master adding CC and BCC recipients to your
emails. #EmailManagement #GmailHacks #Scripting
● Emails with Attachments: Send attachments seamlessly in emails.
#EmailAttachments #DriveIntegration #GoogleApps
● Inline Images in Emails: Enhance your emails with inline images.
#EmailDesign #VisualCommunication #TechInnovation
● Email Quota Check: Keep track of your email sending quota.
#QuotaManagement #MailApp #Efficiency

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
47
● Rich Text Emailing: Send emails with rich text formatting. #RichText
#EmailFormatting #DigitalCommunication
● Setting Reply-To Addresses: Customize your reply-to address in
emails. #EmailCustomization #ProfessionalCommunication
#GoogleScripts
● Advanced Email Options: Explore sending emails with both plain text
and HTML bodies. #EmailOptions #TechSavvy #ScriptingMastery

Each tip comes with a detailed explanation and a code snippet, making
them accessible for all levels. Embrace these strategies to transform your
Gmail experience, making your email communication more efficient and
impactful. 🌟📬
1: Sending a Basic Email

Question: How do you send a basic email using Google Apps Script?

Answer:

function sendBasicEmail() {
MailApp.sendEmail('[email protected]', 'Subject', 'This is the email
body.');
}

Explanation: This script sends an email to '[email protected]' with


the specified subject and body text using MailApp.sendEmail().

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
48
2: Sending an Email with HTML Body

Question: How can you send an email with HTML content in the body?

Answer:

function sendHtmlEmail() {
var htmlBody = '<p>This is an <b>HTML</b> email.</p>';
MailApp.sendEmail('[email protected]', 'Subject', '', {htmlBody:
htmlBody});
}

Explanation: This code sends an email with HTML content. The HTML is
specified in the htmlBody parameter of the sendEmail method.

3: Sending Emails to Multiple Recipients

Question: How do you send an email to multiple recipients?

Answer:

function sendEmailToMultipleRecipients() {
var recipients = '[email protected],[email protected]';
MailApp.sendEmail(recipients, 'Subject', 'This is the email body.');
}

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
49
Explanation: This function sends an email to multiple recipients. The
recipients' email addresses are separated by commas.

4: Sending an Email with Cc and Bcc

Question: How can you send an email with CC and BCC recipients?

Answer:

function sendEmailWithCcBcc() {
var cc = '[email protected]';
var bcc = '[email protected]';
MailApp.sendEmail('[email protected]', 'Subject', 'This is the email
body.', {cc: cc, bcc: bcc});
}

Explanation: This script sends an email with additional recipients in the CC


and BCC fields, which are specified in the options object passed to
sendEmail().

5: Sending an Email with an Attachment

Question: How do you send an email with an attachment from Google


Drive?

Answer:

function sendEmailWithAttachment() {

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
50
var file = DriveApp.getFileById('YOUR_FILE_ID'); // Replace with your file
ID
MailApp.sendEmail('[email protected]', 'Subject', 'Please see
attached file.', {
attachments: [file.getAs(MimeType.PDF)] // Assuming the file is a PDF
});
}

Explanation: This function sends an email with a file attachment. The file is
retrieved from Google Drive using its ID and attached to the email.

6: Sending an Email with Inline Images

Question: How can you send an email with inline images?

Answer:

function sendEmailWithInlineImage() {
var htmlBody = 'Inline image: <img src="cid:imageKey">';
var blob = DriveApp.getFileById('IMAGE_FILE_ID').getBlob(); // Replace
with your image file ID
MailApp.sendEmail({
to: '[email protected]',
subject: 'Subject with inline image',
htmlBody: htmlBody,
inlineImages: {

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
51
imageKey: blob
}
});
}

Explanation: This script sends an HTML email with an inline image. The
image is referenced using a content ID (cid) within the HTML and is passed
in the inlineImages object.

7: Retrieving Quota Information

Question: How do you check the remaining daily quota for sending emails?

Answer:

function checkEmailQuota() {
var remainingQuota = MailApp.getRemainingDailyQuota();
Logger.log('Remaining email quota: ' + remainingQuota);
}

Explanation: This function retrieves the remaining daily quota for sending
emails using MailApp.getRemainingDailyQuota().

8: Sending a Rich Text Email

Question: How can you send an email with rich text formatting?

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
52
Answer:

function sendRichTextEmail() {
var body = 'This is <b>bold</b> and this is <i>italic</i>.';
MailApp.sendEmail('[email protected]', 'Rich Text Email', '',
{htmlBody: body});
}

Explanation: This script sends an email where the body contains rich text
formatting. HTML tags are used for formatting, and the content is sent as
an HTML body.

9: Setting Reply-To Address

Question: How do you set a reply-to address in an email?

Answer:

function setReplyToAddress() {
MailApp.sendEmail({
to: '[email protected]',
subject: 'Subject',
body: 'This is the email body.',
replyTo: '[email protected]'
});
}

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
53
Explanation: This function sends an email with a specific reply-to address
using the replyTo option in the sendEmail method.

10: Sending Email with Advanced Options

Question: How can you send an email with both plain text and HTML
bodies?

Answer:

function sendEmailWithAdvancedOptions() {
var plainBody = 'This is the plain text body.';
var htmlBody = '<p>This is the <b>HTML</b> body.</p>';
MailApp.sendEmail({
to: '[email protected]',
subject: 'Subject',
body: plainBody,
htmlBody: htmlBody
});
}

Explanation: This script sends an email with both plain text and HTML
bodies. The email client of the recipient will display the format it supports or
prefers.

Introduction to SpreadsheetApp

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
54
Apps Script SpreadsheetApp
🚀 Mastering Google Sheets Automation with

Secrets! 🚀
Google Apps Script: Unveiling SpreadsheetApp

I'm excited to share some deep dive insights into Google Apps Script,
especially the incredibly powerful SpreadsheetApp class. If you're
passionate about automating and revolutionizing your Google Sheets
experience, these tips are tailor-made for you! 📊💻
● Effortless Spreadsheet Creation: Learn to create new spreadsheets
on the go. #GoogleAppsScript #SpreadsheetApp #Automation
● Smart Data Entry: Dive into adding data to specific cells easily.
#DataEntry #TechTips #GoogleSheets
● Reading Range Data: Master extracting data from ranges.
#DataExtraction #SpreadsheetMagic #Scripting
● Appending Data Dynamically: Append rows of data seamlessly.
#DataAppending #SheetsAutomation #GoogleTech
● Formula Integration: Set up formulas in cells programmatically.
#FormulasInSheets #EfficiencyHacks #Scripting
● Customizing Cell Appearance: Change cell background colors with
scripts. #CellFormatting #VisualData #GoogleSheets

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
55
● Data Find & Replace: Automate finding and replacing spreadsheet
data. #DataManipulation #SpreadsheetApp #TechSkills
● Adding New Sheets: Easily add new sheets to your spreadsheets.
#SheetManagement #GoogleApps #Productivity
● Range Protection: Learn to protect ranges from unwanted edits.
#DataProtection #SheetsSecurity #ScriptingSolutions
● Automated Data Sorting: Sort data ranges with ease. #DataSorting
#SpreadsheetOrganization #GoogleAppsScript

Each tip comes with a detailed explanation and a handy code snippet,
making it super accessible for all skill levels. Embrace these insights to
transform your Google Sheets, bringing efficiency and innovation to your
data handling. 📈📝

1: Creating a New Spreadsheet

Question: How do you create a new spreadsheet using Google Apps


Script?

Answer:

function createNewSpreadsheet() {

var spreadsheet = SpreadsheetApp.create('New Spreadsheet');

Logger.log(spreadsheet.getUrl());

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
56
}

Explanation: This script uses SpreadsheetApp.create() to create a new


spreadsheet titled 'New Spreadsheet'. The URL of the created spreadsheet
is then logged.

2: Adding Data to a Cell

Question: How can you add data to a specific cell in a spreadsheet?

Answer:

function addDataToCell() {

var spreadsheet =
SpreadsheetApp.openById('YOUR_SPREADSHEET_ID');

var sheet = spreadsheet.getActiveSheet();

sheet.getRange('A1').setValue('Hello, World!');

Explanation: This code snippet opens an existing spreadsheet by ID, gets


the active sheet, and sets the value of cell A1 to 'Hello, World!'.

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
57
3: Reading Data from a Range

Question: How do you read data from a range of cells?

Answer:

function readDataFromRange() {

var spreadsheet =
SpreadsheetApp.openById('YOUR_SPREADSHEET_ID');

var range = spreadsheet.getActiveSheet().getRange('A1:B2');

var values = range.getValues();

return values;

Explanation: This function reads and returns the data from a range (A1:B2)
in the active sheet of the specified spreadsheet. getValues() returns a 2D
array of the range's contents.

4: Appending a Row of Data

Question: How can you append a row of data to a sheet?

Answer:

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
58
function appendRow() {

var spreadsheet =
SpreadsheetApp.openById('YOUR_SPREADSHEET_ID');

var sheet = spreadsheet.getActiveSheet();

sheet.appendRow(['New', 'Row', 'Data']);

Explanation: This script appends a new row with three cells ('New', 'Row',
'Data') to the bottom of the active sheet.

5: Setting a Formula in a Cell

Question: How do you set a formula in a cell?

Answer:

function setFormulaInCell() {

var spreadsheet =
SpreadsheetApp.openById('YOUR_SPREADSHEET_ID');

var sheet = spreadsheet.getActiveSheet();

sheet.getRange('C1').setFormula('=SUM(A1:B1)');

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
59
}

Explanation: This function sets a formula (=SUM(A1:B1)) in cell C1 of the


active sheet, which will calculate the sum of the values in A1 and B1.

6: Changing Cell Background Color

Question: How can you change the background color of a cell?

Answer:

function changeCellBackgroundColor() {

var spreadsheet =
SpreadsheetApp.openById('YOUR_SPREADSHEET_ID');

var sheet = spreadsheet.getActiveSheet();

sheet.getRange('A1').setBackground('yellow');

Explanation: This script changes the background color of cell A1 to yellow


in the active sheet.

7: Finding and Replacing Data

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
60
Question: How do you find and replace data in a spreadsheet?

Answer:

function findAndReplaceData() {

var spreadsheet =
SpreadsheetApp.openById('YOUR_SPREADSHEET_ID');

var sheet = spreadsheet.getActiveSheet();

sheet.createTextFinder('oldData').replaceAllWith('newData');

Explanation: This function uses createTextFinder to search for 'oldData' in


the active sheet and replace it with 'newData'.

8: Adding a New Sheet

Question: How can you add a new sheet to a spreadsheet?

Answer:

function addNewSheet() {

var spreadsheet =
SpreadsheetApp.openById('YOUR_SPREADSHEET_ID');

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
61
spreadsheet.insertSheet('New Sheet');

Explanation: This code snippet adds a new sheet titled 'New Sheet' to the
specified spreadsheet.

9: Protecting a Range

Question: How do you protect a range in a sheet?

Answer:

function protectRange() {

var spreadsheet =
SpreadsheetApp.openById('YOUR_SPREADSHEET_ID');

var range = spreadsheet.getActiveSheet().getRange('A1:B2');

var protection = range.protect().setDescription('Sample Protection');

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
62
Explanation: This script protects a range (A1:B2) in the active sheet,
preventing it from being edited by other users. The protection is given a
description for clarity.

10: Sorting Data in a Range

Question: How can you sort data in a range?

Answer:

function sortRange() {

var spreadsheet =
SpreadsheetApp.openById('YOUR_SPREADSHEET_ID');

var range = spreadsheet.getActiveSheet().getRange('A1:B10');

range.sort({column: 1, ascending: true});

Explanation: This function sorts the data in the range A1:B10 in the active
sheet based on the values in the first column (column 1) in ascending
order.

These questions and answers provide a comprehensive overview of the


capabilities of the SpreadsheetApp class in Google Apps Script, illustrating
how to manipulate and interact with Google Sheets programmatically.

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
63
Introduction to SlidesApp

Apps Script SlidesApp


🌟 Unlocking the Power of Google Slides with

🌟
Google Apps Script: A Journey with SlidesApp!

I'm excited to share some enriching insights into Google Apps Script,
focusing on the dynamic SlidesApp class. For those looking to automate
and creatively enhance their Google Slides presentations, these tips are a
goldmine! 📈🎨
● Seamless Presentation Creation: Learn how to create new
presentations instantly. #GoogleAppsScript #SlidesApp
#PresentationCreation
● Dynamic Text Boxes: Master the art of adding text boxes to your
slides. #TextManipulation #PresentationDesign #TechTips
● Slide Background Customization: Change slide backgrounds to make
your presentations stand out. #VisualDesign #SlidesApp
#GoogleSlides
● Incorporating Images: Enhance your slides with images from the web.
#ImageIntegration #CreativePresentations #Scripting

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
64
● Slide Duplication: Duplicate slides efficiently for consistent formatting.
#SlideManagement #PresentationSkills #GoogleScript
● Utilizing Predefined Layouts: Add slides with specific layouts to
streamline design. #LayoutsInSlides #DesignEfficiency #TechHacks
● Text Replacement in Slides: Automate finding and replacing text
across your presentation. #TextAutomation #SlidesApp #GoogleTech
● Creating Hyperlinks: Turn your text into clickable links within slides.
#Hyperlinks #InteractivePresentations #DigitalSolutions
● Styling Text: Learn to style text for emphasis and clarity. #TextStyle
#FontManagement #PresentationTips
● Deleting Slides: Manage your slide deck by removing unnecessary
slides. #SlideEditing #PresentationCleanup #ScriptingMagic

Each tip comes with a detailed explanation and a practical code snippet,
making it super accessible for all skill levels. Embrace these strategies to
revolutionize your Google Slides presentations, bringing both efficiency and
creativity to your storytelling. 📊💡
1: Creating a New Presentation

Question: How do you create a new Google Slides presentation using


Google Apps Script?

Answer:

function createNewPresentation() {
var presentation = SlidesApp.create('New Presentation');

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
65
Logger.log(presentation.getUrl());
}

Explanation: This script uses SlidesApp.create() to create a new


presentation titled 'New Presentation'. The URL of the created presentation
is then logged.

2: Adding a Text Box

Question: How can you add a text box to a slide?

Answer:

function addTextBox() {
var presentation = SlidesApp.openById('YOUR_PRESENTATION_ID');
var slide = presentation.getSlides()[0]; // Get the first slide
slide.insertTextBox('Hello, Slides!');
}

Explanation: This code snippet opens an existing presentation and adds a


text box with the text 'Hello, Slides!' to the first slide.

3: Changing Slide Background Color

Question: How do you change the background color of a slide?

Answer:

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
66
function changeSlideBackgroundColor() {
var presentation = SlidesApp.openById('YOUR_PRESENTATION_ID');
var slide = presentation.getSlides()[0];
slide.getBackground().setSolidFill('#00FF00'); // Sets the background to
green
}

Explanation: This function changes the background color of the first slide to
green using a hex color code.

4: Adding an Image

Question: How can you add an image to a slide?

Answer:

function addImageToSlide() {
var presentation = SlidesApp.openById('YOUR_PRESENTATION_ID');
var slide = presentation.getSlides()[0];
var imageUrl = 'https://example.com/image.png'; // Replace with your
image URL
slide.insertImage(imageUrl);
}

Explanation: This script adds an image to the first slide of the presentation.
The image is fetched from the specified URL.

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
67
5: Duplicating a Slide

Question: How do you duplicate a slide in a presentation?

Answer:

function duplicateSlide() {
var presentation = SlidesApp.openById('YOUR_PRESENTATION_ID');
var slide = presentation.getSlides()[0];
presentation.insertSlide(1, slide); // Duplicate the first slide and insert it as
the second slide
}

Explanation: This function duplicates the first slide and inserts the duplicate
as the second slide in the presentation.

6: Adding a Slide with a Predefined Layout

Question: How can you add a new slide with a specific layout?

Answer:

function addSlideWithLayout() {
var presentation = SlidesApp.openById('YOUR_PRESENTATION_ID');
var layouts = presentation.getLayouts();
var layout = layouts[0]; // Choose a layout; here we select the first layout
presentation.appendSlide(layout);
}

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
68
Explanation: This script adds a new slide to the presentation using a
predefined layout, selected from the available layouts.

7: Replacing Text in Slides

Question: How do you find and replace text in a presentation?

Answer:

function replaceTextInSlides() {
var presentation = SlidesApp.openById('YOUR_PRESENTATION_ID');
presentation.replaceAllText('oldText', 'newText');
}

Explanation: This function replaces all occurrences of 'oldText' with


'newText' in the presentation.

8: Creating a Hyperlink

Question: How can you create a text box with a hyperlink in a slide?

Answer:

function createHyperlink() {
var presentation = SlidesApp.openById('YOUR_PRESENTATION_ID');
var slide = presentation.getSlides()[0];
var textBox = slide.insertTextBox('OpenAI');

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
69
var textRange = textBox.getText();
textRange.setLinkUrl('https://www.openai.com');
}

Explanation: This script adds a text box to the first slide and sets the text
'OpenAI' with a hyperlink to 'https://www.openai.com'.

9: Changing Text Style

Question: How do you change the font size and make text bold in a text
box?

Answer:

function changeTextStyle() {
var presentation = SlidesApp.openById('YOUR_PRESENTATION_ID');
var slide = presentation.getSlides()[0];
var textBox = slide.insertTextBox('Bold and Large Text');
var textRange = textBox.getText();
textRange.setFontSize(24).setBold(true);
}

Explanation: This function creates a text box with the text 'Bold and Large
Text', sets the font size to 24, and makes the text bold.

10: Deleting a Slide

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
70
Question: How can you delete a specific slide from a presentation?

Answer:

function deleteSlide() {
var presentation = SlidesApp.openById('YOUR_PRESENTATION_ID');
var slides = presentation.getSlides();
presentation.removeSlide(slides[1]); // Remove the second slide
}

Explanation: This script removes the second slide from the presentation.
The slide is identified by its index in the array returned by getSlides().

These questions and answers provide a comprehensive understanding of


various functionalities of the SlidesApp class in Google Apps Script,
demonstrating how to create and manipulate Google Slides presentations
programmatically.

Introduction to ContentService

Apps Script ContentService


🌐
Script: Mastering ContentService! 🌐
Elevating Web Interactions with Google Apps

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
71
I'm excited to share some cutting-edge insights into Google Apps Script,
focusing on the versatile ContentService class. If you're aiming to
streamline your web interactions and data serving techniques, these
nuggets of wisdom are just what you need! 💻🔧
● Plain Text Content Serving: Discover how to serve plain text via web
apps. #GoogleAppsScript #ContentService #WebDevelopment

Each tip includes a detailed explanation and a practical code example,


making them accessible and implementable for a range of web-based
applications. Embrace these strategies to enhance your web content
delivery, bringing both efficiency and versatility to your projects. 📈🌍
1: Serving Plain Text Content

Question: How do you create a basic web app that serves plain text content
using Google Apps Script?

Answer:

function doGet() {

return ContentService.createTextOutput('Hello, World!');

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
72
Explanation: This script uses doGet() to handle HTTP GET requests to the
web app. It uses ContentService.createTextOutput() to return a plain text
response 'Hello, World!'.

Introduction to HtmlService

Apps Script HtmlService


🎨
Script: Mastering HtmlService! 🎨
Unleashing Creativity with Google Apps

Dive into the fascinating world of Google Apps Script today, particularly the
versatile HtmlService class. For those looking to add a creative and
interactive touch to their Google Sheets, Docs, or web apps, these insights
are a treasure trove! 💻🌈
● Simple HTML Creation: Learn to create and serve simple HTML
pages. #GoogleAppsScript #HtmlService #WebDevelopment
● Serving HTML Files: Master the art of serving HTML files from your
script project. #HTML #Coding #Scripting
● JavaScript Integration: Embed JavaScript in your HTML pages for
dynamic content. #JavaScript #WebDesign #DigitalCreation
● Dynamic Templated HTML: Use templated HTML for personalized
content delivery. #TemplatedHTML #CustomWeb #TechTips

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
73
● Styling with CSS: Bring life to your pages with CSS styling. #CSS
#WebStyling #CreativeCoding
● Server-Side Function Calls: Connect HTML elements to Google
Script functions. #FunctionCalls #InteractiveDesign #Scripting
● Client-Server Data Transfer: Learn to pass data from client to server
seamlessly. #DataTransfer #WebApps #GoogleScripts
● Material Design Implementation: Incorporate Google's Material
Design for a sleek look. #MaterialDesign #UIUX #DesignInTech
● Custom UI for Google Sheets: Create unique user interfaces within
Google Sheets. #CustomUI #GoogleSheets #SpreadsheetMagic
● IFrame Sandbox Mode: Serve secure HTML content in IFrame
sandbox mode. #IFrame #WebSecurity #SandboxMode

Each tip includes a detailed explanation and a practical code example,


making them accessible for a variety of applications. Embrace these
strategies to transform your Google Sheets, Docs, or standalone web apps
into interactive and visually appealing masterpieces. 🌟📊
1: Creating a Simple HTML Page

Question: How do you create and serve a simple HTML page using Google
Apps Script?

Answer:

function doGet() {

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
74
return HtmlService.createHtmlOutput('<h1>Hello World!</h1>');

Explanation: This script uses HtmlService.createHtmlOutput() to create a


basic HTML page with a heading. This is typically used in the doGet()
function to serve HTML content when a web app URL is accessed.

2: Serving an HTML File

Question: How can you serve an HTML file stored in the script project?

Answer:

function doGet() {

var html = HtmlService.createHtmlOutputFromFile('Index');

return html;

Explanation: This function serves an HTML page from a file named


'Index.html' in the script project. createHtmlOutputFromFile() is used to load
the HTML content.

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
75
3: Embedding JavaScript in HTML Service

Question: How do you embed JavaScript in an HTML page served by


Google Apps Script?

Answer:

function doGet() {

var html = HtmlService.createHtmlOutput('<script>alert("Hello,


world!");</script><p>Hello, world!</p>');

return html;

Explanation: This script creates an HTML output that includes JavaScript.


Note that due to Content Security Policy (CSP), certain JavaScript
practices (like inline JavaScript) may not work, and alternatives (like using
google.script.run) are recommended.

4: Using Templated HTML

Question: How can you use templated HTML to dynamically insert values
into a page?

Answer:

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
76
function doGet() {

var template = HtmlService.createTemplate('<p>Hello, <?= userName


?>!</p>');

template.userName = 'Alice';

return template.evaluate();

Explanation: This code uses the templating feature of HtmlService to insert


a dynamic value (userName) into the HTML. <?= ?> is used to embed the
variable.

5: Serving CSS with HTML

Question: How do you include CSS in an HTML page served by Google


Apps Script?

Answer:

function doGet() {

var html = HtmlService.createHtmlOutput('<style>body { color: blue;


}</style><p>This is a blue text.</p>');

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
77
return html;

Explanation: This script embeds CSS directly into the HTML output,
changing the color of the text to blue.

6: Communicating with Google Apps Script Functions

Question: How can you call a server-side Google Apps Script function from
HTML served by HtmlService?

Answer:

function doGet() {

var html = HtmlService.createHtmlOutput('<button


onclick="google.script.run.myFunction()">Click me</button>');

return html;

function myFunction() {

Logger.log('Button was clicked!');

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
78
}

Explanation: This script creates an HTML output with a button. When


clicked, it calls the server-side function myFunction() using
google.script.run.

7: Passing Data from Client to Server

Question: How do you pass data from the HTML page to a server-side
function?

Answer:

function doGet() {

var html = HtmlService.createHtmlOutput('<input id="name"


type="text"><button
onclick="submitName()">Submit</button><script>function submitName() {
var name = document.getElementById("name").value;
google.script.run.withSuccessHandler(function(response) {
console.log(response); }).processName(name); }</script>');

return html;

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
79
function processName(name) {

Logger.log('Name submitted: ' + name);

return 'Received ' + name;

Explanation: This code includes a text input and a button in the HTML.
When the button is clicked, it calls a JavaScript function submitName(),
which retrieves the input value and passes it to the server-side function
processName.

8: Incorporating Google Material Design

Question: How can you use Google's Material Design components in an


HTML page?

Answer:

function doGet() {

var html = HtmlService.createHtmlOutput('<link rel="stylesheet"


href="https://fonts.googleapis.com/icon?family=Material+Icons"><button
class="material-icons">face</button>');

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
80
return html;

Explanation: This script includes Google's Material Design stylesheet and


uses a Material icon in a button.

9: Creating a User Interface for Spreadsheet

Question: How do you create a custom user interface in a Google Sheet


using HtmlService?

Answer:

function showCustomUi() {

var html = HtmlService.createHtmlOutput('<h2>Custom UI</h2>');

SpreadsheetApp.getUi().showModalDialog(html, 'My Custom UI');

Explanation: This function uses HtmlService to create a simple HTML


output and then uses SpreadsheetApp.getUi().showModalDialog() to
display it as a modal dialog in Google Sheets.

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
81
10: Serving HTML with IFrame Sandbox Mode

Question: How can you serve HTML content in IFrame sandbox mode?

Answer:

function doGet() {

var html = HtmlService.createHtmlOutput('<p>Sandboxed


content</p>').setSandboxMode(HtmlService.SandboxMode.IFRAME);

return html;

Explanation: This script serves HTML content using IFrame as the sandbox
mode, which provides a secure and isolated environment for the content.

Introduction to HtmlOutput

These questions and answers demonstrate various uses of the


HtmlService class in Google Apps Script, illustrating how to create
interactive and dynamic web pages and user interfaces.

Apps Script HtmlOutput

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
82
🌟
into HtmlOutput! 🌟
Exploring the Versatility of Google Apps Script: A Deep Dive

Below are some enriching insights into Google Apps Script, especially the
dynamic HtmlOutput class. Perfect for those looking to elevate their web
app experiences with interactive and responsive HTML interfaces! 💻🌐
● Basic HTML Output Creation: Learn to craft simple yet impactful
HTML outputs. #GoogleAppsScript #HtmlOutput #WebDevelopment
● Enhancing Pages with Titles: Discover the art of setting titles for your
HTML outputs. #PageTitles #WebDesign #CodingTips
● Styling with Inline CSS: Inject life into pages with CSS styles.
#InlineCSS #Styling #CreativeCoding
● Web App Serving Techniques: Master serving HTML content as a
web app. #WebApps #Scripting #DigitalInnovation
● JavaScript Inclusion: Integrate JavaScript for dynamic and interactive
content. #JavaScript #WebInteraction #ScriptingMagic
● Dynamic Templated HTML: Utilize templated HTML for flexible
content rendering. #TemplatedHTML #DynamicContent
#TechSolutions
● Custom MIME Types: Tailor MIME types for specific content needs.
#MimeType #WebStandards #TechTips

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
83
● Creating Downloadable HTML: Design HTML outputs for easy
downloading. #DownloadableContent #HtmlService #DigitalSolutions
● Incorporating Custom Fonts: Enhance the aesthetic appeal with
custom fonts. #WebFonts #DesignInTech #UserExperience
● Embedding External Resources: Leverage external JS and CSS for
enriched functionalities. #ExternalResources #WebDesign
#CodingExcellence

Each tip comes with a full explanation and a practical code snippet, making
them super accessible for all skill levels. Embrace these strategies to
transform your Google Apps Script projects into interactive, user-friendly
web experiences. 🚀📊
1: Creating Basic HTML Output

Question: How do you create a basic HTML output in Google Apps Script?

Answer:

function createBasicHtmlOutput() {

var htmlOutput = HtmlService.createHtmlOutput('<h1>Hello World</h1>');

return htmlOutput;

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
84
Explanation: This function creates a basic HTML output with a heading tag
(<h1>). HtmlService.createHtmlOutput() is used to generate the HTML
content.

2: Setting the Title of HTML Output

Question: How can you set the title of an HTML output page?

Answer:

function setHtmlOutputTitle() {

var htmlOutput = HtmlService.createHtmlOutput('<p>Sample Content</p>')

.setTitle('My Custom Page');

return htmlOutput;

Explanation: This script sets the title of the HTML output to 'My Custom
Page' using the setTitle() method.

3: Adding Inline CSS to HTML Output

Question: How do you add inline CSS to HTML output?

Answer:

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
85
function addInlineCssToHtmlOutput() {

var html = '<style>body {background-color: #f3f3f3;}</style><p>Styled


Content</p>';

return HtmlService.createHtmlOutput(html);

Explanation: This function creates HTML output with inline CSS that sets
the background color of the body element.

4: Serving HTML Output as a Web App

Question: How can you serve HTML output as a web app in Google Apps
Script?

Answer:

function doGet() {

return HtmlService.createHtmlOutput('<h2>Welcome to my Web


App</h2>');

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
86
Explanation: This script uses the special function doGet() to serve HTML
content when the web app URL is accessed. It's the entry point for a web
app in Google Apps Script.

5: Including JavaScript in HTML Output

Question: How can you include JavaScript in HTML output?

Answer:

function htmlOutputWithJavascript() {

var html = '<script>alert("Hello from JavaScript!");</script><p>Page with


JavaScript</p>';

return HtmlService.createHtmlOutput(html);

Explanation: This function creates an HTML output that includes a <script>


tag with JavaScript code. Note that due to Content Security Policy, certain
inline JavaScript practices might not work.

6: Using Templated HTML in HTML Output

Question: How do you use templated HTML in HTML output?

Answer:

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
87
function useTemplatedHtml() {

var template = HtmlService.createTemplate('<p>Hello, <?= name


?>!</p>');

template.name = 'Alice';

return template.evaluate();

Explanation: This script uses HtmlService.createTemplate() to create


templated HTML, allowing server-side code to dynamically insert data into
the HTML. <?= ?> is used to embed the variable name.

7: Serving HTML Output with Custom Fonts

Question: How can you include custom fonts in HTML output?

Answer:

function includeCustomFonts() {

var html = '<link


href="https://fonts.googleapis.com/css2?family=Roboto&display=swap"
rel="stylesheet"><style>body {font-family: "Roboto",
sans-serif;}</style><p>Content with Roboto font</p>';

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
88
return HtmlService.createHtmlOutput(html);

Explanation: This function includes a link to the Google Fonts API for the
'Roboto' font and sets it as the font family in the CSS.

8: Embedding External JavaScript and CSS

Question: How do you embed external JavaScript and CSS files in HTML
output?

Answer:

function embedExternalJsCss() {

var html = '<link rel="stylesheet"


href="https://example.com/style.css"><script
src="https://example.com/script.js"></script><p>Content with external JS
and CSS</p>';

return HtmlService.createHtmlOutput(html);

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
89
Explanation: This script embeds external JavaScript and CSS by including
their respective <script> and <link> tags in the HTML output.

These questions and answers illustrate a variety of uses for the HtmlOutput
class in Google Apps Script, showing how to create interactive and
dynamic HTML content for web apps and user interfaces.

Introduction to TextOutput

Apps Script TextOutput


🔥
Apps Script: Delving into TextOutput! 🔥
Elevating Web App Responses with Google

Below unfold the capabilities of Google Apps Script, specifically exploring


the TextOutput class. Ideal for those venturing into the realm of web apps
and seeking to master text-based responses and data handling! 🌍💻
● Crafting Basic Text Outputs: Dive into creating simple yet effective
text responses. #GoogleAppsScript #TextOutput #WebDevelopment
● Setting JSON Content Types: Learn the nuances of serving JSON
data efficiently. #JSON #WebServices #CodingExcellence
● Serving Data as Web Apps: Master the art of serving text outputs in
web apps. #WebApps #Scripting #DigitalSolutions

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
90
● CSV Data Responses: Serve CSV formatted data effectively. #CSV
#DataFormats #ScriptingMastery

Each tip comes with an in-depth explanation and a code snippet, making
them highly accessible and implementable for various web-based projects.
Embrace these strategies to enhance your web app responses, making
your text data handling more efficient and versatile. 🚀📊
1: Creating Basic Text Output

Question: How do you create a basic text output in Google Apps Script?

Answer:

function createBasicTextOutput() {

var textOutput = ContentService.createTextOutput('Hello, World!');

return textOutput;

Explanation: This script uses ContentService.createTextOutput() to create a


simple text output that contains the string 'Hello, World!'. This is often used
for serving plain text responses in web apps.

2: Setting Content Type of Text Output

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
91
Question: How can you set the content type for a text output to JSON?

Answer:

function setContentTypeJson() {

var textOutput = ContentService.createTextOutput()

.setMimeType(ContentService.MimeType.JSON);

return textOutput;

Explanation: This code snippet creates a text output and sets its MIME type
to JSON using setMimeType(). This is useful when returning
JSON-formatted strings in web apps.

3: Returning JSON Data

Question: How do you return a JSON string from a server function?

Answer:

function returnJson() {

var data = {

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
92
message: 'Hello, JSON!'

};

var jsonString = JSON.stringify(data);

return ContentService.createTextOutput(jsonString)

.setMimeType(ContentService.MimeType.JSON);

Explanation: This function converts a JavaScript object into a JSON string


using JSON.stringify() and returns it as a text output with a JSON MIME
type.

4: Serving Text Output as a Web App

Question: How can you serve text output as a web app in Google Apps
Script?

Answer:

function doGet() {

return ContentService.createTextOutput('This is a web app response.');

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
93
Explanation: This script uses the doGet() function to serve text content as a
response in a web app. It's the standard way to handle GET requests in a
Google Apps Script web app.

5: Serving XML Data

Question: How do you create and serve XML data as text output?

Answer:

function serveXmlData() {

var xmlData = '<?xml version="1.0"?><message>Hello, XML!</message>';

return ContentService.createTextOutput(xmlData)

.setMimeType(ContentService.MimeType.XML);

Explanation: This function creates a text output containing an XML string


and sets the MIME type to XML, which is suitable for XML data responses.

6: Returning CSV Data

Question: How can you return CSV formatted data as text output?

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
94
Answer:

function returnCsvData() {

var csvData = 'Name,Age\nAlice,30\nBob,25';

return ContentService.createTextOutput(csvData)

.setMimeType(ContentService.MimeType.CSV);

Explanation: This function creates a text output containing data in CSV


format and sets the MIME type to CSV, which is ideal for returning
spreadsheet-like data.

These questions and answers cover various functionalities of the


TextOutput class in Google Apps Script, illustrating how to create and
manipulate text-based responses for web applications.

Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
95
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
96

You might also like