Skip to content

Snippets · 12 functions

Gmail snippets

Twelve short functions for common Gmail tasks: searching, reading, sending, and labeling.

How to use these

Set up before you run

Copy a snippet into a script file, read its setup and notes, change the placeholder values, and save. For functions meant to run manually, choose the function name in the toolbar and press Run. Results appear in the Execution log unless the description says otherwise.

1

Search threads with a query

Runs a Gmail search, the same kind you type in the Gmail search box, and logs how many threads match.

Code.gs
function searchRecentThreadsFromSender() {
  const query = 'from:billing@example.com newer_than:7d';
  const threads = GmailApp.search(query);
  Logger.log('Found ' + threads.length + ' threads.');
}

2

Read sender, subject, and date of the newest message in a thread

Logs who sent the newest message in a thread, its subject, and when it arrived.

Code.gs
function logNewestMessageDetails() {
  const threads = GmailApp.search('from:billing@example.com');
  if (!threads.length) return;
  const messages = threads[0].getMessages();
  const newest = messages[messages.length - 1];
  Logger.log(newest.getFrom() + ' | ' + newest.getSubject() + ' | ' + newest.getDate());
}

3

Send a plain-text email

Sends a plain-text email with a subject and body.

Code.gs
function sendPlainTextEmail() {
  const recipient = 'you@example.com';
  const subject = 'A quick update';
  const body = 'This is a plain-text message sent from Apps Script.';
  GmailApp.sendEmail(recipient, subject, body);
  Logger.log('Sent to ' + recipient);
}

4

Send an HTML email with htmlBody

Sends a formatted email by passing an htmlBody option along with a plain-text body.

Code.gs
function sendHtmlEmail() {
  const recipient = 'you@example.com';
  const subject = 'A formatted update';
  const plainBody = 'This message needs an HTML-capable email client.';
  const htmlBody = '<p>This is <strong>bold</strong> and this is <em>italic</em>.</p>';
  GmailApp.sendEmail(recipient, subject, plainBody, { htmlBody: htmlBody });
  Logger.log('Sent HTML email to ' + recipient);
}

Good to know. Always include a plain-text body too, in case the recipient's email client cannot show HTML.

5

Send with an attachment from Drive

Attaches an existing Drive file to an email by turning it into a blob first.

Code.gs
function sendEmailWithDriveAttachment() {
  const fileId = 'REPLACE_WITH_FILE_ID';
  const file = DriveApp.getFileById(fileId);
  const recipient = 'you@example.com';
  GmailApp.sendEmail(recipient, 'A file for you', 'See the attached file.', {
    attachments: [file.getBlob()]
  });
  Logger.log('Sent ' + file.getName() + ' to ' + recipient);
}

6

Create a draft instead of sending

Saves a message as a draft, so a person can review it and send it themselves.

GmailApp.GmailDraft
Code.gs
function createFollowUpDraft() {
  const recipient = 'you@example.com';
  const subject = 'Draft for review';
  const body = 'This draft was created by a script and is waiting for review.';
  const draft = GmailApp.createDraft(recipient, subject, body);
  Logger.log('Draft created with id ' + draft.getId());
}

7

Add a label to matching threads

Searches for threads and adds an existing Gmail label to every result.

Code.gs
function labelInvoiceThreads() {
  const label = GmailApp.getUserLabelByName('Invoices');
  if (!label) throw new Error('Create a Gmail label named Invoices before running this function.');
  const threads = GmailApp.search('subject:invoice newer_than:30d');
  threads.forEach((thread) => label.addToThread(thread));
  Logger.log('Labeled ' + threads.length + ' threads.');
}

8

Mark a thread as read

Marks the first matching thread as read, the same as opening it in Gmail.

Code.gs
function markFirstMatchingThreadRead() {
  const threads = GmailApp.search('from:billing@example.com is:unread');
  if (!threads.length) return;
  threads[0].markRead();
  Logger.log('Marked thread as read.');
}

9

Star a message

Stars the newest message in a thread.

Code.gs
function starNewestMatchingMessage() {
  const threads = GmailApp.search('from:billing@example.com');
  if (!threads.length) return;
  const messages = threads[0].getMessages();
  const newest = messages[messages.length - 1];
  GmailApp.starMessage(newest);
  Logger.log('Starred message from ' + newest.getFrom());
}

10

Count unread threads in the inbox

Logs how many inbox threads are unread, a number you might put in a daily summary.

Code.gs
function logUnreadInboxCount() {
  const unreadCount = GmailApp.getInboxUnreadCount();
  Logger.log('Unread threads in inbox: ' + unreadCount);
}

11

Get the plain body of a message

Reads the plain-text body of the newest message in a thread, without any HTML formatting.

Code.gs
function logNewestMessageBody() {
  const threads = GmailApp.search('from:billing@example.com');
  if (!threads.length) return;
  const messages = threads[0].getMessages();
  const newest = messages[messages.length - 1];
  Logger.log(newest.getPlainBody());
}

12

List your labels

Logs every Gmail label you have created, so a script can check which ones already exist.

Code.gs
function logAllLabelNames() {
  const labels = GmailApp.getUserLabels();
  const names = labels.map((label) => label.getName());
  Logger.log(names);
}

Keep going

See these in a complete task

All snippet collections