Skip to main content

Actions

The ballerinax/googleapis.gmail package exposes the following clients:

ClientPurpose
ClientGmail REST API: messages, drafts, threads, labels, history, profile, and attachments.

Client

Gmail REST API: messages, drafts, threads, labels, history, profile, and attachments.

Configuration

FieldTypeDefaultDescription
authhttp:BearerTokenConfig|OAuth2RefreshTokenGrantConfigRequiredOAuth 2.0 refresh token config or bearer token.
httpVersionhttp:HttpVersionHTTP_2_0HTTP protocol version.
timeoutdecimal30Request timeout in seconds.
retryConfighttp:RetryConfig()Retry configuration for failed requests.
secureSockethttp:ClientSecureSocket()SSL/TLS configuration.
proxyhttp:ProxyConfig()Proxy server configuration.
compressionhttp:CompressionCOMPRESSION_AUTOCompression setting for requests.
circuitBreakerhttp:CircuitBreakerConfig()Circuit breaker configuration.
cachehttp:CacheConfig{}HTTP response cache configuration.
validationbooleantrueEnable payload validation against the OpenAPI spec.
laxDataBindingbooleantrueAllow lax data binding for response payloads.

Initializing the client

import ballerinax/googleapis.gmail as gmail;

configurable string clientId = ?;
configurable string clientSecret = ?;
configurable string refreshToken = ?;

gmail:Client gmail = check new ({
auth: {
clientId: clientId,
clientSecret: clientSecret,
refreshToken: refreshToken,
refreshUrl: "https://accounts.google.com/o/oauth2/token"
}
});

Operations

Profile

Get user profile

Retrieves the authenticated user's Gmail profile including email address, total messages, total threads, and history ID.

Parameters:

NameTypeRequiredDescription
userIdstringYesThe user's email address or the special value "me" for the authenticated user.

Returns: gmail:Profile|error

Sample code:

gmail:Profile profile = check gmail->/users/me/profile();

Sample response:

{"emailAddress": "[email protected]", "messagesTotal": 15234, "threadsTotal": 8421, "historyId": "987654"}

Messages

List messages

Lists message IDs in the user's mailbox. Supports Gmail search syntax via the q query parameter.

Parameters:

NameTypeRequiredDescription
userIdstringYesThe user's email address or "me".
qstringNoGmail search query (e.g., "label:INBOX is:unread").
maxResultsintNoMaximum number of messages to return (default 100, max 500).
pageTokenstringNoToken for fetching the next page of results.
labelIdsstring[]NoOnly return messages with all of the specified label IDs.
includeSpamTrashbooleanNoInclude messages from SPAM and TRASH in results.

Returns: gmail:ListMessagesResponse|error

Sample code:

gmail:ListMessagesResponse messageList = check gmail->/users/me/messages(q = "label:INBOX is:unread");

Sample response:

{"messages": [{"id": "18a1b2c3d4e5f6a7", "threadId": "18a1b2c3d4e5f6a7"}, {"id": "18a1b2c3d4e5f6a8", "threadId": "18a1b2c3d4e5f6a8"}], "resultSizeEstimate": 2}
Send a message

Sends an email message. Supports plain text, HTML body, inline images, and file attachments.

Parameters:

NameTypeRequiredDescription
userIdstringYesThe user's email address or "me".
messagegmail:MessageRequestYesThe message to send, including recipients, subject, body, and optional attachments.

Returns: gmail:Message|error

Sample code:

gmail:Message sendResult = check gmail->/users/me/messages/send.post({
to: ["[email protected]"],
subject: "Scheduled Maintenance Notification",
bodyInHtml: "<h1>Maintenance Notice</h1><p>Systems will be down for maintenance.</p>",
inlineImages: [{
contentId: "logo",
mimeType: "image/png",
name: "logo.png",
path: "resources/logo.png"
}]
});

Sample response:

{"id": "18a1b2c3d4e5f6a9", "threadId": "18a1b2c3d4e5f6a9", "labelIds": ["SENT"]}
Get a message

Retrieves a specific message by ID with full metadata, headers, and body content.

Parameters:

NameTypeRequiredDescription
userIdstringYesThe user's email address or "me".
idstringYesThe message ID.
formatstringNoResponse format: "full", "metadata", "minimal", or "raw".
metadataHeadersstring[]NoSpecific headers to include when format is "metadata".

