Gmail¶
Gmail ¶
Gmail(auth: GoogleAuth, user_id: str = 'me')
High-level Gmail client.
Example
auth = GoogleAuth() auth.authenticate()
gmail = Gmail(auth)
Get unread¶
for msg in gmail.get_unread(): print(msg.subject) msg.mark_as_read()
Send¶
gmail.send( to=["user@example.com"], subject="Hello", body="World", )
Initialize Gmail client.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
auth
|
GoogleAuth
|
GoogleAuth instance with valid credentials |
required |
user_id
|
str
|
Gmail user ID ("me" for authenticated user) |
'me'
|
iter_messages ¶
iter_messages(query: str | Query | None = None, labels: list[str] | None = None, max_results: int | None = 25, include_body: bool = True) -> Iterator[Message]
Lazily yield messages matching criteria, following result pages.
Messages are fetched in HTTP batches of 50 rather than one request each. A message deleted while listing is skipped.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str | Query | None
|
Gmail search query (str or Query object) |
None
|
labels
|
list[str] | None
|
Filter by label IDs |
None
|
max_results
|
int | None
|
Maximum messages to yield (None = all matches) |
25
|
include_body
|
bool
|
Whether to fetch full message content |
True
|
get_messages ¶
get_messages(query: str | Query | None = None, labels: list[str] | None = None, max_results: int | None = 25, include_body: bool = True) -> list[Message]
Get messages matching criteria.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str | Query | None
|
Gmail search query (str or Query object) |
None
|
labels
|
list[str] | None
|
Filter by label IDs |
None
|
max_results
|
int | None
|
Maximum messages to return (None = all matches; can be slow) |
25
|
include_body
|
bool
|
Whether to fetch full message content |
True
|
Returns:
| Type | Description |
|---|---|
list[Message]
|
List of Message objects |
search ¶
search(query: str | Query, max_results: int = 25) -> list[Message]
Search messages with a query.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str | Query
|
Gmail search query |
required |
max_results
|
int
|
Maximum results |
25
|
Returns:
| Type | Description |
|---|---|
list[Message]
|
List of matching messages |
get_unread_inbox ¶
get_unread_inbox(max_results: int = 25) -> list[Message]
Get unread messages in inbox.
get_drafts ¶
get_drafts(max_results: int = 25) -> list[Message]
Get draft messages (as Messages; see list_drafts for Draft objects).
get_message ¶
get_message(message_id: str, format: MessageFormat = 'full', headers: Sequence[str] | None = None) -> Message | None
Get a specific message by ID, or None if it doesn't exist.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message_id
|
str
|
Message ID |
required |
format
|
MessageFormat
|
"full" (body included), "metadata" (headers only) or "minimal" |
'full'
|
headers
|
Sequence[str] | None
|
With format="metadata", only these headers ("From", "Subject", ...) |
None
|
get_thread ¶
get_thread(thread_id: str, format: MessageFormat = 'full', headers: Sequence[str] | None = None) -> Thread | None
Get a thread by ID, or None if it doesn't exist.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
thread_id
|
str
|
Thread ID |
required |
format
|
MessageFormat
|
"full" (bodies included), "metadata" (headers only) or "minimal" |
'full'
|
headers
|
Sequence[str] | None
|
With format="metadata", only these headers, e.g. ["From", "To", "Cc", "Subject", "Date"] |
None
|
iter_threads ¶
iter_threads(query: str | Query | None = None, labels: list[str] | None = None, max_results: int | None = 25) -> Iterator[Thread]
Lazily yield conversations matching criteria (fetched in batches).
get_threads ¶
get_threads(query: str | Query | None = None, labels: list[str] | None = None, max_results: int | None = 25) -> list[Thread]
Get conversations matching criteria.
create_label ¶
create_label(name: str, show_in_label_list: bool = True, show_in_message_list: bool = True) -> Label
Create a label. Use "Parent/Child" to nest it.
Returns:
| Type | Description |
|---|---|
Label
|
The new Label |
delete_label ¶
delete_label(label: str) -> bool
Delete a label (by name or ID). Messages keep existing, unlabeled.
Returns:
| Type | Description |
|---|---|
bool
|
True if deleted, False if no such label exists |
batch_modify ¶
batch_modify(message_ids: Sequence[str], add_labels: Sequence[str] | None = None, remove_labels: Sequence[str] | None = None) -> int
Add/remove labels on many messages in a few calls (1000 per call).
Labels can be names or IDs ("UNREAD", "STARRED", "INBOX", "Work"). Example: gmail.batch_modify(ids, remove_labels=["UNREAD"]) marks read.
Returns:
| Type | Description |
|---|---|
int
|
Number of message IDs sent |
list_filters ¶
list_filters() -> list[dict[str, Any]]
List filters ({id, criteria, action} dicts as the API returns them).
create_filter ¶
create_filter(criteria: dict[str, Any], action: dict[str, Any]) -> dict[str, Any]
Create a filter for incoming mail.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
criteria
|
dict[str, Any]
|
e.g. {"from": "alerts@example.com", "hasAttachment": True} |
required |
action
|
dict[str, Any]
|
e.g. {"addLabelIds": ["Alerts"], "removeLabelIds": ["INBOX"]}. Label names are resolved to IDs for you. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
The created filter |
delete_filter ¶
delete_filter(filter_id: str) -> bool
Delete a filter. Returns False if it doesn't exist.
get_signature ¶
get_signature(send_as_email: str | None = None) -> str | None
Get the account's email signature.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
send_as_email
|
str | None
|
Specific send-as email (default: primary) |
None
|
Returns:
| Type | Description |
|---|---|
str | None
|
HTML signature or None |
send ¶
send(to: list[str], subject: str, body: str, cc: list[str] | None = None, bcc: list[str] | None = None, html: bool = False, signature: bool = False, reply_to: str | None = None, thread_id: str | None = None, attachments: list[OutgoingAttachment] | None = None) -> Message
Send an email.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
to
|
list[str]
|
Recipient email addresses |
required |
subject
|
str
|
Email subject |
required |
body
|
str
|
Email body |
required |
cc
|
list[str] | None
|
CC recipients |
None
|
bcc
|
list[str] | None
|
BCC recipients |
None
|
html
|
bool
|
Whether body is HTML (a plain-text alternative is added) |
False
|
signature
|
bool
|
Include account signature (appends to body) |
False
|
reply_to
|
str | None
|
Gmail message ID this replies to; sets the threading headers and thread (see reply() for a higher-level version) |
None
|
thread_id
|
str | None
|
Thread ID (for threading) |
None
|
attachments
|
list[OutgoingAttachment] | None
|
File paths or (filename, bytes) tuples |
None
|
Returns:
| Type | Description |
|---|---|
Message
|
The sent message |
reply ¶
reply(message: Message, body: str, html: bool = False, signature: bool = False, reply_all: bool = False, attachments: list[OutgoingAttachment] | None = None) -> Message
Reply to a message, in its thread for every participant.
Goes to the Reply-To address (or the sender). Replying to a message you sent goes to its recipients instead of back to you.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reply_all
|
bool
|
Also include the other To/Cc recipients |
False
|
Returns:
| Type | Description |
|---|---|
Message
|
The sent reply |
forward ¶
forward(message: Message, to: list[str], body: str = '', include_attachments: bool = True) -> Message
Forward a message, quoting it below body.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include_attachments
|
bool
|
Re-attach the original attachments |
True
|
Returns:
| Type | Description |
|---|---|
Message
|
The sent message |
create_draft ¶
create_draft(to: list[str], subject: str, body: str, cc: list[str] | None = None, bcc: list[str] | None = None, html: bool = False, attachments: list[OutgoingAttachment] | None = None, reply_to: str | None = None) -> Draft
Save a draft (same arguments as send()).
list_drafts ¶
list_drafts(max_results: int | None = 25) -> list[Draft]
List drafts with their content (fetched in batches).
delete_draft ¶
delete_draft(draft_id: str) -> bool
Discard a draft. Returns False if it doesn't exist.
iter_message_ids ¶
iter_message_ids(query: str | Query | None = None, labels: list[str] | None = None, max_results: int | None = None) -> Iterator[str]
IDs of the matching messages, without fetching them (500 per request).
list_message_ids ¶
list_message_ids(query: str | Query | None = None, labels: list[str] | None = None, page_token: str | None = None, page_size: int = 500) -> IdPage
One page of matching message IDs, to page through a listing yourself.
iter_message_ids follows every page in one go; this returns one and
its next_page_token, so a long listing can stop and resume later.
iter_thread_ids ¶
iter_thread_ids(query: str | Query | None = None, labels: list[str] | None = None, max_results: int | None = None) -> Iterator[str]
IDs of the matching threads, without fetching them.
get_history_id ¶
get_history_id() -> str
The mailbox's current history ID: where a first history call starts.
history ¶
history(start_history_id: str, history_types: Sequence[HistoryType] | None = None, label_id: str | None = None) -> HistoryDelta
Message IDs added, deleted or relabeled since start_history_id.
Follows every page; keep delta.history_id for the next call.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start_history_id
|
str
|
From |
required |
history_types
|
Sequence[HistoryType] | None
|
Only these changes ("messageAdded", "messageDeleted", "labelAdded", "labelRemoved"); default all |
None
|
label_id
|
str | None
|
Only changes to messages with this label ID |
None
|
Raises:
| Type | Description |
|---|---|
SyncTokenExpiredError
|
Gmail no longer has that history (it keeps
about a week); list the messages again and start over from
|
watch ¶
watch(topic: str, label_ids: Sequence[str] | None = None, label_filter: LabelFilter = 'include') -> MailboxWatch
Have Gmail publish to a Pub/Sub topic whenever the mailbox changes.
Each notification says only that something changed, with a history ID:
ask history() for the changes since the one you kept. The topic
must let gmail-api-push@system.gserviceaccount.com publish. Gmail
stops after about a week: call this again before
watch.expiration (calling it early is fine, e.g. daily).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
topic
|
str
|
|
required |
label_ids
|
Sequence[str] | None
|
Only notify about (or, with "exclude", ignore) messages with these label IDs; default: every change |
None
|
label_filter
|
LabelFilter
|
"include" or "exclude" |
'include'
|
Returns:
| Type | Description |
|---|---|
MailboxWatch
|
The mailbox's current history ID and when the watch expires |
AsyncGmail ¶
AsyncGmail(auth: Any, user_id: str = 'me', *, concurrency: int = 10, timeout: float | None = None, transport: Any = None)
Async Gmail client.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
auth
|
Any
|
GoogleAuth (OAuth or service account) or google-auth credentials |
required |
user_id
|
str
|
Gmail user ID ("me" for the authenticated user) |
'me'
|
concurrency
|
int
|
Requests in flight at once when fetching many messages, threads, labels or drafts (the sync client uses HTTP batches) |
10
|
timeout
|
float | None
|
Seconds per request (default: GSUITE_REQUEST_TIMEOUT) |
None
|
transport
|
Any
|
httpx transport (tests) |
None
|
iter_messages
async
¶
iter_messages(query: str | Query | None = None, labels: list[str] | None = None, max_results: int | None = 25, include_body: bool = True) -> AsyncIterator[Message]
Lazily yield messages matching criteria, following result pages.
Each page's messages are fetched concurrently; one deleted while listing is skipped.
get_messages
async
¶
get_messages(query: str | Query | None = None, labels: list[str] | None = None, max_results: int | None = 25, include_body: bool = True) -> list[Message]
Messages matching criteria (None = all matches; can be slow).
search
async
¶
search(query: str | Query, max_results: int = 25) -> list[Message]
Messages matching a Gmail query.
get_message
async
¶
get_message(message_id: str, format: MessageFormat = 'full', headers: Sequence[str] | None = None) -> Message | None
A message by ID, or None if it doesn't exist (format/headers as in Gmail).
download_attachment
async
¶
download_attachment(message_id: str, attachment_id: str) -> bytes
Content of an attachment (attachment.download() for sync messages).
get_thread
async
¶
get_thread(thread_id: str, format: MessageFormat = 'full', headers: Sequence[str] | None = None) -> Thread | None
A conversation, or None if it doesn't exist (format/headers as in Gmail).
get_threads
async
¶
get_threads(query: str | Query | None = None, labels: list[str] | None = None, max_results: int | None = 25) -> list[Thread]
Conversations matching criteria.
create_label
async
¶
create_label(name: str, show_in_label_list: bool = True, show_in_message_list: bool = True) -> Label
Create a label. Use "Parent/Child" to nest it.
rename_label
async
¶
rename_label(label: str, new_name: str) -> Label
Rename a label (by name or ID).
delete_label
async
¶
delete_label(label: str) -> bool
Delete a label (by name or ID); False if there is no such label.
batch_modify
async
¶
batch_modify(message_ids: Sequence[str], add_labels: Sequence[str] | None = None, remove_labels: Sequence[str] | None = None) -> int
Add/remove labels on many messages in a few calls (1000 per call).
Labels can be names or IDs ("UNREAD", "STARRED", "INBOX", "Work"). Example: remove_labels=["UNREAD"] marks read.
Returns:
| Type | Description |
|---|---|
int
|
Number of message IDs sent |
modify_message
async
¶
modify_message(message: Message, add_labels: Sequence[str] = (), remove_labels: Sequence[str] = ()) -> Message
Add/remove labels on one message, as the sync fluent methods do.
Labels are names or IDs. Like message.add_label(), an unknown name
is skipped, and a label the message already has (or lacks) isn't sent.
message.labels is updated; the same message is returned.
Example
await gmail.modify_message(message, remove_labels=["UNREAD"]) # read
list_filters
async
¶
list_filters() -> list[dict[str, Any]]
Filters ({id, criteria, action} dicts as the API returns them).
create_filter
async
¶
create_filter(criteria: dict[str, Any], action: dict[str, Any]) -> dict[str, Any]
Create a filter; label names in the action are resolved to IDs.
delete_filter
async
¶
delete_filter(filter_id: str) -> bool
Delete a filter; False if it doesn't exist.
iter_message_ids ¶
iter_message_ids(query: str | Query | None = None, labels: list[str] | None = None, max_results: int | None = None) -> AsyncIterator[str]
IDs of the matching messages, without fetching them (500 per request).
list_message_ids
async
¶
list_message_ids(query: str | Query | None = None, labels: list[str] | None = None, page_token: str | None = None, page_size: int = 500) -> IdPage
One page of matching message IDs and the next page's token (see Gmail).
iter_thread_ids ¶
iter_thread_ids(query: str | Query | None = None, labels: list[str] | None = None, max_results: int | None = None) -> AsyncIterator[str]
IDs of the matching threads, without fetching them.
get_history_id
async
¶
get_history_id() -> str
The mailbox's current history ID: where a first history call starts.
history
async
¶
history(start_history_id: str, history_types: Sequence[HistoryType] | None = None, label_id: str | None = None) -> HistoryDelta
Message IDs added, deleted or relabeled since start_history_id (see Gmail).
Raises:
| Type | Description |
|---|---|
SyncTokenExpiredError
|
Gmail no longer has that history; start over. |
watch
async
¶
watch(topic: str, label_ids: Sequence[str] | None = None, label_filter: LabelFilter = 'include') -> MailboxWatch
Have Gmail publish to a Pub/Sub topic when the mailbox changes (see Gmail.watch).
get_signature
async
¶
get_signature(send_as_email: str | None = None) -> str | None
The account's HTML signature, or None (best effort, never raises).
send
async
¶
send(to: list[str], subject: str, body: str, cc: list[str] | None = None, bcc: list[str] | None = None, html: bool = False, signature: bool = False, reply_to: str | None = None, thread_id: str | None = None, attachments: list[OutgoingAttachment] | None = None) -> Message
Send an email (same arguments as Gmail.send); returns the sent message.
reply
async
¶
reply(message: Message, body: str, html: bool = False, signature: bool = False, reply_all: bool = False, attachments: list[OutgoingAttachment] | None = None) -> Message
Reply in the message's thread (same rules as Gmail.reply).
forward
async
¶
forward(message: Message, to: list[str], body: str = '', include_attachments: bool = True) -> Message
Forward a message, quoting it below body.
create_draft
async
¶
create_draft(to: list[str], subject: str, body: str, cc: list[str] | None = None, bcc: list[str] | None = None, html: bool = False, attachments: list[OutgoingAttachment] | None = None, reply_to: str | None = None) -> Draft
Save a draft (same arguments as send()).
list_drafts
async
¶
list_drafts(max_results: int | None = 25) -> list[Draft]
Drafts with their content (fetched concurrently).
delete_draft
async
¶
delete_draft(draft_id: str) -> bool
Discard a draft; False if it doesn't exist.
Message
dataclass
¶
Message(id: str, thread_id: str, subject: str, sender: str, recipient: str, cc: list[str] = list(), bcc: list[str] = list(), date: datetime | None = None, snippet: str = '', plain: str | None = None, html: str | None = None, labels: list[str] = list(), attachments: list[Attachment] = list(), reply_to: str | None = None, rfc822_message_id: str | None = None, references: str | None = None, raw: dict[str, Any] = dict(), _gmail: Optional[Gmail] = None)
Gmail message with fluent modification methods.
Example
message.mark_as_read().star().add_label("Work")
reply ¶
reply(body: str, html: bool = False, signature: bool = False, reply_all: bool = False, attachments: list[OutgoingAttachment] | None = None) -> Message
Reply to this message, in the same thread for every participant.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
body
|
str
|
Reply body |
required |
html
|
bool
|
Whether body is HTML |
False
|
signature
|
bool
|
Include account signature |
False
|
reply_all
|
bool
|
Also reply to the other To/Cc recipients |
False
|
attachments
|
list[OutgoingAttachment] | None
|
File paths or (filename, bytes) tuples |
None
|
Returns:
| Type | Description |
|---|---|
Message
|
The sent reply message |
forward ¶
forward(to: list[str], body: str = '', include_attachments: bool = True) -> Message
Forward this message (with its attachments by default).
HistoryDelta
dataclass
¶
HistoryDelta(added: list[str] = list(), deleted: list[str] = list(), labels_changed: list[str] = list(), history_id: str | None = None, added_labels: dict[str, list[str]] = dict())
Message IDs that changed since a history ID, and the ID to resume from.
A message added and then deleted in the same window appears only in
deleted; labels_changed leaves out deleted messages too. Keep
history_id and pass it to the next Gmail.history.
IdPage
dataclass
¶
IdPage(ids: list[str] = list(), next_page_token: str | None = None)
One page of message IDs, and the token for the next (None on the last page).
Store next_page_token to resume a long listing later, e.g. across runs.
MailboxWatch
dataclass
¶
MailboxWatch(history_id: str, expiration: datetime | None = None)
A mailbox being watched: Gmail publishes to a Pub/Sub topic when it changes.
history_id is where the first Gmail.history call after a
notification starts. Gmail stops publishing at expiration (about a week
later): call watch again before then, e.g. once a day.