google_api module¶
Functions¶
- google_api.authenticate_google_app(credentials_path='gmail_credentials.json', token_path='gmail_token.json', SCOPES=None, service_name=None, service_version=None)¶
Authenticates and returns a Google API service object. Reads cached credentials from
token_pathif available. When a cached token exists but has expired, it is refreshed silently using the stored refresh token. Only when no valid token exists at all is the full OAuth browser flow triggered. The (potentially refreshed) token is always written back totoken_pathso subsequent calls can reuse it.- Parameters:
credentials_path (str, optional) – Path to the OAuth client secrets file downloaded from the Google Cloud console. Defaults to
'gmail_credentials.json'.token_path (str, optional) – Path where the user token is cached. Defaults to
'gmail_token.json'.SCOPES (list of str, optional) – OAuth scopes to request. Defaults to None.
service_name (str, optional) – Google API service identifier (e.g.,
'gmail','calendar'). Defaults to None.service_version (str, optional) – API version string (e.g.,
'v1','v3'). Defaults to None.
- Returns:
Authenticated Google API service object.
- Return type:
googleapiclient.discovery.Resource
Classes¶
- class google_api.Gmail(credentials_path='credentials.json', token_path='token.json', sender=None)¶
Manages and sends Gmail messages via the Gmail API.
- Parameters:
credentials_path (str, optional) – Path to the Google API OAuth credentials file. Defaults to
'credentials.json'.token_path (str, optional) – Path to the cached token file. Defaults to
'token.json'.sender (str, optional) – Default sender email address used when no sender is specified in
make_message. Defaults to None.
- add_message_label(message=None, message_id=None, label_names=None, label_ids=None)¶
Adds one or more labels to a Gmail message.
- Parameters:
message (dict, optional) – Message metadata dict containing an
'id'key. Used whenmessage_idis not provided. Defaults to None.message_id (str, optional) – Gmail message ID. Defaults to None.
label_names (str or list of str, optional) – Label name(s) to add. Accepts a single string or a list of strings. Defaults to None.
label_ids (str or list of str, optional) – Label ID(s) to add. Takes precedence over
label_namesif both are provided. Defaults to None.
- Returns:
None
- delete_message(message=None, message_id=None)¶
Permanently deletes a Gmail message.
- Parameters:
message (dict, optional) – Message metadata dict with an
'id'key. Defaults to None.message_id (str, optional) – Gmail message ID. Defaults to None.
- Returns:
None
- get_all_labels()¶
Retrieves all Gmail labels for the authenticated account.
- Returns:
DataFrame with one row per label, containing label names and metadata returned by the API.
- Return type:
pandas.DataFrame
- get_from_sender(sender, label_name=None, label_id=None)¶
Finds all messages from a specific sender. When
label_nameis provided it is resolved to a label ID viaget_label_id.- Parameters:
sender (str) – Email address of the sender to search for.
label_name (str, optional) – Filter by this label name. Defaults to None.
label_id (str, optional) – Filter by this label ID directly. Takes precedence over
label_nameif both are provided. Defaults to None.
- Returns:
List of message metadata dicts, or None if no messages are found.
- Return type:
list of dict or None
- get_label_id(label_name)¶
Returns the ID of a Gmail label by its display name.
- Parameters:
label_name (str) – The exact label name (case-insensitive).
- Returns:
The label ID, or None if no matching label is found.
- Return type:
str or None
- get_labeled_messages(label_name=None, label_id=None)¶
Retrieves all messages with a specific label. When
label_nameis provided it is resolved to a label ID viaget_label_id.- Parameters:
label_name (str, optional) – Label name to filter by. Defaults to None.
label_id (str, optional) – Label ID to filter by directly. Takes precedence over
label_nameif both are provided. Defaults to None.
- Returns:
List of message metadata dicts, or None if no messages are found.
- Return type:
list of dict or None
- get_message(message=None, message_id=None)¶
Retrieves a full Gmail message by its ID.
- Parameters:
message (dict, optional) – Message metadata dict with an
'id'key. Defaults to None.message_id (str, optional) – Gmail message ID. Defaults to None.
- Returns:
Full Gmail message payload returned by the API.
- Return type:
dict
- get_message_return_path(message=None, message_id=None)¶
Returns the
Return-Path(orFrom) address of a message.- Parameters:
message (dict, optional) – Message metadata dict with an
'id'key. Defaults to None.message_id (str, optional) – Gmail message ID. Defaults to None.
- Returns:
The sender email address extracted from the Return-Path or From header.
- Return type:
str
- get_return_paths(messages=None)¶
Returns the sender address for each message in a list.
- Parameters:
messages (list of dict) – List of message metadata dicts, each containing an
'id'key.- Returns:
Return-Path or From addresses, one per message.
- Return type:
list of str
- make_message(sender=None, to=None, cc=None, bcc=None, subject='No subject', plain_text=None, html_text=None, markdown_text=None, send=True, attachments=None)¶
Creates and optionally sends a Gmail message. At least one of
plain_text,html_text, ormarkdown_textshould be provided. Markdown is converted to HTML before sending. If none is provided, the body defaults to'No message'.- Parameters:
sender (str, optional) – Sender email address. Falls back to
self.senderif not provided. Defaults to None.to (str or list of str, optional) – Recipient address(es). Defaults to None.
cc (str or list of str, optional) – CC address(es). Defaults to None.
bcc (str or list of str, optional) – BCC address(es). Defaults to None.
subject (str, optional) – Email subject line. Defaults to
'No subject'.plain_text (str, optional) – Plain-text email body. Defaults to None.
html_text (str, optional) – HTML email body. Defaults to None.
markdown_text (str, optional) – Markdown email body (converted to HTML). Defaults to None.
send (bool, optional) – If True, send immediately; if False, save as a draft. Defaults to True.
attachments (str or list of str, optional) – File path(s) to attach. Defaults to None.
- Returns:
Sent message metadata if
send=True, draft metadata ifsend=False, or None if an HTTP error occurs.- Return type:
dict or None
- move_message(message=None, message_id=None, old_label_name=None, new_label_name=None)¶
Moves a Gmail message from one label to another. Only the labels that are actually specified are sent to the API, so passing only
new_label_nameadds a label without removing one, and passing onlyold_label_nameremoves a label without adding one.- Parameters:
message (dict, optional) – Message metadata dict with an
'id'key. Defaults to None.message_id (str, optional) – Gmail message ID. Defaults to None.
old_label_name (str, optional) – Label to remove. Defaults to None.
new_label_name (str, optional) – Label to add. Defaults to None.
- Returns:
None
- move_messages(messages=None, old_label_name=None, new_label_name=None)¶
Moves a list of Gmail messages from one label to another by calling
move_messagefor each message.- Parameters:
messages (list of dict) – List of message metadata dicts, each with an
'id'key.old_label_name (str, optional) – Label to remove from each message. Defaults to None.
new_label_name (str, optional) – Label to add to each message. Defaults to None.
- Returns:
None
- remove_message_label(message=None, message_id=None, label_names=None, label_ids=None)¶
Removes one or more labels from a Gmail message.
- Parameters:
message (dict, optional) – Message metadata dict with an
'id'key. Defaults to None.message_id (str, optional) – Gmail message ID. Defaults to None.
label_names (str or list of str, optional) – Label name(s) to remove. Accepts a single string or a list. Defaults to None.
label_ids (str or list of str, optional) – Label ID(s) to remove. Defaults to None.
- Returns:
None
- trash_message(message=None, message_id=None)¶
Moves a Gmail message to the trash.
- Parameters:
message (dict, optional) – Message metadata dict with an
'id'key. Defaults to None.message_id (str, optional) – Gmail message ID. Defaults to None.
- Returns:
None
- class google_api.GoogleCalendar(credentials_path='credentials.json', token_path='token.json')¶
Interacts with Google Calendar via the Calendar API. On initialization, retrieves the list of all calendars and identifies the primary calendar.
- Parameters:
credentials_path (str, optional) – Path to the OAuth client secrets file. Defaults to
'credentials.json'.token_path (str, optional) – Path to the cached token file. Defaults to
'token.json'.
- calendar_ids: pandas.Series¶
Series mapping calendar display names to their calendar IDs.
- primary_calendar: str¶
Display name of the authenticated user’s primary calendar.
- primary_calendar_id: str¶
Calendar ID of the primary calendar.
- add_event(start, end=None, duration=0, duration_units='H', title='Event', description=None, calendar_name=None, calendar_id=None, time_zone=None, all_day=False)¶
Adds a single event to a Google Calendar.
- Parameters:
start (str) – Event start time. Accepts natural-language strings parsed by pandas (e.g.,
'January 4, 2022 4pm').end (str, optional) – Event end time. Defaults to None, in which case
durationis used.duration (float, optional) – Duration of the event in
duration_units. Ignored whenendis provided. Defaults to 0.duration_units (str, optional) – Pandas offset alias for the duration unit (e.g.,
'H'for hours). Defaults to'H'.title (str, optional) – Event title. Defaults to
'Event'.description (str, optional) – Event description. Defaults to None.
calendar_name (str, optional) – Target calendar name. Defaults to None (uses primary calendar).
calendar_id (str, optional) – Target calendar ID. Defaults to None (uses primary calendar).
time_zone (str, optional) – IANA time zone identifier (e.g.,
'America/Los_Angeles'). Defaults to None, which uses the calendar’s own time zone.all_day (bool, optional) – If True, create an all-day event. Defaults to False.
- Raises:
ValueError – If
calendar_nameandcalendar_idrefer to different calendars.- Returns:
None
- delete_events(events=None, calendar_name=None, calendar_id=None)¶
Deletes a list of events from a Google Calendar.
- Parameters:
events (list of dict) – Event dicts as returned by the Calendar API, each containing an
'id'key.calendar_name (str, optional) – Calendar name. Defaults to None (uses primary calendar).
calendar_id (str, optional) – Calendar ID. Defaults to None (uses primary calendar).
- Raises:
ValueError – If
calendar_nameandcalendar_idrefer to different calendars.- Returns:
None
- export_to_ics(event, ics_path='event.ics')¶
Converts a Google Calendar event dict to an ICS file. Handles both timed events (
'dateTime'key) and all-day events ('date'key). All-day events are written withDATEvalues rather thanDATE-TIMEvalues, which is required for calendar clients to display them correctly.- Parameters:
event (dict) – A Google Calendar event dict. Required keys are
'summary','start'(dict with'dateTime'or'date'), and'end'(dict with'dateTime'or'date'). Optional keys include'description','location', and a'timeZone'entry inside'start'/'end'.ics_path (str, optional) – Destination path for the ICS file. Defaults to
'event.ics'.
- Raises:
KeyError – If required event keys are missing.
ValueError – If datetime parsing fails or an invalid time zone is specified.
- Returns:
None
- find_future_events(title_contains=None, description_contains=None, calendar_name=None, calendar_id=None, maxResults=1000)¶
Finds future events matching a title or description keyword.
- Parameters:
title_contains (str, optional) – Return only events whose title contains this string. Defaults to None.
description_contains (str, optional) – Return only events whose description contains this string. Defaults to None.
calendar_name (str, optional) – Calendar to search. Defaults to None (uses primary calendar).
calendar_id (str, optional) – Calendar ID to search. Defaults to None (uses primary calendar).
maxResults (int, optional) – Maximum number of results to fetch from the API before filtering. Defaults to 1000.
- Returns:
Matching future event dicts. Returns all future events if no filter is specified.
- Return type:
list of dict
- Raises:
ValueError – If
calendar_nameandcalendar_idrefer to different calendars.
- import_from_ics(ics_path=None, calendar_name=None, calendar_id=None, delete_ics=False)¶
Imports events from an ICS file into a Google Calendar.
- Parameters:
ics_path (str, optional) – Path to the
.icsfile. Defaults to None.calendar_name (str, optional) – Target calendar name. Defaults to None (uses primary calendar).
calendar_id (str, optional) – Target calendar ID. Defaults to None (uses primary calendar).
delete_ics (bool, optional) – If True, delete the
.icsfile after a successful import. Defaults to False.
- Raises:
FileNotFoundError – If
ics_pathdoes not exist.ValueError – If the ICS file cannot be parsed, or if
calendar_nameandcalendar_idrefer to different calendars.
- Returns:
None
- make_multiple_events(title='Event', description=None, start_date=None, end_date=None, event_time=None, duration=None, duration_units='H', freq='B', periods=None, calendar_name=None, calendar_id=None, time_zone=None)¶
Creates multiple recurring events in a Google Calendar by generating a date range and calling
add_eventfor each date.- Parameters:
title (str, optional) – Event title. Defaults to
'Event'.description (str, optional) – Event description. Defaults to None.
start_date (str) – Start of the recurring series. Accepts natural-language strings parsed by pandas.
end_date (str, optional) – End of the recurring series. Defaults to None.
event_time (str, optional) – Time-of-day to append to
start_datewhen generating the date range. Defaults to None.duration (float, optional) – Duration of each event in
duration_units. Defaults to None.duration_units (str, optional) – Pandas offset alias for the duration unit. Defaults to
'H'.freq (str, optional) – Recurrence frequency as a pandas offset alias (e.g.,
'B'for business days). Defaults to'B'.periods (int, optional) – Number of occurrences to generate. Defaults to None.
calendar_name (str, optional) – Target calendar name. Defaults to None.
calendar_id (str, optional) – Target calendar ID. Defaults to None.
time_zone (str, optional) – IANA time zone identifier. Defaults to None.
- Returns:
None
- parse_ics(ics_path)¶
Parses an ICS file into a list of Google Calendar event dicts. Text fields (
summary,location,description) are returned as plain Python strings. Events missing astartorendfield are silently skipped.- Parameters:
ics_path (str) – Path to the
.icsfile.- Returns:
One dict per
VEVENTcomponent found in the file. Each dict may contain'summary','location','description','start'(dict with'dateTime'and'timeZone'), and'end'(dict with'dateTime'and'timeZone').- Return type:
list of dict
- Raises:
FileNotFoundError – If
ics_pathdoes not exist.ValueError – If the file contains malformed ICS data.