Returns: gmail:Message|error

Sample code:

gmail:Message message = check gmail->/users/me/messages/["18a1b2c3d4e5f6a7"](format = "full");

Sample response:

{"id": "18a1b2c3d4e5f6a7", "threadId": "18a1b2c3d4e5f6a7", "labelIds": ["INBOX", "UNREAD"], "snippet": "Hello, this is a test email...", "from": "[email protected]", "to": "[email protected]", "subject": "Test Email", "date": "Mon, 15 Jan 2024 10:30:00 +0000", "internalDate": "1705312200000", "sizeEstimate": 2048}
Insert a message

Inserts a message directly into the mailbox (similar to IMAP APPEND), bypassing send.

Parameters:

NameTypeRequiredDescription
userIdstringYesThe user's email address or "me".
messagegmail:MessageRequestYesThe message to insert.
deletedbooleanNoMark the message as permanently deleted (not TRASH) upon insert.
internalDateSourcestringNoSource for internal date: "receivedTime" or "dateHeader".

Returns: gmail:Message|error

Sample code:

gmail:Message inserted = check gmail->/users/me/messages.post({
to: ["[email protected]"],
subject: "Archived Message",
bodyInText: "This message is being archived."
});

Sample response:

{"id": "18a1b2c3d4e5f6b0", "threadId": "18a1b2c3d4e5f6b0", "labelIds": ["INBOX"]}
Import a message

Imports a message into the mailbox with standard email delivery scanning (spam classification, etc.).

Parameters:

NameTypeRequiredDescription
userIdstringYesThe user's email address or "me".
messagegmail:MessageRequestYesThe message to import.
neverMarkSpambooleanNoNever mark the imported message as spam.
processForCalendarbooleanNoProcess calendar invites in the message.

Returns: gmail:Message|error

Sample code:

gmail:Message imported = check gmail->/users/me/messages/'import.post({
to: ["[email protected]"],
subject: "Migrated Message",
bodyInText: "This message was migrated from another system."
});

Sample response:

{"id": "18a1b2c3d4e5f6b1", "threadId": "18a1b2c3d4e5f6b1", "labelIds": ["INBOX"]}
Modify a message

Modifies the labels on a message (add or remove labels).

Parameters:

NameTypeRequiredDescription
userIdstringYesThe user's email address or "me".
idstringYesThe message ID.
modifyRequestgmail:ModifyMessageRequestYesLabels to add and/or remove.

Returns: gmail:Message|error

Sample code:

gmail:Message modified = check gmail->/users/me/messages/["18a1b2c3d4e5f6a7"]/modify.post({
addLabelIds: ["STARRED"],
removeLabelIds: ["UNREAD"]
});

Sample response:

{"id": "18a1b2c3d4e5f6a7", "threadId": "18a1b2c3d4e5f6a7", "labelIds": ["INBOX", "STARRED"]}
Trash a message

Moves a message to the trash.

Parameters:

NameTypeRequiredDescription
userIdstringYesThe user's email address or "me".
idstringYesThe message ID.

Returns: gmail:Message|error

Sample code:

gmail:Message trashed = check gmail->/users/me/messages/["18a1b2c3d4e5f6a7"]/trash.post();

Sample response:

{"id": "18a1b2c3d4e5f6a7", "threadId": "18a1b2c3d4e5f6a7", "labelIds": ["TRASH"]}
Untrash a message

Removes a message from the trash, restoring it to its previous labels.

Parameters:

NameTypeRequiredDescription
userIdstringYesThe user's email address or "me".
idstringYesThe message ID.

Returns: gmail:Message|error

Sample code:

gmail:Message restored = check gmail->/users/me/messages/["18a1b2c3d4e5f6a7"]/untrash.post();

Sample response:

{"id": "18a1b2c3d4e5f6a7", "threadId": "18a1b2c3d4e5f6a7", "labelIds": ["INBOX"]}
Delete a message

Permanently deletes a message. This action cannot be undone.

Parameters:

NameTypeRequiredDescription
userIdstringYesThe user's email address or "me".
idstringYesThe message ID.

Returns: error?

Sample code:

