CheddahBot/cheddahbot/gmail_draft.py

57 lines
1.5 KiB
Python

"""Gmail draft creation via Gmail API (OAuth2)."""
from __future__ import annotations
import base64
import logging
from email.mime.text import MIMEText
from googleapiclient.discovery import build
from .google_auth import get_credentials
log = logging.getLogger(__name__)
class GmailDraftClient:
"""Create email drafts in Gmail via the API."""
def __init__(self):
creds = get_credentials()
self._service = build("gmail", "v1", credentials=creds)
def create_draft(
self,
to: str,
subject: str,
body: str,
cc: list[str] | None = None,
) -> str:
"""Create a draft email in the authenticated user's Gmail.
Args:
to: Recipient email address.
subject: Email subject line.
body: Plain text email body.
cc: Optional list of CC email addresses.
Returns:
The Gmail draft ID.
"""
message = MIMEText(body)
message["to"] = to
message["subject"] = subject
if cc:
message["cc"] = ", ".join(cc)
raw = base64.urlsafe_b64encode(message.as_bytes()).decode("ascii")
draft = (
self._service.users()
.drafts()
.create(userId="me", body={"message": {"raw": raw}})
.execute()
)
draft_id = draft["id"]
log.info("Created Gmail draft %s (to=%s, subject=%s)", draft_id, to, subject)
return draft_id