AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
feat(blocks): Add Gmail Draft Reply Block (#10882)
Nicholas Tindlecddeb185a82d
diff --git a/autogpt_platform/backend/backend/blocks/google/gmail.py b/autogpt_platform/backend/backend/blocks/google/gmail.pyindex 1b1fb5eb74..9efeed0331 100644--- a/autogpt_platform/backend/backend/blocks/google/gmail.py+++ b/autogpt_platform/backend/backend/blocks/google/gmail.py@@ -1094,6 +1094,117 @@ class GmailGetThreadBlock(GmailBase):return thread+async def _build_reply_message(+ service, input_data, graph_exec_id: str, user_id: str+) -> tuple[str, str]:+ """+ Builds a reply MIME message for Gmail threads.++ Returns:+ tuple: (base64-encoded raw message, threadId)+ """+ # Get parent message for reply context+ parent = await asyncio.to_thread(+ lambda: service.users()+ .messages()+ .get(+ userId="me",+ id=input_data.parentMessageId,+ format="metadata",+ metadataHeaders=[+ "Subject",+ "References",+ "Message-ID",+ "From",+ "To",+ "Cc",+ "Reply-To",+ ],+ )+ .execute()+ )++ # Build headers dictionary, preserving all values for duplicate headers+ headers = {}+ for h in parent.get("payload", {}).get("headers", []):+ name = h["name"].lower()+ value = h["value"]+ if name in headers:+ # For duplicate headers, keep the first occurrence (most relevant for reply context)+ continue+ headers[name] = value++ # Determine recipients if not specified+ if not (input_data.to or input_data.cc or input_data.bcc):+ if input_data.replyAll:+ recipients = [parseaddr(headers.get("from", ""))[1]]+ recipients += [addr for _, addr in getaddresses([headers.get("to", "")])]+ recipients += [addr for _, addr in getaddresses([headers.get("cc", "")])]+ # Use dict.fromkeys() for O(n) deduplication while preserving order+ input_data.to = list(dict.fromkeys(filter(None, recipients)))+ else:+ # Check Reply-To header first, fall back to From header+ reply_to = headers.get("reply-to", "")+ from_addr = headers.get("from", "")+ sender = parseaddr(reply_to if reply_to else from_addr)[1]+ input_data.to = [sender] if sender else []++ # Set subject with Re: prefix if not already present+ if input_data.subject:+ subject = input_data.subject+ else:+ parent_subject = headers.get("subject", "").strip()+ # Only add "Re:" if not already present (case-insensitive check)+ if parent_subject.lower().startswith("re:"):+ subject = parent_subject+ else:+ subject = f"Re: {parent_subject}" if parent_subject else "Re:"++ # Build references header for proper threading+ references = headers.get("references", "").split()+ if headers.get("message-id"):+ references.append(headers["message-id"])++ # Create MIME message+ msg = MIMEMultipart()+ if input_data.to:+ msg["To"] = ", ".join(input_data.to)+ if input_data.cc:+ msg["Cc"] = ", ".join(input_data.cc)+ if input_data.bcc:+ msg["Bcc"] = ", ".join(input_data.bcc)+ msg["Subject"] = subject+ if headers.get("message-id"):+ msg["In-Reply-To"] = headers["message-id"]+ if references:+ msg["References"] = " ".join(references)++ # Use the helper function for consistent content type handling+ msg.attach(_make_mime_text(input_data.body, input_data.content_type))++ # Handle attachments+ for attach in input_data.attachments:+ local_path = await store_media_file(+ user_id=user_id,+ graph_exec_id=graph_exec_id,+ file=attach,+ return_content=False,+ )+ abs_path = get_exec_file_path(graph_exec_id, local_path)+ part = MIMEBase("application", "octet-stream")+ with open(abs_path, "rb") as f:+ part.set_payload(f.read())+ encoders.encode_base64(part)+ part.add_header(+ "Content-Disposition", f"attachment; filename={Path(abs_path).name}"+ )+ msg.attach(part)++ # Encode message+ raw = base64.urlsafe_b64encode(msg.as_bytes()).decode("utf-8")+ return raw, input_data.threadId++class GmailReplyBlock(GmailBase):"""Replies to Gmail threads with intelligent content type detection.@@ -1230,92 +1341,145 @@ class GmailReplyBlock(GmailBase):async def _reply(self, service, input_data: Input, graph_exec_id: str, user_id: str) -> dict:- parent = await asyncio.to_thread(+ # Build the reply message using the shared helper+ raw, thread_id = await _build_reply_message(+ service, input_data, graph_exec_id, user_id+ )++ # Send the message+ return await asyncio.to_thread(lambda: service.users().messages()- .get(- userId="me",- id=input_data.parentMessageId,- format="metadata",- metadataHeaders=[- "Subject",- "References",- "Message-ID",- "From",- "To",- "Cc",- "Reply-To",- ],- )+ .send(userId="me", body={"threadId": thread_id, "raw": raw}).execute())- headers = {- h["name"].lower(): h["value"]- for h in parent.get("payload", {}).get("headers", [])- }- if not (input_data.to or input_data.cc or input_data.bcc):- if input_data.replyAll:- recipients = [parseaddr(headers.get("from", ""))[1]]- recipients += [- addr for _, addr in getaddresses([headers.get("to", "")])- ]- recipients += [- addr for _, addr in getaddresses([headers.get("cc", "")])- ]- dedup: list[str] = []- for r in recipients:- if r and r not in dedup:- dedup.append(r)- input_data.to = dedup- else:- sender = parseaddr(headers.get("reply-to", headers.get("from", "")))[1]- input_data.to = [sender] if sender else []- subject = input_data.subject or (f"Re: {headers.get('subject', '')}".strip())- references = headers.get("references", "").split()- if headers.get("message-id"):- references.append(headers["message-id"])- msg = MIMEMultipart()- if input_data.to:- msg["To"] = ", ".join(input_data.to)- if input_data.cc:- msg["Cc"] = ", ".join(input_data.cc)- if input_data.bcc:- msg["Bcc"] = ", ".join(input_data.bcc)- msg["Subject"] = subject- if headers.get("message-id"):- msg["In-Reply-To"] = headers["message-id"]- if references:- msg["References"] = " ".join(references)- # Use the new helper function for consistent content type handling- msg.attach(_make_mime_text(input_data.body, input_data.content_type))+class GmailDraftReplyBlock(GmailBase):+ """+ Creates draft replies to Gmail threads with intelligent content type detection.- for attach in input_data.attachments:- local_path = await store_media_file(- user_id=user_id,- graph_exec_id=graph_exec_id,- file=attach,- return_content=False,- )- abs_path = get_exec_file_path(graph_exec_id, local_path)- part = MIMEBase("application", "octet-stream")- with open(abs_path, "rb") as f:- part.set_payload(f.read())- encoders.encode_base64(part)- part.add_header(- "Content-Disposition", f"attachment; filename={Path(abs_path).name}"- )- msg.attach(part)+ Features:+ - Automatic HTML detection: Draft replies containing HTML tags are formatted as text/html+ - No hard-wrap for plain text: Plain text draft replies preserve natural line flow+ - Manual content type override: Use content_type parameter to force specific format+ - Reply-all functionality: Option to reply to all original recipients+ - Thread preservation: Maintains proper email threading with headers+ - Full Unicode/emoji support with UTF-8 encoding+ """- raw = base64.urlsafe_b64encode(msg.as_bytes()).decode("utf-8")- return await asyncio.to_thread(+ class Input(BlockSchema):+ credentials: GoogleCredentialsInput = GoogleCredentialsField(+ [+ "https://www.googleapis.com/auth/gmail.modify",+ "https://www.googleapis.com/auth/gmail.readonly",+ ]+ )+ threadId: str = SchemaField(description="Thread ID to reply in")+ parentMessageId: str = SchemaField(+ description="ID of the message being replied to"+ )+ to: list[str] = SchemaField(description="To recipients", default_factory=list)+ cc: list[str] = SchemaField(description="CC recipients", default_factory=list)+ bcc: list[str] = SchemaField(description="BCC recipients", default_factory=list)+ replyAll: bool = SchemaField(+ description="Reply to all original recipients", default=False+ )+ subject: str = SchemaField(description="Email subject", default="")+ body: str = SchemaField(description="Email body (plain text or HTML)")+ content_type: Optional[Literal["auto", "plain", "html"]] = SchemaField(+ description="Content type: 'auto' (default - detects HTML), 'plain', or 'html'",+ default=None,+ advanced=True,+ )+ attachments: list[MediaFileType] = SchemaField(+ description="Files to attach", default_factory=list, advanced=True+ )++ class Output(BlockSchema):+ draftId: str = SchemaField(description="Created draft ID")+ messageId: str = SchemaField(description="Draft message ID")+ threadId: str = SchemaField(description="Thread ID")+ status: str = SchemaField(description="Draft creation status")+ error: str = SchemaField(description="Error message if any")++ def __init__(self):+ super().__init__(+ id="d7a9f3e2-8b4c-4d6f-9e1a-3c5b7f8d2a6e",+ description="Create draft replies to Gmail threads with automatic HTML detection and proper text formatting. Plain text draft replies maintain natural paragraph flow without 78-character line wrapping. HTML content is automatically detected and formatted correctly.",+ categories={BlockCategory.COMMUNICATION},+ input_schema=GmailDraftReplyBlock.Input,+ output_schema=GmailDraftReplyBlock.Output,+ disabled=not GOOGLE_OAUTH_IS_CONFIGURED,+ test_input={+ "threadId": "t1",+ "parentMessageId": "m1",+ "body": "Thanks for your message. I'll review and get back to you.",+ "replyAll": False,+ "credentials": TEST_CREDENTIALS_INPUT,+ },+ test_credentials=TEST_CREDENTIALS,+ test_output=[+ ("draftId", "draft1"),+ ("messageId", "m2"),+ ("threadId", "t1"),+ ("status", "draft_created"),+ ],+ test_mock={+ "_create_draft_reply": lambda *args, **kwargs: {+ "id": "draft1",+ "message": {"id": "m2", "threadId": "t1"},+ }+ },+ )++ async def run(+ self,+ input_data: Input,+ *,+ credentials: GoogleCredentials,+ graph_exec_id: str,+ user_id: str,+ **kwargs,+ ) -> BlockOutput:+ service = self._build_service(credentials, **kwargs)+ draft = await self._create_draft_reply(+ service,+ input_data,+ graph_exec_id,+ user_id,+ )+ yield "draftId", draft["id"]+ yield "messageId", draft["message"]["id"]+ yield "threadId", draft["message"].get("threadId", input_data.threadId)+ yield "status", "draft_created"++ async def _create_draft_reply(+ self, service, input_data: Input, graph_exec_id: str, user_id: str+ ) -> dict:+ # Build the reply message using the shared helper+ raw, thread_id = await _build_reply_message(+ service, input_data, graph_exec_id, user_id+ )++ # Create draft with proper thread association+ draft = await asyncio.to_thread(lambda: service.users()- .messages()- .send(userId="me", body={"threadId": input_data.threadId, "raw": raw})+ .drafts()+ .create(+ userId="me",+ body={+ "message": {+ "threadId": thread_id,+ "raw": raw,+ }+ },+ ).execute())+ return draft+class GmailGetProfileBlock(GmailBase):class Input(BlockSchema):