check gmail->/users/me/messages/["18a1b2c3d4e5f6a7"].delete();
Batch delete messages

Permanently deletes multiple messages by ID.

Parameters:

NameTypeRequiredDescription
userIdstringYesThe user's email address or "me".
requestgmail:BatchDeleteMessagesRequestYesObject containing the array of message IDs to delete.

Returns: error?

Sample code:

check gmail->/users/me/messages/batchDelete.post({
ids: ["18a1b2c3d4e5f6a7", "18a1b2c3d4e5f6a8"]
});
Batch modify messages

Modifies labels on multiple messages at once.

Parameters:

NameTypeRequiredDescription
userIdstringYesThe user's email address or "me".
requestgmail:BatchModifyMessagesRequestYesMessage IDs and labels to add/remove.

Returns: error?

Sample code:

check gmail->/users/me/messages/batchModify.post({
ids: ["18a1b2c3d4e5f6a7", "18a1b2c3d4e5f6a8"],
removeLabelIds: ["UNREAD"]
});

Attachments

Get an attachment

Retrieves a message attachment by its ID.

Parameters:

NameTypeRequiredDescription
userIdstringYesThe user's email address or "me".
messageIdstringYesThe message ID containing the attachment.
idstringYesThe attachment ID.

Returns: gmail:Attachment|error

Sample code:

gmail:Attachment attachment = check gmail->/users/me/messages/["18a1b2c3d4e5f6a7"]/attachments/["ANGjdJ8abc123"]();

Sample response:

{"attachmentId": "ANGjdJ8abc123", "size": 24576}

Drafts

List drafts

Lists drafts in the user's mailbox.

Parameters:

NameTypeRequiredDescription
userIdstringYesThe user's email address or "me".
qstringNoGmail search query to filter drafts.
maxResultsintNoMaximum number of drafts to return.
pageTokenstringNoToken for fetching the next page.
includeSpamTrashbooleanNoInclude drafts in SPAM and TRASH.

Returns: gmail:ListDraftsResponse|error

Sample code:

gmail:ListDraftsResponse draftList = check gmail->/users/me/drafts();

Sample response:

{"drafts": [{"id": "r_abc123", "message": {"id": "18a1b2c3d4e5f6c0", "threadId": "18a1b2c3d4e5f6c0"}}], "resultSizeEstimate": 1}
Create a draft

Creates a new draft.

Parameters:

NameTypeRequiredDescription
userIdstringYesThe user's email address or "me".
draftgmail:DraftRequestYesThe draft content including the message.

Returns: gmail:Draft|error

Sample code:

gmail:Draft draft = check gmail->/users/me/drafts.post({
message: {
to: ["[email protected]"],
subject: "Project Update",
bodyInText: "Here is the latest update on the project."
}
});

Sample response:

{"id": "r_def456", "message": {"id": "18a1b2c3d4e5f6c1", "threadId": "18a1b2c3d4e5f6c1", "labelIds": ["DRAFT"]}}
Get a draft

Retrieves a specific draft by ID.

Parameters:

NameTypeRequiredDescription
userIdstringYesThe user's email address or "me".
idstringYesThe draft ID.
formatstringNoResponse format: "full", "metadata", "minimal", or "raw".

Returns: gmail:Draft|error

Sample code:

gmail:Draft draft = check gmail->/users/me/drafts/["r_def456"](format = "full");

Sample response:

{"id": "r_def456", "message": {"id": "18a1b2c3d4e5f6c1", "threadId": "18a1b2c3d4e5f6c1", "labelIds": ["DRAFT"], "snippet": "Here is the latest update...", "subject": "Project Update"}}
Update a draft

Replaces the content of an existing draft.

Parameters:

NameTypeRequiredDescription
userIdstringYesThe user's email address or "me".
idstringYesThe draft ID.
draftgmail:DraftRequestYesThe updated draft content.

Returns: gmail:Draft|error

Sample code:

gmail:Draft updated = check gmail->/users/me/drafts/["r_def456"].put({
message: {
to: ["[email protected]"],
subject: "Project Update (Revised)",
bodyInText: "Here is the revised update."
}
});

Sample response:

{"id": "r_def456", "message": {"id": "18a1b2c3d4e5f6c2", "threadId": "18a1b2c3d4e5f6c1", "labelIds": ["DRAFT"]}}
Send a draft

