diff --git a/gmail/gmail_tools.py b/gmail/gmail_tools.py
index 2d817f3..f2b3ee9 100644
--- a/gmail/gmail_tools.py
+++ b/gmail/gmail_tools.py
@@ -227,6 +227,114 @@ def _append_signature_to_body(
return f"{body}{separator}{signature_text}"
+async def _fetch_original_for_quote(service, thread_id: str, in_reply_to: Optional[str] = None) -> Optional[dict]:
+ """Fetch the original message from a thread for quoting in a reply.
+
+ When *in_reply_to* is provided the function looks for that specific
+ Message-ID inside the thread. Otherwise it falls back to the last
+ message in the thread.
+
+ Returns a dict with keys: sender, date, text_body, html_body -- or
+ *None* when the message cannot be retrieved.
+ """
+ try:
+ thread_data = await asyncio.to_thread(
+ service.users()
+ .threads()
+ .get(userId="me", id=thread_id, format="full")
+ .execute
+ )
+ except Exception as e:
+ logger.warning(f"Failed to fetch thread {thread_id} for quoting: {e}")
+ return None
+
+ messages = thread_data.get("messages", [])
+ if not messages:
+ return None
+
+ target = None
+ if in_reply_to:
+ for msg in messages:
+ headers = {
+ h["name"]: h["value"]
+ for h in msg.get("payload", {}).get("headers", [])
+ }
+ if headers.get("Message-ID") == in_reply_to:
+ target = msg
+ break
+ if target is None:
+ target = messages[-1]
+
+ headers = {
+ h["name"]: h["value"]
+ for h in target.get("payload", {}).get("headers", [])
+ }
+ bodies = _extract_message_bodies(target.get("payload", {}))
+ return {
+ "sender": headers.get("From", "unknown"),
+ "date": headers.get("Date", ""),
+ "text_body": bodies.get("text", ""),
+ "html_body": bodies.get("html", ""),
+ }
+
+
+def _build_quoted_reply_body(
+ reply_body: str,
+ body_format: Literal["plain", "html"],
+ signature_html: str,
+ original: dict,
+) -> str:
+ """Assemble reply body + signature + quoted original message.
+
+ Layout:
+ reply_body
+ -- signature --
+ On {date}, {sender} wrote:
+ > quoted original
+ """
+ import html as _html_mod
+
+ if original.get("date"):
+ attribution = f"On {original['date']}, {original['sender']} wrote:"
+ else:
+ attribution = f"{original['sender']} wrote:"
+
+ if body_format == "html":
+ # Signature
+ sig_block = ""
+ if signature_html and signature_html.strip():
+ sig_block = f"
{signature_html}"
+
+ # Quoted original
+ orig_html = original.get("html_body") or ""
+ if not orig_html:
+ orig_text = original.get("text_body", "")
+ orig_html = f"
{_html_mod.escape(orig_text)}"
+
+ quote_block = (
+ '' + f"{orig_html}" + "