Sends an existing draft.

Parameters:

NameTypeRequiredDescription
userIdstringYesThe user's email address or "me".
draftgmail:DraftRequestYesThe draft to send (must include the draft id).

Returns: gmail:Message|error

Sample code:

gmail:Message sent = check gmail->/users/me/drafts/send.post({
id: "r_def456",
message: {}
});

Sample response:

{"id": "18a1b2c3d4e5f6c3", "threadId": "18a1b2c3d4e5f6c1", "labelIds": ["SENT"]}
Delete a draft

Permanently deletes a draft.

Parameters:

NameTypeRequiredDescription
userIdstringYesThe user's email address or "me".
idstringYesThe draft ID.

Returns: error?

Sample code:

check gmail->/users/me/drafts/["r_def456"].delete();

Threads

List threads

Lists threads in the user's mailbox, with optional search filtering.

Parameters:

NameTypeRequiredDescription
userIdstringYesThe user's email address or "me".
qstringNoGmail search query to filter threads.
maxResultsintNoMaximum number of threads to return.
pageTokenstringNoToken for fetching the next page.
labelIdsstring[]NoOnly return threads with all of the specified label IDs.
includeSpamTrashbooleanNoInclude threads from SPAM and TRASH.

Returns: gmail:ListThreadsResponse|error

Sample code:

gmail:ListThreadsResponse threadList = check gmail->/users/me/threads(q = "subject:invoice", maxResults = 10);

Sample response:

{"threads": [{"id": "18a1b2c3d4e5f6d0", "snippet": "Please find the invoice attached...", "historyId": "987650"}], "resultSizeEstimate": 1}
Get a thread

Retrieves a specific thread with all its messages.

Parameters:

NameTypeRequiredDescription
userIdstringYesThe user's email address or "me".
idstringYesThe thread ID.
formatstringNoResponse format: "full", "metadata", or "minimal".
metadataHeadersstring[]NoSpecific headers to include when format is "metadata".

Returns: gmail:MailThread|error

Sample code:

gmail:MailThread thread = check gmail->/users/me/threads/["18a1b2c3d4e5f6d0"]();

Sample response:

{"id": "18a1b2c3d4e5f6d0", "historyId": "987654", "messages": [{"id": "18a1b2c3d4e5f6d0", "threadId": "18a1b2c3d4e5f6d0", "snippet": "Please find the invoice..."}]}
Modify a thread

Modifies the labels applied to all messages in a thread.

Parameters:

NameTypeRequiredDescription
userIdstringYesThe user's email address or "me".
idstringYesThe thread ID.
modifyRequestgmail:ModifyThreadRequestYesLabels to add and/or remove.

Returns: gmail:MailThread|error

Sample code:

gmail:MailThread modified = check gmail->/users/me/threads/["18a1b2c3d4e5f6d0"]/modify.post({
addLabelIds: ["IMPORTANT"],
removeLabelIds: ["UNREAD"]
});

Sample response:

{"id": "18a1b2c3d4e5f6d0", "historyId": "987660"}
Trash a thread

Moves all messages in a thread to the trash.

Parameters:

NameTypeRequiredDescription
userIdstringYesThe user's email address or "me".
idstringYesThe thread ID.

Returns: gmail:MailThread|error

Sample code:

gmail:MailThread trashed = check gmail->/users/me/threads/["18a1b2c3d4e5f6d0"]/trash.post();

Sample response:

{"id": "18a1b2c3d4e5f6d0", "historyId": "987661"}
Untrash a thread

Removes all messages in a thread from the trash.

Parameters:

NameTypeRequiredDescription
userIdstringYesThe user's email address or "me".
idstringYesThe thread ID.

Returns: gmail:MailThread|error

Sample code:

gmail:MailThread restored = check gmail->/users/me/threads/["18a1b2c3d4e5f6d0"]/untrash.post();

Sample response:

{"id": "18a1b2c3d4e5f6d0", "historyId": "987662"}
Delete a thread

Permanently deletes a thread and all its messages.

Parameters:

NameTypeRequiredDescription
userIdstringYesThe user's email address or "me".
idstringYesThe thread ID.

Returns: error?

Sample code:

check gmail->/users/me/threads/["18a1b2c3d4e5f6d0"].delete();

Labels

List labels

Lists all labels in the user's mailbox, including system and custom labels.

Parameters:

NameTypeRequiredDescription
userIdstringYesThe user's email address or "me".

Returns: gmail:ListLabelsResponse|error

Sample code:

gmail:ListLabelsResponse labelList = check gmail->/users/me/labels();

Sample response:

{"labels": [{"id": "INBOX", "name": "INBOX", "type": "system"}, {"id": "Label_1", "name": "Work", "type": "user", "messagesTotal": 42, "messagesUnread": 5}]}
Create a label

Creates a new custom label.

Parameters:

NameTypeRequiredDescription
userIdstringYesThe user's email address or "me".
labelgmail:LabelYesThe label to create.

Returns: gmail:Label|error

Sample code:

gmail:Label newLabel = check gmail->/users/me/labels.post({
name: "Invoices",
labelListVisibility: "labelShow",
messageListVisibility: "show"
});

Sample response:

{"id": "Label_25", "name": "Invoices", "type": "user", "labelListVisibility": "labelShow", "messageListVisibility": "show", "messagesTotal": 0, "messagesUnread": 0, "threadsTotal": 0, "threadsUnread": 0}
Get a label

Retrieves a specific label by ID.

Parameters:

NameTypeRequiredDescription
userIdstringYesThe user's email address or "me".
idstringYesThe label ID.

Returns: gmail:Label|error

Sample code:

gmail:Label label = check gmail->/users/me/labels/["Label_25"]();

Sample response:

{"id": "Label_25", "name": "Invoices", "type": "user", "labelListVisibility": "labelShow", "messageListVisibility": "show", "messagesTotal": 12, "messagesUnread": 3, "threadsTotal": 8, "threadsUnread": 2}
Update a label

Replaces all fields of a label with the provided values.

Parameters:

NameTypeRequiredDescription
userIdstringYesThe user's email address or "me".
idstringYesThe label ID.
labelgmail:LabelYesThe full label object with updated values.

Returns: gmail:Label|error

Sample code:

gmail:Label updated = check gmail->/users/me/labels/["Label_25"].put({
name: "Invoices: Paid",
labelListVisibility: "labelShow",
messageListVisibility: "show"
});

Sample response:

{"id": "Label_25", "name": "Invoices: Paid", "type": "user", "labelListVisibility": "labelShow", "messageListVisibility": "show"}
Patch a label

Partially updates a label, modifying only the specified fields.

Parameters:

NameTypeRequiredDescription
userIdstringYesThe user's email address or "me".
idstringYesThe label ID.
labelgmail:LabelYesThe label fields to update.

Returns: gmail:Label|error

Sample code:

gmail:Label patched = check gmail->/users/me/labels/["Label_25"].patch({
name: "Invoices: Archived"
});

Sample response:

{"id": "Label_25", "name": "Invoices: Archived", "type": "user", "labelListVisibility": "labelShow", "messageListVisibility": "show"}
Delete a label

Permanently deletes a custom label. Messages with the label are not deleted.

Parameters:

NameTypeRequiredDescription
userIdstringYesThe user's email address or "me".
idstringYesThe label ID.

Returns: error?

Sample code:

check gmail->/users/me/labels/["Label_25"].delete();

History

List history

Lists the history of changes to the mailbox since a given history ID, useful for incremental sync.

Parameters:

NameTypeRequiredDescription
userIdstringYesThe user's email address or "me".
startHistoryIdstringYesThe history ID to start listing from (obtained from a previous profile or message response).
maxResultsintNoMaximum number of history records to return.
pageTokenstringNoToken for fetching the next page.
labelIdstringNoOnly return history for this label.
historyTypesstring[]NoFilter by history type: "messageAdded", "messageDeleted", "labelAdded", "labelRemoved".

Returns: gmail:ListHistoryResponse|error

Sample code:

gmail:ListHistoryResponse history = check gmail->/users/me/history(startHistoryId = "987654");

Sample response:

{"historyId": "987700", "history": [{"id": "987655", "messagesAdded": [{"message": {"id": "18a1b2c3d4e5f6e0", "threadId": "18a1b2c3d4e5f6e0"}}]}]}