gws-cli 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
gws/services/gmail.py ADDED
@@ -0,0 +1,2001 @@
1
+ """Google Gmail service operations."""
2
+
3
+ import base64
4
+ import mimetypes
5
+ import os
6
+ from email import encoders
7
+ from email.mime.base import MIMEBase
8
+ from email.mime.multipart import MIMEMultipart
9
+ from email.mime.text import MIMEText
10
+ from typing import Any
11
+
12
+ from googleapiclient.errors import HttpError
13
+
14
+ from gws.services.base import BaseService
15
+ from gws.output import output_success, output_error, output_external_content
16
+ from gws.exceptions import ExitCode
17
+
18
+
19
+ class GmailService(BaseService):
20
+ """Google Gmail operations."""
21
+
22
+ SERVICE_NAME = "gmail"
23
+ VERSION = "v1"
24
+
25
+ def list_messages(
26
+ self,
27
+ query: str | None = None,
28
+ max_results: int = 10,
29
+ label_ids: list[str] | None = None,
30
+ ) -> dict[str, Any]:
31
+ """List messages matching criteria."""
32
+ try:
33
+ params: dict[str, Any] = {
34
+ "userId": "me",
35
+ "maxResults": max_results,
36
+ }
37
+
38
+ if query:
39
+ params["q"] = query
40
+ if label_ids:
41
+ params["labelIds"] = label_ids
42
+
43
+ result = self.execute(self.service.users().messages().list(**params))
44
+
45
+ messages: list[dict[str, Any]] = []
46
+ batch_errors: dict[str, str] = {}
47
+ msg_refs = result.get("messages", [])
48
+
49
+ if msg_refs:
50
+ # Use batch request to fetch all messages in one round-trip
51
+ batch_results: dict[str, Any] = {}
52
+
53
+ def handle_response(request_id: str, response: Any, exception: Any) -> None:
54
+ if exception is None:
55
+ batch_results[request_id] = response
56
+ else:
57
+ batch_errors[request_id] = str(exception)
58
+
59
+ batch = self.service.new_batch_http_request(callback=handle_response)
60
+ for msg_ref in msg_refs:
61
+ batch.add(
62
+ self.service.users()
63
+ .messages()
64
+ .get(
65
+ userId="me",
66
+ id=msg_ref["id"],
67
+ format="metadata",
68
+ metadataHeaders=["From", "To", "Subject", "Date"],
69
+ ),
70
+ request_id=msg_ref["id"],
71
+ )
72
+ batch.execute()
73
+
74
+ # Process batch results in original order
75
+ for msg_ref in msg_refs:
76
+ msg = batch_results.get(msg_ref["id"])
77
+ if not msg:
78
+ continue
79
+
80
+ headers = {
81
+ h["name"]: h["value"]
82
+ for h in msg.get("payload", {}).get("headers", [])
83
+ }
84
+
85
+ messages.append({
86
+ "id": msg["id"],
87
+ "thread_id": msg["threadId"],
88
+ "subject": headers.get("Subject", "(no subject)"),
89
+ "from": headers.get("From", ""),
90
+ "to": headers.get("To", ""),
91
+ "date": headers.get("Date", ""),
92
+ "snippet": msg.get("snippet", "")[:100],
93
+ })
94
+
95
+ output_kwargs: dict[str, Any] = {
96
+ "operation": "gmail.list",
97
+ "message_count": len(messages),
98
+ "messages": messages,
99
+ "next_page_token": result.get("nextPageToken"),
100
+ }
101
+ if batch_errors:
102
+ output_kwargs["failed_ids"] = batch_errors
103
+ output_success(**output_kwargs)
104
+ return result
105
+ except HttpError as e:
106
+ output_error(
107
+ error_code="API_ERROR",
108
+ operation="gmail.list",
109
+ message=f"Gmail API error: {e.reason}",
110
+ )
111
+ raise SystemExit(ExitCode.API_ERROR)
112
+
113
+ def read_message(
114
+ self,
115
+ message_id: str,
116
+ format_type: str = "full",
117
+ ) -> dict[str, Any]:
118
+ """Read a message by ID."""
119
+ try:
120
+ msg = self.execute(
121
+ self.service.users()
122
+ .messages()
123
+ .get(userId="me", id=message_id, format=format_type)
124
+ )
125
+
126
+ # Build case-insensitive header lookup (Gmail API may return lowercase
127
+ # header names for messages sent via the API)
128
+ raw_headers = {
129
+ h["name"]: h["value"]
130
+ for h in msg.get("payload", {}).get("headers", [])
131
+ }
132
+ headers = {k.lower(): v for k, v in raw_headers.items()}
133
+
134
+ # Extract body
135
+ body = self._extract_body(msg.get("payload", {}))
136
+
137
+ # Extract attachments info
138
+ attachments = self._extract_attachments(msg.get("payload", {}))
139
+
140
+ output_external_content(
141
+ operation="gmail.read",
142
+ source_type="email",
143
+ source_id=message_id,
144
+ content_fields={
145
+ "subject": headers.get("subject", "(no subject)"),
146
+ "body": body,
147
+ },
148
+ message_id=message_id,
149
+ thread_id=msg["threadId"],
150
+ history_id=msg.get("historyId"),
151
+ from_address=headers.get("from", ""),
152
+ to_address=headers.get("to", ""),
153
+ cc=headers.get("cc", ""),
154
+ date=headers.get("date", ""),
155
+ labels=msg.get("labelIds", []),
156
+ attachments=attachments,
157
+ )
158
+ return msg
159
+ except HttpError as e:
160
+ output_error(
161
+ error_code="API_ERROR",
162
+ operation="gmail.read",
163
+ message=f"Gmail API error: {e.reason}",
164
+ )
165
+ raise SystemExit(ExitCode.API_ERROR)
166
+
167
+ def _extract_body(self, payload: dict) -> str:
168
+ """Extract message body from payload."""
169
+ if "body" in payload and payload["body"].get("data"):
170
+ return base64.urlsafe_b64decode(payload["body"]["data"]).decode("utf-8")
171
+
172
+ if "parts" in payload:
173
+ for part in payload["parts"]:
174
+ if part["mimeType"] == "text/plain":
175
+ if "data" in part.get("body", {}):
176
+ return base64.urlsafe_b64decode(
177
+ part["body"]["data"]
178
+ ).decode("utf-8")
179
+ elif part["mimeType"] == "multipart/alternative":
180
+ return self._extract_body(part)
181
+
182
+ return ""
183
+
184
+ def _extract_attachments(self, payload: dict) -> list[dict]:
185
+ """Extract attachment info from payload."""
186
+ attachments = []
187
+
188
+ if "parts" in payload:
189
+ for part in payload["parts"]:
190
+ if part.get("filename"):
191
+ attachments.append({
192
+ "filename": part["filename"],
193
+ "mime_type": part["mimeType"],
194
+ "size": part.get("body", {}).get("size", 0),
195
+ "attachment_id": part.get("body", {}).get("attachmentId"),
196
+ })
197
+ if "parts" in part:
198
+ attachments.extend(self._extract_attachments(part))
199
+
200
+ return attachments
201
+
202
+ def get_profile(self) -> dict[str, Any]:
203
+ """Get the current user's Gmail profile.
204
+
205
+ Best-effort: returns empty dict on API errors since profile data
206
+ (display name for email sender) is non-critical.
207
+ """
208
+ try:
209
+ profile = self.execute(self.service.users().getProfile(userId="me"))
210
+ return profile
211
+ except HttpError:
212
+ return {}
213
+
214
+ def _unescape_text(self, text: str) -> str:
215
+ """Remove unnecessary escape sequences from text.
216
+
217
+ This handles cases where shell environments escape special characters
218
+ like exclamation marks (\\! -> !).
219
+ """
220
+ # Unescape common shell-escaped characters
221
+ return text.replace("\\!", "!")
222
+
223
+ def send_message(
224
+ self,
225
+ to: str,
226
+ subject: str,
227
+ body: str,
228
+ cc: str | None = None,
229
+ bcc: str | None = None,
230
+ html: bool = False,
231
+ from_name: str | None = None,
232
+ signature: str | None = None,
233
+ ) -> dict[str, Any]:
234
+ """Send a new email message."""
235
+ try:
236
+ # Unescape shell-escaped characters
237
+ subject = self._unescape_text(subject)
238
+ body = self._unescape_text(body)
239
+ if signature:
240
+ signature = self._unescape_text(signature)
241
+
242
+ # Append signature if provided
243
+ full_body = body
244
+ if signature:
245
+ full_body = f"{body}\n\n--\n{signature}"
246
+
247
+ # Use MIMEText directly - MIMEMultipart only needed for attachments
248
+ subtype = "html" if html else "plain"
249
+ message = MIMEText(full_body, subtype, "utf-8")
250
+
251
+ message["to"] = to
252
+ message["subject"] = subject
253
+
254
+ # Set From with display name (explicit > account config)
255
+ effective_name = from_name or self.auth_manager.config.get_account_display_name(
256
+ self.auth_manager.account_name
257
+ )
258
+ if effective_name:
259
+ profile = self.get_profile()
260
+ email_address = profile.get("emailAddress", "")
261
+ if email_address:
262
+ message["from"] = f'"{effective_name}" <{email_address}>'
263
+
264
+ if cc:
265
+ message["cc"] = cc
266
+ if bcc:
267
+ message["bcc"] = bcc
268
+
269
+ raw = base64.urlsafe_b64encode(message.as_bytes()).decode("utf-8")
270
+
271
+ result = self.execute(
272
+ self.service.users()
273
+ .messages()
274
+ .send(userId="me", body={"raw": raw})
275
+ )
276
+
277
+ output_success(
278
+ operation="gmail.send",
279
+ message_id=result["id"],
280
+ thread_id=result["threadId"],
281
+ to=to,
282
+ subject=subject,
283
+ )
284
+ return result
285
+ except HttpError as e:
286
+ output_error(
287
+ error_code="API_ERROR",
288
+ operation="gmail.send",
289
+ message=f"Gmail API error: {e.reason}",
290
+ )
291
+ raise SystemExit(ExitCode.API_ERROR)
292
+
293
+ def reply_to_message(
294
+ self,
295
+ message_id: str,
296
+ body: str,
297
+ html: bool = False,
298
+ from_name: str | None = None,
299
+ signature: str | None = None,
300
+ ) -> dict[str, Any]:
301
+ """Reply to an existing message."""
302
+ try:
303
+ # Unescape shell-escaped characters
304
+ body = self._unescape_text(body)
305
+ if signature:
306
+ signature = self._unescape_text(signature)
307
+
308
+ # Get the original message
309
+ original = self.execute(
310
+ self.service.users()
311
+ .messages()
312
+ .get(userId="me", id=message_id, format="full")
313
+ )
314
+
315
+ thread_id = original["threadId"]
316
+ headers = {
317
+ h["name"]: h["value"]
318
+ for h in original.get("payload", {}).get("headers", [])
319
+ }
320
+
321
+ # Append signature if provided
322
+ full_body = body
323
+ if signature:
324
+ full_body = f"{body}\n\n--\n{signature}"
325
+
326
+ # Build reply - use MIMEText directly
327
+ subtype = "html" if html else "plain"
328
+ message = MIMEText(full_body, subtype, "utf-8")
329
+
330
+ # Set From with display name if provided
331
+ if from_name:
332
+ profile = self.get_profile()
333
+ email_address = profile.get("emailAddress", "")
334
+ if email_address:
335
+ message["from"] = f'"{from_name}" <{email_address}>'
336
+
337
+ # Reply to the sender — use case-insensitive header lookup
338
+ # Gmail API may return lowercase header names (from, to) for sent messages
339
+ ci_headers = {k.lower(): v for k, v in headers.items()}
340
+ reply_to = ci_headers.get("reply-to", ci_headers.get("from", ""))
341
+ if not reply_to:
342
+ reply_to = ci_headers.get("to", "")
343
+ message["to"] = reply_to
344
+ message["subject"] = f"Re: {ci_headers.get('subject', '')}"
345
+
346
+ # Set references for threading
347
+ message_id_header = ci_headers.get("message-id", "")
348
+ if message_id_header:
349
+ message["In-Reply-To"] = message_id_header
350
+ message["References"] = message_id_header
351
+
352
+ raw = base64.urlsafe_b64encode(message.as_bytes()).decode("utf-8")
353
+
354
+ result = self.execute(
355
+ self.service.users()
356
+ .messages()
357
+ .send(userId="me", body={"raw": raw, "threadId": thread_id})
358
+ )
359
+
360
+ output_success(
361
+ operation="gmail.reply",
362
+ message_id=result["id"],
363
+ thread_id=result["threadId"],
364
+ to=reply_to,
365
+ subject=message["subject"],
366
+ )
367
+ return result
368
+ except HttpError as e:
369
+ output_error(
370
+ error_code="API_ERROR",
371
+ operation="gmail.reply",
372
+ message=f"Gmail API error: {e.reason}",
373
+ )
374
+ raise SystemExit(ExitCode.API_ERROR)
375
+
376
+ def search_messages(
377
+ self,
378
+ query: str,
379
+ max_results: int = 10,
380
+ ) -> dict[str, Any]:
381
+ """Search messages using Gmail query syntax."""
382
+ return self.list_messages(query=query, max_results=max_results)
383
+
384
+ def delete_message(
385
+ self,
386
+ message_id: str,
387
+ permanent: bool = False,
388
+ ) -> dict[str, Any]:
389
+ """Delete a message (move to trash or permanent delete)."""
390
+ try:
391
+ if permanent:
392
+ self.execute(self.service.users().messages().delete(
393
+ userId="me", id=message_id
394
+ ))
395
+ output_success(
396
+ operation="gmail.delete",
397
+ message_id=message_id,
398
+ permanent=True,
399
+ )
400
+ else:
401
+ result = self.execute(
402
+ self.service.users()
403
+ .messages()
404
+ .trash(userId="me", id=message_id)
405
+ )
406
+ output_success(
407
+ operation="gmail.delete",
408
+ message_id=message_id,
409
+ permanent=False,
410
+ moved_to_trash=True,
411
+ )
412
+ return result
413
+
414
+ return {"id": message_id, "deleted": True}
415
+ except HttpError as e:
416
+ output_error(
417
+ error_code="API_ERROR",
418
+ operation="gmail.delete",
419
+ message=f"Gmail API error: {e.reason}",
420
+ )
421
+ raise SystemExit(ExitCode.API_ERROR)
422
+
423
+ def mark_as_read(self, message_id: str) -> dict[str, Any]:
424
+ """Mark a message as read by removing the UNREAD label."""
425
+ try:
426
+ result = self.execute(
427
+ self.service.users()
428
+ .messages()
429
+ .modify(
430
+ userId="me",
431
+ id=message_id,
432
+ body={"removeLabelIds": ["UNREAD"]},
433
+ )
434
+ )
435
+ output_success(
436
+ operation="gmail.mark-read",
437
+ message_id=message_id,
438
+ labels=result.get("labelIds", []),
439
+ )
440
+ return result
441
+ except HttpError as e:
442
+ output_error(
443
+ error_code="API_ERROR",
444
+ operation="gmail.mark-read",
445
+ message=f"Gmail API error: {e.reason}",
446
+ )
447
+ raise SystemExit(ExitCode.API_ERROR)
448
+
449
+ def mark_as_unread(self, message_id: str) -> dict[str, Any]:
450
+ """Mark a message as unread by adding the UNREAD label."""
451
+ try:
452
+ result = self.execute(
453
+ self.service.users()
454
+ .messages()
455
+ .modify(
456
+ userId="me",
457
+ id=message_id,
458
+ body={"addLabelIds": ["UNREAD"]},
459
+ )
460
+ )
461
+ output_success(
462
+ operation="gmail.mark-unread",
463
+ message_id=message_id,
464
+ labels=result.get("labelIds", []),
465
+ )
466
+ return result
467
+ except HttpError as e:
468
+ output_error(
469
+ error_code="API_ERROR",
470
+ operation="gmail.mark-unread",
471
+ message=f"Gmail API error: {e.reason}",
472
+ )
473
+ raise SystemExit(ExitCode.API_ERROR)
474
+
475
+ # ===== Label Operations =====
476
+
477
+ def list_labels(self) -> dict[str, Any]:
478
+ """List all labels in the mailbox."""
479
+ try:
480
+ result = self.execute(self.service.users().labels().list(userId="me"))
481
+
482
+ labels = []
483
+ for label in result.get("labels", []):
484
+ labels.append({
485
+ "id": label["id"],
486
+ "name": label["name"],
487
+ "type": label.get("type", "user"),
488
+ "message_list_visibility": label.get("messageListVisibility"),
489
+ "label_list_visibility": label.get("labelListVisibility"),
490
+ })
491
+
492
+ output_success(
493
+ operation="gmail.list_labels",
494
+ label_count=len(labels),
495
+ labels=labels,
496
+ )
497
+ return result
498
+ except HttpError as e:
499
+ output_error(
500
+ error_code="API_ERROR",
501
+ operation="gmail.list_labels",
502
+ message=f"Gmail API error: {e.reason}",
503
+ )
504
+ raise SystemExit(ExitCode.API_ERROR)
505
+
506
+ def create_label(
507
+ self,
508
+ name: str,
509
+ message_list_visibility: str = "show",
510
+ label_list_visibility: str = "labelShow",
511
+ ) -> dict[str, Any]:
512
+ """Create a new label.
513
+
514
+ Args:
515
+ name: Label name.
516
+ message_list_visibility: Show label in message list (show/hide).
517
+ label_list_visibility: Show in label list (labelShow/labelShowIfUnread/labelHide).
518
+ """
519
+ try:
520
+ label_body = {
521
+ "name": name,
522
+ "messageListVisibility": message_list_visibility,
523
+ "labelListVisibility": label_list_visibility,
524
+ }
525
+
526
+ result = self.execute(
527
+ self.service.users()
528
+ .labels()
529
+ .create(userId="me", body=label_body)
530
+ )
531
+
532
+ output_success(
533
+ operation="gmail.create_label",
534
+ label_id=result["id"],
535
+ name=result["name"],
536
+ )
537
+ return result
538
+ except HttpError as e:
539
+ output_error(
540
+ error_code="API_ERROR",
541
+ operation="gmail.create_label",
542
+ message=f"Gmail API error: {e.reason}",
543
+ )
544
+ raise SystemExit(ExitCode.API_ERROR)
545
+
546
+ def delete_label(self, label_id: str) -> dict[str, Any]:
547
+ """Delete a label.
548
+
549
+ Args:
550
+ label_id: The label ID to delete.
551
+ """
552
+ try:
553
+ self.execute(self.service.users().labels().delete(userId="me", id=label_id))
554
+
555
+ output_success(
556
+ operation="gmail.delete_label",
557
+ label_id=label_id,
558
+ )
559
+ return {"deleted": True, "label_id": label_id}
560
+ except HttpError as e:
561
+ output_error(
562
+ error_code="API_ERROR",
563
+ operation="gmail.delete_label",
564
+ message=f"Gmail API error: {e.reason}",
565
+ )
566
+ raise SystemExit(ExitCode.API_ERROR)
567
+
568
+ def add_labels(
569
+ self,
570
+ message_id: str,
571
+ label_ids: list[str],
572
+ ) -> dict[str, Any]:
573
+ """Add labels to a message.
574
+
575
+ Args:
576
+ message_id: The message ID.
577
+ label_ids: List of label IDs to add.
578
+ """
579
+ try:
580
+ result = self.execute(
581
+ self.service.users()
582
+ .messages()
583
+ .modify(
584
+ userId="me",
585
+ id=message_id,
586
+ body={"addLabelIds": label_ids},
587
+ )
588
+ )
589
+
590
+ output_success(
591
+ operation="gmail.add_labels",
592
+ message_id=message_id,
593
+ added_labels=label_ids,
594
+ current_labels=result.get("labelIds", []),
595
+ )
596
+ return result
597
+ except HttpError as e:
598
+ output_error(
599
+ error_code="API_ERROR",
600
+ operation="gmail.add_labels",
601
+ message=f"Gmail API error: {e.reason}",
602
+ )
603
+ raise SystemExit(ExitCode.API_ERROR)
604
+
605
+ def remove_labels(
606
+ self,
607
+ message_id: str,
608
+ label_ids: list[str],
609
+ ) -> dict[str, Any]:
610
+ """Remove labels from a message.
611
+
612
+ Args:
613
+ message_id: The message ID.
614
+ label_ids: List of label IDs to remove.
615
+ """
616
+ try:
617
+ result = self.execute(
618
+ self.service.users()
619
+ .messages()
620
+ .modify(
621
+ userId="me",
622
+ id=message_id,
623
+ body={"removeLabelIds": label_ids},
624
+ )
625
+ )
626
+
627
+ output_success(
628
+ operation="gmail.remove_labels",
629
+ message_id=message_id,
630
+ removed_labels=label_ids,
631
+ current_labels=result.get("labelIds", []),
632
+ )
633
+ return result
634
+ except HttpError as e:
635
+ output_error(
636
+ error_code="API_ERROR",
637
+ operation="gmail.remove_labels",
638
+ message=f"Gmail API error: {e.reason}",
639
+ )
640
+ raise SystemExit(ExitCode.API_ERROR)
641
+
642
+ # ===== Draft Operations =====
643
+
644
+ def list_drafts(self, max_results: int = 10) -> dict[str, Any]:
645
+ """List drafts in the mailbox.
646
+
647
+ Args:
648
+ max_results: Maximum number of drafts to return.
649
+ """
650
+ try:
651
+ result = self.execute(
652
+ self.service.users()
653
+ .drafts()
654
+ .list(userId="me", maxResults=max_results)
655
+ )
656
+
657
+ drafts = []
658
+ draft_refs = result.get("drafts", [])
659
+
660
+ if draft_refs:
661
+ batch_results: dict[str, Any] = {}
662
+
663
+ def handle_draft_response(request_id: str, response: Any, exception: Any) -> None:
664
+ if exception is None:
665
+ batch_results[request_id] = response
666
+
667
+ batch = self.service.new_batch_http_request(callback=handle_draft_response)
668
+ for draft_ref in draft_refs:
669
+ batch.add(
670
+ self.service.users()
671
+ .drafts()
672
+ .get(userId="me", id=draft_ref["id"], format="metadata"),
673
+ request_id=draft_ref["id"],
674
+ )
675
+ batch.execute()
676
+
677
+ for draft_ref in draft_refs:
678
+ draft = batch_results.get(draft_ref["id"])
679
+ if not draft:
680
+ continue
681
+
682
+ msg = draft.get("message", {})
683
+ headers = {
684
+ h["name"]: h["value"]
685
+ for h in msg.get("payload", {}).get("headers", [])
686
+ }
687
+
688
+ drafts.append({
689
+ "id": draft["id"],
690
+ "message_id": msg.get("id"),
691
+ "subject": headers.get("Subject", "(no subject)"),
692
+ "to": headers.get("To", ""),
693
+ "snippet": msg.get("snippet", "")[:100],
694
+ })
695
+
696
+ output_success(
697
+ operation="gmail.list_drafts",
698
+ draft_count=len(drafts),
699
+ drafts=drafts,
700
+ )
701
+ return result
702
+ except HttpError as e:
703
+ output_error(
704
+ error_code="API_ERROR",
705
+ operation="gmail.list_drafts",
706
+ message=f"Gmail API error: {e.reason}",
707
+ )
708
+ raise SystemExit(ExitCode.API_ERROR)
709
+
710
+ def get_draft(self, draft_id: str) -> dict[str, Any]:
711
+ """Get a draft by ID.
712
+
713
+ Args:
714
+ draft_id: The draft ID.
715
+ """
716
+ try:
717
+ draft = self.execute(
718
+ self.service.users()
719
+ .drafts()
720
+ .get(userId="me", id=draft_id, format="full")
721
+ )
722
+
723
+ msg = draft.get("message", {})
724
+ headers = {
725
+ h["name"]: h["value"]
726
+ for h in msg.get("payload", {}).get("headers", [])
727
+ }
728
+
729
+ body = self._extract_body(msg.get("payload", {}))
730
+
731
+ output_external_content(
732
+ operation="gmail.get_draft",
733
+ source_type="email",
734
+ source_id=draft["id"],
735
+ content_fields={
736
+ "subject": headers.get("Subject", "(no subject)"),
737
+ "body": body,
738
+ },
739
+ draft_id=draft["id"],
740
+ message_id=msg.get("id"),
741
+ to=headers.get("To", ""),
742
+ cc=headers.get("Cc", ""),
743
+ )
744
+ return draft
745
+ except HttpError as e:
746
+ output_error(
747
+ error_code="API_ERROR",
748
+ operation="gmail.get_draft",
749
+ message=f"Gmail API error: {e.reason}",
750
+ )
751
+ raise SystemExit(ExitCode.API_ERROR)
752
+
753
+ def create_draft(
754
+ self,
755
+ to: str,
756
+ subject: str,
757
+ body: str,
758
+ cc: str | None = None,
759
+ bcc: str | None = None,
760
+ html: bool = False,
761
+ ) -> dict[str, Any]:
762
+ """Create a new draft.
763
+
764
+ Args:
765
+ to: Recipient email address.
766
+ subject: Email subject.
767
+ body: Email body content.
768
+ cc: CC recipients.
769
+ bcc: BCC recipients.
770
+ html: If True, body is HTML.
771
+ """
772
+ try:
773
+ # Unescape shell-escaped characters
774
+ subject = self._unescape_text(subject)
775
+ body = self._unescape_text(body)
776
+
777
+ subtype = "html" if html else "plain"
778
+ message = MIMEText(body, subtype, "utf-8")
779
+
780
+ message["to"] = to
781
+ message["subject"] = subject
782
+
783
+ if cc:
784
+ message["cc"] = cc
785
+ if bcc:
786
+ message["bcc"] = bcc
787
+
788
+ raw = base64.urlsafe_b64encode(message.as_bytes()).decode("utf-8")
789
+
790
+ result = self.execute(
791
+ self.service.users()
792
+ .drafts()
793
+ .create(userId="me", body={"message": {"raw": raw}})
794
+ )
795
+
796
+ output_success(
797
+ operation="gmail.create_draft",
798
+ draft_id=result["id"],
799
+ to=to,
800
+ subject=subject,
801
+ )
802
+ return result
803
+ except HttpError as e:
804
+ output_error(
805
+ error_code="API_ERROR",
806
+ operation="gmail.create_draft",
807
+ message=f"Gmail API error: {e.reason}",
808
+ )
809
+ raise SystemExit(ExitCode.API_ERROR)
810
+
811
+ def update_draft(
812
+ self,
813
+ draft_id: str,
814
+ to: str | None = None,
815
+ subject: str | None = None,
816
+ body: str | None = None,
817
+ cc: str | None = None,
818
+ bcc: str | None = None,
819
+ html: bool = False,
820
+ ) -> dict[str, Any]:
821
+ """Update an existing draft.
822
+
823
+ Args:
824
+ draft_id: The draft ID to update.
825
+ to: New recipient (optional).
826
+ subject: New subject (optional).
827
+ body: New body content (optional).
828
+ cc: New CC recipients (optional).
829
+ bcc: New BCC recipients (optional).
830
+ html: If True, body is HTML.
831
+ """
832
+ try:
833
+ # Get current draft to preserve values
834
+ current_draft = self.execute(
835
+ self.service.users()
836
+ .drafts()
837
+ .get(userId="me", id=draft_id, format="full")
838
+ )
839
+
840
+ current_msg = current_draft.get("message", {})
841
+ current_headers = {
842
+ h["name"]: h["value"]
843
+ for h in current_msg.get("payload", {}).get("headers", [])
844
+ }
845
+ current_body = self._extract_body(current_msg.get("payload", {}))
846
+
847
+ # Use new values or preserve existing
848
+ final_to = to if to is not None else current_headers.get("To", "")
849
+ final_subject = subject if subject is not None else current_headers.get("Subject", "")
850
+ final_body = body if body is not None else current_body
851
+ final_cc = cc if cc is not None else current_headers.get("Cc")
852
+ final_bcc = bcc if bcc is not None else current_headers.get("Bcc")
853
+
854
+ # Unescape shell-escaped characters
855
+ final_subject = self._unescape_text(final_subject)
856
+ final_body = self._unescape_text(final_body)
857
+
858
+ subtype = "html" if html else "plain"
859
+ message = MIMEText(final_body, subtype, "utf-8")
860
+
861
+ message["to"] = final_to
862
+ message["subject"] = final_subject
863
+
864
+ if final_cc:
865
+ message["cc"] = final_cc
866
+ if final_bcc:
867
+ message["bcc"] = final_bcc
868
+
869
+ raw = base64.urlsafe_b64encode(message.as_bytes()).decode("utf-8")
870
+
871
+ result = self.execute(
872
+ self.service.users()
873
+ .drafts()
874
+ .update(
875
+ userId="me",
876
+ id=draft_id,
877
+ body={"message": {"raw": raw}},
878
+ )
879
+ )
880
+
881
+ output_success(
882
+ operation="gmail.update_draft",
883
+ draft_id=result["id"],
884
+ to=final_to,
885
+ subject=final_subject,
886
+ )
887
+ return result
888
+ except HttpError as e:
889
+ output_error(
890
+ error_code="API_ERROR",
891
+ operation="gmail.update_draft",
892
+ message=f"Gmail API error: {e.reason}",
893
+ )
894
+ raise SystemExit(ExitCode.API_ERROR)
895
+
896
+ def send_draft(self, draft_id: str) -> dict[str, Any]:
897
+ """Send a draft.
898
+
899
+ Args:
900
+ draft_id: The draft ID to send.
901
+ """
902
+ try:
903
+ result = self.execute(
904
+ self.service.users()
905
+ .drafts()
906
+ .send(userId="me", body={"id": draft_id})
907
+ )
908
+
909
+ output_success(
910
+ operation="gmail.send_draft",
911
+ message_id=result["id"],
912
+ thread_id=result.get("threadId"),
913
+ )
914
+ return result
915
+ except HttpError as e:
916
+ output_error(
917
+ error_code="API_ERROR",
918
+ operation="gmail.send_draft",
919
+ message=f"Gmail API error: {e.reason}",
920
+ )
921
+ raise SystemExit(ExitCode.API_ERROR)
922
+
923
+ def delete_draft(self, draft_id: str) -> dict[str, Any]:
924
+ """Delete a draft.
925
+
926
+ Args:
927
+ draft_id: The draft ID to delete.
928
+ """
929
+ try:
930
+ self.execute(self.service.users().drafts().delete(userId="me", id=draft_id))
931
+
932
+ output_success(
933
+ operation="gmail.delete_draft",
934
+ draft_id=draft_id,
935
+ )
936
+ return {"deleted": True, "draft_id": draft_id}
937
+ except HttpError as e:
938
+ output_error(
939
+ error_code="API_ERROR",
940
+ operation="gmail.delete_draft",
941
+ message=f"Gmail API error: {e.reason}",
942
+ )
943
+ raise SystemExit(ExitCode.API_ERROR)
944
+
945
+ # ===== Attachment Operations =====
946
+
947
+ def send_with_attachment(
948
+ self,
949
+ to: str,
950
+ subject: str,
951
+ body: str,
952
+ attachment_paths: list[str],
953
+ cc: str | None = None,
954
+ bcc: str | None = None,
955
+ html: bool = False,
956
+ from_name: str | None = None,
957
+ ) -> dict[str, Any]:
958
+ """Send an email with file attachments.
959
+
960
+ Args:
961
+ to: Recipient email address.
962
+ subject: Email subject.
963
+ body: Email body content.
964
+ attachment_paths: List of file paths to attach.
965
+ cc: CC recipients.
966
+ bcc: BCC recipients.
967
+ html: If True, body is HTML.
968
+ from_name: Sender display name.
969
+ """
970
+ try:
971
+ # Unescape shell-escaped characters
972
+ subject = self._unescape_text(subject)
973
+ body = self._unescape_text(body)
974
+
975
+ # Create multipart message for attachments
976
+ message = MIMEMultipart()
977
+ message["to"] = to
978
+ message["subject"] = subject
979
+
980
+ # Set From with display name (explicit > account config)
981
+ effective_name = from_name or self.auth_manager.config.get_account_display_name(
982
+ self.auth_manager.account_name
983
+ )
984
+ if effective_name:
985
+ profile = self.get_profile()
986
+ email_address = profile.get("emailAddress", "")
987
+ if email_address:
988
+ message["from"] = f'"{effective_name}" <{email_address}>'
989
+
990
+ if cc:
991
+ message["cc"] = cc
992
+ if bcc:
993
+ message["bcc"] = bcc
994
+
995
+ # Add body
996
+ subtype = "html" if html else "plain"
997
+ message.attach(MIMEText(body, subtype, "utf-8"))
998
+
999
+ # Add attachments
1000
+ attached_files = []
1001
+ for file_path in attachment_paths:
1002
+ if not os.path.isfile(file_path):
1003
+ output_error(
1004
+ error_code="NOT_FOUND",
1005
+ operation="gmail.send_with_attachment",
1006
+ message=f"File not found: {file_path}",
1007
+ )
1008
+ raise SystemExit(ExitCode.NOT_FOUND)
1009
+
1010
+ # Guess MIME type
1011
+ content_type, _ = mimetypes.guess_type(file_path)
1012
+ if content_type is None:
1013
+ content_type = "application/octet-stream"
1014
+
1015
+ main_type, sub_type = content_type.split("/", 1)
1016
+
1017
+ with open(file_path, "rb") as f:
1018
+ attachment = MIMEBase(main_type, sub_type)
1019
+ attachment.set_payload(f.read())
1020
+
1021
+ encoders.encode_base64(attachment)
1022
+ filename = os.path.basename(file_path)
1023
+ attachment.add_header(
1024
+ "Content-Disposition",
1025
+ "attachment",
1026
+ filename=filename,
1027
+ )
1028
+ message.attach(attachment)
1029
+ attached_files.append(filename)
1030
+
1031
+ raw = base64.urlsafe_b64encode(message.as_bytes()).decode("utf-8")
1032
+
1033
+ result = self.execute(
1034
+ self.service.users()
1035
+ .messages()
1036
+ .send(userId="me", body={"raw": raw})
1037
+ )
1038
+
1039
+ output_success(
1040
+ operation="gmail.send_with_attachment",
1041
+ message_id=result["id"],
1042
+ thread_id=result["threadId"],
1043
+ to=to,
1044
+ subject=subject,
1045
+ attachments=attached_files,
1046
+ )
1047
+ return result
1048
+ except HttpError as e:
1049
+ output_error(
1050
+ error_code="API_ERROR",
1051
+ operation="gmail.send_with_attachment",
1052
+ message=f"Gmail API error: {e.reason}",
1053
+ )
1054
+ raise SystemExit(ExitCode.API_ERROR)
1055
+
1056
+ def list_attachments(self, message_id: str) -> dict[str, Any]:
1057
+ """List attachments in a message.
1058
+
1059
+ Args:
1060
+ message_id: The message ID.
1061
+ """
1062
+ try:
1063
+ msg = self.execute(
1064
+ self.service.users()
1065
+ .messages()
1066
+ .get(userId="me", id=message_id, format="full")
1067
+ )
1068
+
1069
+ attachments = self._extract_attachments(msg.get("payload", {}))
1070
+
1071
+ output_success(
1072
+ operation="gmail.list_attachments",
1073
+ message_id=message_id,
1074
+ attachment_count=len(attachments),
1075
+ attachments=attachments,
1076
+ )
1077
+ return {"message_id": message_id, "attachments": attachments}
1078
+ except HttpError as e:
1079
+ output_error(
1080
+ error_code="API_ERROR",
1081
+ operation="gmail.list_attachments",
1082
+ message=f"Gmail API error: {e.reason}",
1083
+ )
1084
+ raise SystemExit(ExitCode.API_ERROR)
1085
+
1086
+ def download_attachment(
1087
+ self,
1088
+ message_id: str,
1089
+ attachment_id: str,
1090
+ output_path: str,
1091
+ ) -> dict[str, Any]:
1092
+ """Download an attachment to a file.
1093
+
1094
+ Args:
1095
+ message_id: The message ID containing the attachment.
1096
+ attachment_id: The attachment ID.
1097
+ output_path: Path to save the downloaded file.
1098
+ """
1099
+ try:
1100
+ attachment = self.execute(
1101
+ self.service.users()
1102
+ .messages()
1103
+ .attachments()
1104
+ .get(userId="me", messageId=message_id, id=attachment_id)
1105
+ )
1106
+
1107
+ # Decode base64 data
1108
+ data = attachment.get("data", "")
1109
+ file_data = base64.urlsafe_b64decode(data)
1110
+
1111
+ # Write to file
1112
+ with open(output_path, "wb") as f:
1113
+ f.write(file_data)
1114
+
1115
+ output_success(
1116
+ operation="gmail.download_attachment",
1117
+ message_id=message_id,
1118
+ attachment_id=attachment_id,
1119
+ output_path=output_path,
1120
+ size=len(file_data),
1121
+ )
1122
+ return {"output_path": output_path, "size": len(file_data)}
1123
+ except HttpError as e:
1124
+ output_error(
1125
+ error_code="API_ERROR",
1126
+ operation="gmail.download_attachment",
1127
+ message=f"Gmail API error: {e.reason}",
1128
+ )
1129
+ raise SystemExit(ExitCode.API_ERROR)
1130
+
1131
+ # =========================================================================
1132
+ # THREAD OPERATIONS
1133
+ # =========================================================================
1134
+
1135
+ def list_threads(
1136
+ self,
1137
+ query: str | None = None,
1138
+ max_results: int = 10,
1139
+ label_ids: list[str] | None = None,
1140
+ ) -> dict[str, Any]:
1141
+ """List email threads.
1142
+
1143
+ Args:
1144
+ query: Gmail search query (same syntax as search_messages).
1145
+ max_results: Maximum number of threads to return.
1146
+ label_ids: List of label IDs to filter by.
1147
+ """
1148
+ try:
1149
+ params: dict[str, Any] = {
1150
+ "userId": "me",
1151
+ "maxResults": max_results,
1152
+ }
1153
+ if query:
1154
+ params["q"] = query
1155
+ if label_ids:
1156
+ params["labelIds"] = label_ids
1157
+
1158
+ result = self.execute(self.service.users().threads().list(**params))
1159
+
1160
+ threads = []
1161
+ for thread in result.get("threads", []):
1162
+ thread_id = thread.get("id")
1163
+ snippet = thread.get("snippet", "")
1164
+ threads.append({
1165
+ "thread_id": thread_id,
1166
+ "snippet": snippet[:100] + "..." if len(snippet) > 100 else snippet,
1167
+ })
1168
+
1169
+ output_success(
1170
+ operation="gmail.list_threads",
1171
+ thread_count=len(threads),
1172
+ threads=threads,
1173
+ )
1174
+ return {"threads": threads}
1175
+ except HttpError as e:
1176
+ output_error(
1177
+ error_code="API_ERROR",
1178
+ operation="gmail.list_threads",
1179
+ message=f"Gmail API error: {e.reason}",
1180
+ )
1181
+ raise SystemExit(ExitCode.API_ERROR)
1182
+
1183
+ def get_thread(
1184
+ self,
1185
+ thread_id: str,
1186
+ format_type: str = "metadata",
1187
+ ) -> dict[str, Any]:
1188
+ """Get a thread with all its messages.
1189
+
1190
+ Args:
1191
+ thread_id: The thread ID.
1192
+ format_type: Message format (full, metadata, minimal).
1193
+ """
1194
+ try:
1195
+ thread = self.execute(
1196
+ self.service.users()
1197
+ .threads()
1198
+ .get(userId="me", id=thread_id, format=format_type)
1199
+ )
1200
+
1201
+ messages = []
1202
+ for msg in thread.get("messages", []):
1203
+ msg_info = {
1204
+ "message_id": msg.get("id"),
1205
+ "snippet": msg.get("snippet", "")[:100],
1206
+ }
1207
+
1208
+ # Extract headers if available
1209
+ headers = msg.get("payload", {}).get("headers", [])
1210
+ for header in headers:
1211
+ name = header.get("name", "").lower()
1212
+ if name in ("from", "to", "subject", "date"):
1213
+ msg_info[name] = header.get("value", "")
1214
+
1215
+ messages.append(msg_info)
1216
+
1217
+ output_success(
1218
+ operation="gmail.get_thread",
1219
+ thread_id=thread_id,
1220
+ message_count=len(messages),
1221
+ messages=messages,
1222
+ )
1223
+ return {"thread_id": thread_id, "messages": messages}
1224
+ except HttpError as e:
1225
+ output_error(
1226
+ error_code="API_ERROR",
1227
+ operation="gmail.get_thread",
1228
+ message=f"Gmail API error: {e.reason}",
1229
+ )
1230
+ raise SystemExit(ExitCode.API_ERROR)
1231
+
1232
+ def trash_thread(self, thread_id: str) -> dict[str, Any]:
1233
+ """Move a thread to trash.
1234
+
1235
+ Args:
1236
+ thread_id: The thread ID.
1237
+ """
1238
+ try:
1239
+ self.execute(self.service.users().threads().trash(userId="me", id=thread_id))
1240
+
1241
+ output_success(
1242
+ operation="gmail.trash_thread",
1243
+ thread_id=thread_id,
1244
+ )
1245
+ return {"thread_id": thread_id, "status": "trashed"}
1246
+ except HttpError as e:
1247
+ output_error(
1248
+ error_code="API_ERROR",
1249
+ operation="gmail.trash_thread",
1250
+ message=f"Gmail API error: {e.reason}",
1251
+ )
1252
+ raise SystemExit(ExitCode.API_ERROR)
1253
+
1254
+ def untrash_thread(self, thread_id: str) -> dict[str, Any]:
1255
+ """Remove a thread from trash.
1256
+
1257
+ Args:
1258
+ thread_id: The thread ID.
1259
+ """
1260
+ try:
1261
+ self.execute(self.service.users().threads().untrash(userId="me", id=thread_id))
1262
+
1263
+ output_success(
1264
+ operation="gmail.untrash_thread",
1265
+ thread_id=thread_id,
1266
+ )
1267
+ return {"thread_id": thread_id, "status": "untrashed"}
1268
+ except HttpError as e:
1269
+ output_error(
1270
+ error_code="API_ERROR",
1271
+ operation="gmail.untrash_thread",
1272
+ message=f"Gmail API error: {e.reason}",
1273
+ )
1274
+ raise SystemExit(ExitCode.API_ERROR)
1275
+
1276
+ def modify_thread_labels(
1277
+ self,
1278
+ thread_id: str,
1279
+ add_label_ids: list[str] | None = None,
1280
+ remove_label_ids: list[str] | None = None,
1281
+ ) -> dict[str, Any]:
1282
+ """Add or remove labels from all messages in a thread.
1283
+
1284
+ Args:
1285
+ thread_id: The thread ID.
1286
+ add_label_ids: Label IDs to add.
1287
+ remove_label_ids: Label IDs to remove.
1288
+ """
1289
+ try:
1290
+ body: dict[str, Any] = {}
1291
+ if add_label_ids:
1292
+ body["addLabelIds"] = add_label_ids
1293
+ if remove_label_ids:
1294
+ body["removeLabelIds"] = remove_label_ids
1295
+
1296
+ if not body:
1297
+ output_error(
1298
+ error_code="INVALID_ARGS",
1299
+ operation="gmail.modify_thread_labels",
1300
+ message="Must specify labels to add or remove",
1301
+ )
1302
+ raise SystemExit(ExitCode.INVALID_ARGS)
1303
+
1304
+ self.execute(self.service.users().threads().modify(
1305
+ userId="me", id=thread_id, body=body
1306
+ ))
1307
+
1308
+ output_success(
1309
+ operation="gmail.modify_thread_labels",
1310
+ thread_id=thread_id,
1311
+ added_labels=add_label_ids or [],
1312
+ removed_labels=remove_label_ids or [],
1313
+ )
1314
+ return {"thread_id": thread_id}
1315
+ except HttpError as e:
1316
+ output_error(
1317
+ error_code="API_ERROR",
1318
+ operation="gmail.modify_thread_labels",
1319
+ message=f"Gmail API error: {e.reason}",
1320
+ )
1321
+ raise SystemExit(ExitCode.API_ERROR)
1322
+
1323
+ # =========================================================================
1324
+ # SETTINGS
1325
+ # =========================================================================
1326
+
1327
+ def get_vacation_settings(self) -> dict[str, Any]:
1328
+ """Get vacation responder settings."""
1329
+ try:
1330
+ settings = self.execute(
1331
+ self.service.users()
1332
+ .settings()
1333
+ .getVacation(userId="me")
1334
+ )
1335
+
1336
+ output_success(
1337
+ operation="gmail.get_vacation_settings",
1338
+ enabled=settings.get("enableAutoReply", False),
1339
+ subject=settings.get("responseSubject", ""),
1340
+ body_plain_text=settings.get("responseBodyPlainText", ""),
1341
+ restrict_to_contacts=settings.get("restrictToContacts", False),
1342
+ restrict_to_domain=settings.get("restrictToDomain", False),
1343
+ start_time=settings.get("startTime"),
1344
+ end_time=settings.get("endTime"),
1345
+ )
1346
+ return settings
1347
+ except HttpError as e:
1348
+ output_error(
1349
+ error_code="API_ERROR",
1350
+ operation="gmail.get_vacation_settings",
1351
+ message=f"Gmail API error: {e.reason}",
1352
+ )
1353
+ raise SystemExit(ExitCode.API_ERROR)
1354
+
1355
+ def set_vacation_settings(
1356
+ self,
1357
+ enable: bool,
1358
+ subject: str | None = None,
1359
+ message: str | None = None,
1360
+ html_message: str | None = None,
1361
+ start_time: int | None = None,
1362
+ end_time: int | None = None,
1363
+ restrict_to_contacts: bool = False,
1364
+ restrict_to_domain: bool = False,
1365
+ ) -> dict[str, Any]:
1366
+ """Set vacation responder settings.
1367
+
1368
+ Args:
1369
+ enable: Whether to enable the vacation responder.
1370
+ subject: Response subject line.
1371
+ message: Plain text response message.
1372
+ html_message: HTML response message.
1373
+ start_time: Start time (Unix timestamp in milliseconds).
1374
+ end_time: End time (Unix timestamp in milliseconds).
1375
+ restrict_to_contacts: Only respond to contacts.
1376
+ restrict_to_domain: Only respond to same domain.
1377
+ """
1378
+ try:
1379
+ body: dict[str, Any] = {
1380
+ "enableAutoReply": enable,
1381
+ "restrictToContacts": restrict_to_contacts,
1382
+ "restrictToDomain": restrict_to_domain,
1383
+ }
1384
+
1385
+ if subject:
1386
+ body["responseSubject"] = subject
1387
+ if message:
1388
+ body["responseBodyPlainText"] = message
1389
+ if html_message:
1390
+ body["responseBodyHtml"] = html_message
1391
+ if start_time:
1392
+ body["startTime"] = start_time
1393
+ if end_time:
1394
+ body["endTime"] = end_time
1395
+
1396
+ result = self.execute(
1397
+ self.service.users()
1398
+ .settings()
1399
+ .updateVacation(userId="me", body=body)
1400
+ )
1401
+
1402
+ output_success(
1403
+ operation="gmail.set_vacation_settings",
1404
+ enabled=enable,
1405
+ subject=subject,
1406
+ )
1407
+ return result
1408
+ except HttpError as e:
1409
+ output_error(
1410
+ error_code="API_ERROR",
1411
+ operation="gmail.set_vacation_settings",
1412
+ message=f"Gmail API error: {e.reason}",
1413
+ )
1414
+ raise SystemExit(ExitCode.API_ERROR)
1415
+
1416
+ def get_signature(self, send_as_email: str | None = None) -> dict[str, Any]:
1417
+ """Get email signature.
1418
+
1419
+ Args:
1420
+ send_as_email: Email address of the send-as alias (default: primary).
1421
+ """
1422
+ try:
1423
+ # Get primary email if not specified
1424
+ if not send_as_email:
1425
+ profile = self.execute(self.service.users().getProfile(userId="me"))
1426
+ send_as_email = profile.get("emailAddress", "")
1427
+
1428
+ result = self.execute(
1429
+ self.service.users()
1430
+ .settings()
1431
+ .sendAs()
1432
+ .get(userId="me", sendAsEmail=send_as_email)
1433
+ )
1434
+
1435
+ output_success(
1436
+ operation="gmail.get_signature",
1437
+ send_as_email=send_as_email,
1438
+ signature=result.get("signature", ""),
1439
+ display_name=result.get("displayName", ""),
1440
+ is_primary=result.get("isPrimary", False),
1441
+ )
1442
+ return result
1443
+ except HttpError as e:
1444
+ output_error(
1445
+ error_code="API_ERROR",
1446
+ operation="gmail.get_signature",
1447
+ message=f"Gmail API error: {e.reason}",
1448
+ )
1449
+ raise SystemExit(ExitCode.API_ERROR)
1450
+
1451
+ def set_signature(
1452
+ self,
1453
+ signature: str,
1454
+ send_as_email: str | None = None,
1455
+ ) -> dict[str, Any]:
1456
+ """Set email signature.
1457
+
1458
+ Args:
1459
+ signature: HTML signature content.
1460
+ send_as_email: Email address of the send-as alias (default: primary).
1461
+ """
1462
+ try:
1463
+ # Get primary email if not specified
1464
+ if not send_as_email:
1465
+ profile = self.execute(self.service.users().getProfile(userId="me"))
1466
+ send_as_email = profile.get("emailAddress", "")
1467
+
1468
+ result = self.execute(
1469
+ self.service.users()
1470
+ .settings()
1471
+ .sendAs()
1472
+ .patch(
1473
+ userId="me",
1474
+ sendAsEmail=send_as_email,
1475
+ body={"signature": signature}
1476
+ )
1477
+ )
1478
+
1479
+ output_success(
1480
+ operation="gmail.set_signature",
1481
+ send_as_email=send_as_email,
1482
+ signature_length=len(signature),
1483
+ )
1484
+ return result
1485
+ except HttpError as e:
1486
+ output_error(
1487
+ error_code="API_ERROR",
1488
+ operation="gmail.set_signature",
1489
+ message=f"Gmail API error: {e.reason}",
1490
+ )
1491
+ raise SystemExit(ExitCode.API_ERROR)
1492
+
1493
+ # ===== Filters =====
1494
+
1495
+ def list_filters(self) -> dict[str, Any]:
1496
+ """List all mail filters."""
1497
+ try:
1498
+ result = self.execute(
1499
+ self.service.users()
1500
+ .settings()
1501
+ .filters()
1502
+ .list(userId="me")
1503
+ )
1504
+
1505
+ filters = []
1506
+ for f in result.get("filter", []):
1507
+ criteria = f.get("criteria", {})
1508
+ action = f.get("action", {})
1509
+
1510
+ filters.append({
1511
+ "id": f.get("id"),
1512
+ "criteria": {
1513
+ "from": criteria.get("from"),
1514
+ "to": criteria.get("to"),
1515
+ "subject": criteria.get("subject"),
1516
+ "query": criteria.get("query"),
1517
+ "has_attachment": criteria.get("hasAttachment"),
1518
+ "size": criteria.get("size"),
1519
+ "size_comparison": criteria.get("sizeComparison"),
1520
+ },
1521
+ "action": {
1522
+ "add_label_ids": action.get("addLabelIds", []),
1523
+ "remove_label_ids": action.get("removeLabelIds", []),
1524
+ "forward": action.get("forward"),
1525
+ "star": action.get("star", False),
1526
+ "mark_important": action.get("markImportant", False),
1527
+ "archive": "INBOX" in action.get("removeLabelIds", []),
1528
+ "trash": "TRASH" in action.get("addLabelIds", []),
1529
+ "never_spam": "SPAM" in action.get("removeLabelIds", []),
1530
+ },
1531
+ })
1532
+
1533
+ output_success(
1534
+ operation="gmail.list_filters",
1535
+ filter_count=len(filters),
1536
+ filters=filters,
1537
+ )
1538
+ return result
1539
+ except HttpError as e:
1540
+ output_error(
1541
+ error_code="API_ERROR",
1542
+ operation="gmail.list_filters",
1543
+ message=f"Gmail API error: {e.reason}",
1544
+ )
1545
+ raise SystemExit(ExitCode.API_ERROR)
1546
+
1547
+ def get_filter(self, filter_id: str) -> dict[str, Any]:
1548
+ """Get a specific mail filter."""
1549
+ try:
1550
+ result = self.execute(
1551
+ self.service.users()
1552
+ .settings()
1553
+ .filters()
1554
+ .get(userId="me", id=filter_id)
1555
+ )
1556
+
1557
+ criteria = result.get("criteria", {})
1558
+ action = result.get("action", {})
1559
+
1560
+ output_success(
1561
+ operation="gmail.get_filter",
1562
+ filter_id=filter_id,
1563
+ criteria={
1564
+ "from": criteria.get("from"),
1565
+ "to": criteria.get("to"),
1566
+ "subject": criteria.get("subject"),
1567
+ "query": criteria.get("query"),
1568
+ "has_attachment": criteria.get("hasAttachment"),
1569
+ },
1570
+ action={
1571
+ "add_label_ids": action.get("addLabelIds", []),
1572
+ "remove_label_ids": action.get("removeLabelIds", []),
1573
+ "forward": action.get("forward"),
1574
+ "star": action.get("star", False),
1575
+ "mark_important": action.get("markImportant", False),
1576
+ },
1577
+ )
1578
+ return result
1579
+ except HttpError as e:
1580
+ if e.resp.status == 404:
1581
+ output_error(
1582
+ error_code="NOT_FOUND",
1583
+ operation="gmail.get_filter",
1584
+ message=f"Filter not found: {filter_id}",
1585
+ )
1586
+ raise SystemExit(ExitCode.NOT_FOUND)
1587
+ output_error(
1588
+ error_code="API_ERROR",
1589
+ operation="gmail.get_filter",
1590
+ message=f"Gmail API error: {e.reason}",
1591
+ )
1592
+ raise SystemExit(ExitCode.API_ERROR)
1593
+
1594
+ def create_filter(
1595
+ self,
1596
+ from_address: str | None = None,
1597
+ to_address: str | None = None,
1598
+ subject: str | None = None,
1599
+ query: str | None = None,
1600
+ has_attachment: bool | None = None,
1601
+ add_label_ids: list[str] | None = None,
1602
+ remove_label_ids: list[str] | None = None,
1603
+ archive: bool = False,
1604
+ star: bool = False,
1605
+ mark_important: bool | None = None,
1606
+ never_spam: bool = False,
1607
+ trash: bool = False,
1608
+ forward_to: str | None = None,
1609
+ ) -> dict[str, Any]:
1610
+ """Create a mail filter.
1611
+
1612
+ Args:
1613
+ from_address: Match messages from this address.
1614
+ to_address: Match messages to this address.
1615
+ subject: Match messages with this subject.
1616
+ query: Gmail search query to match.
1617
+ has_attachment: Match messages with attachments.
1618
+ add_label_ids: Label IDs to add to matching messages.
1619
+ remove_label_ids: Label IDs to remove from matching messages.
1620
+ archive: Skip inbox (archive) matching messages.
1621
+ star: Star matching messages.
1622
+ mark_important: Mark matching messages as important (True/False/None).
1623
+ never_spam: Never send matching messages to spam.
1624
+ trash: Delete matching messages.
1625
+ forward_to: Forward matching messages to this address.
1626
+ """
1627
+ try:
1628
+ # Build criteria
1629
+ criteria: dict[str, Any] = {}
1630
+ if from_address:
1631
+ criteria["from"] = from_address
1632
+ if to_address:
1633
+ criteria["to"] = to_address
1634
+ if subject:
1635
+ criteria["subject"] = subject
1636
+ if query:
1637
+ criteria["query"] = query
1638
+ if has_attachment is not None:
1639
+ criteria["hasAttachment"] = has_attachment
1640
+
1641
+ if not criteria:
1642
+ output_error(
1643
+ error_code="INVALID_ARGS",
1644
+ operation="gmail.create_filter",
1645
+ message="At least one filter criteria is required",
1646
+ )
1647
+ raise SystemExit(ExitCode.INVALID_ARGS)
1648
+
1649
+ # Build action
1650
+ action: dict[str, Any] = {}
1651
+ add_labels = list(add_label_ids) if add_label_ids else []
1652
+ remove_labels = list(remove_label_ids) if remove_label_ids else []
1653
+
1654
+ if archive:
1655
+ remove_labels.append("INBOX")
1656
+ if trash:
1657
+ add_labels.append("TRASH")
1658
+ if never_spam:
1659
+ remove_labels.append("SPAM")
1660
+
1661
+ if add_labels:
1662
+ action["addLabelIds"] = add_labels
1663
+ if remove_labels:
1664
+ action["removeLabelIds"] = remove_labels
1665
+ if star:
1666
+ action["star"] = True
1667
+ if mark_important is not None:
1668
+ action["markImportant"] = mark_important
1669
+ if forward_to:
1670
+ action["forward"] = forward_to
1671
+
1672
+ if not action:
1673
+ output_error(
1674
+ error_code="INVALID_ARGS",
1675
+ operation="gmail.create_filter",
1676
+ message="At least one filter action is required",
1677
+ )
1678
+ raise SystemExit(ExitCode.INVALID_ARGS)
1679
+
1680
+ body = {"criteria": criteria, "action": action}
1681
+
1682
+ result = self.execute(
1683
+ self.service.users()
1684
+ .settings()
1685
+ .filters()
1686
+ .create(userId="me", body=body)
1687
+ )
1688
+
1689
+ output_success(
1690
+ operation="gmail.create_filter",
1691
+ filter_id=result.get("id"),
1692
+ criteria=criteria,
1693
+ action=action,
1694
+ )
1695
+ return result
1696
+ except HttpError as e:
1697
+ output_error(
1698
+ error_code="API_ERROR",
1699
+ operation="gmail.create_filter",
1700
+ message=f"Gmail API error: {e.reason}",
1701
+ )
1702
+ raise SystemExit(ExitCode.API_ERROR)
1703
+
1704
+ def delete_filter(self, filter_id: str) -> dict[str, Any]:
1705
+ """Delete a mail filter."""
1706
+ try:
1707
+ self.execute(self.service.users().settings().filters().delete(
1708
+ userId="me", id=filter_id
1709
+ ))
1710
+
1711
+ output_success(
1712
+ operation="gmail.delete_filter",
1713
+ filter_id=filter_id,
1714
+ deleted=True,
1715
+ )
1716
+ return {"deleted": True, "filter_id": filter_id}
1717
+ except HttpError as e:
1718
+ if e.resp.status == 404:
1719
+ output_error(
1720
+ error_code="NOT_FOUND",
1721
+ operation="gmail.delete_filter",
1722
+ message=f"Filter not found: {filter_id}",
1723
+ )
1724
+ raise SystemExit(ExitCode.NOT_FOUND)
1725
+ output_error(
1726
+ error_code="API_ERROR",
1727
+ operation="gmail.delete_filter",
1728
+ message=f"Gmail API error: {e.reason}",
1729
+ )
1730
+ raise SystemExit(ExitCode.API_ERROR)
1731
+
1732
+ # =========================================================================
1733
+ # ADDITIONAL MESSAGE OPERATIONS
1734
+ # =========================================================================
1735
+
1736
+ def untrash_message(self, message_id: str) -> dict[str, Any]:
1737
+ """Remove a message from trash."""
1738
+ try:
1739
+ result = self.execute(
1740
+ self.service.users()
1741
+ .messages()
1742
+ .untrash(userId="me", id=message_id)
1743
+ )
1744
+
1745
+ output_success(
1746
+ operation="gmail.untrash_message",
1747
+ message_id=message_id,
1748
+ )
1749
+ return result
1750
+ except HttpError as e:
1751
+ if e.resp.status == 404:
1752
+ output_error(
1753
+ error_code="NOT_FOUND",
1754
+ operation="gmail.untrash_message",
1755
+ message=f"Message not found: {message_id}",
1756
+ )
1757
+ raise SystemExit(ExitCode.NOT_FOUND)
1758
+ output_error(
1759
+ error_code="API_ERROR",
1760
+ operation="gmail.untrash_message",
1761
+ message=f"Gmail API error: {e.reason}",
1762
+ )
1763
+ raise SystemExit(ExitCode.API_ERROR)
1764
+
1765
+ def batch_modify_messages(
1766
+ self,
1767
+ message_ids: list[str],
1768
+ add_label_ids: list[str] | None = None,
1769
+ remove_label_ids: list[str] | None = None,
1770
+ ) -> dict[str, Any]:
1771
+ """Modify labels on multiple messages at once.
1772
+
1773
+ Args:
1774
+ message_ids: List of message IDs to modify.
1775
+ add_label_ids: Labels to add to all messages.
1776
+ remove_label_ids: Labels to remove from all messages.
1777
+ """
1778
+ try:
1779
+ body: dict[str, Any] = {"ids": message_ids}
1780
+ if add_label_ids:
1781
+ body["addLabelIds"] = add_label_ids
1782
+ if remove_label_ids:
1783
+ body["removeLabelIds"] = remove_label_ids
1784
+
1785
+ self.execute(
1786
+ self.service.users()
1787
+ .messages()
1788
+ .batchModify(userId="me", body=body)
1789
+ )
1790
+
1791
+ output_success(
1792
+ operation="gmail.batch_modify",
1793
+ message_count=len(message_ids),
1794
+ add_label_ids=add_label_ids,
1795
+ remove_label_ids=remove_label_ids,
1796
+ )
1797
+ return {"modified": len(message_ids)}
1798
+ except HttpError as e:
1799
+ output_error(
1800
+ error_code="API_ERROR",
1801
+ operation="gmail.batch_modify",
1802
+ message=f"Gmail API error: {e.reason}",
1803
+ )
1804
+ raise SystemExit(ExitCode.API_ERROR)
1805
+
1806
+ # =========================================================================
1807
+ # LABEL OPERATIONS (extended)
1808
+ # =========================================================================
1809
+
1810
+ def get_label(self, label_id: str) -> dict[str, Any]:
1811
+ """Get details of a specific label."""
1812
+ try:
1813
+ result = self.execute(
1814
+ self.service.users()
1815
+ .labels()
1816
+ .get(userId="me", id=label_id)
1817
+ )
1818
+
1819
+ output_success(
1820
+ operation="gmail.get_label",
1821
+ label_id=label_id,
1822
+ name=result.get("name"),
1823
+ label_type=result.get("type"),
1824
+ message_list_visibility=result.get("messageListVisibility"),
1825
+ label_list_visibility=result.get("labelListVisibility"),
1826
+ messages_total=result.get("messagesTotal"),
1827
+ messages_unread=result.get("messagesUnread"),
1828
+ threads_total=result.get("threadsTotal"),
1829
+ threads_unread=result.get("threadsUnread"),
1830
+ )
1831
+ return result
1832
+ except HttpError as e:
1833
+ if e.resp.status == 404:
1834
+ output_error(
1835
+ error_code="NOT_FOUND",
1836
+ operation="gmail.get_label",
1837
+ message=f"Label not found: {label_id}",
1838
+ )
1839
+ raise SystemExit(ExitCode.NOT_FOUND)
1840
+ output_error(
1841
+ error_code="API_ERROR",
1842
+ operation="gmail.get_label",
1843
+ message=f"Gmail API error: {e.reason}",
1844
+ )
1845
+ raise SystemExit(ExitCode.API_ERROR)
1846
+
1847
+ def update_label(
1848
+ self,
1849
+ label_id: str,
1850
+ name: str | None = None,
1851
+ message_list_visibility: str | None = None,
1852
+ label_list_visibility: str | None = None,
1853
+ text_color: str | None = None,
1854
+ background_color: str | None = None,
1855
+ ) -> dict[str, Any]:
1856
+ """Update a label's properties.
1857
+
1858
+ Args:
1859
+ label_id: The label ID to update.
1860
+ name: New label name.
1861
+ message_list_visibility: 'show' or 'hide' in message list.
1862
+ label_list_visibility: 'labelShow', 'labelShowIfUnread', or 'labelHide'.
1863
+ text_color: Text color (hex, e.g., '#000000').
1864
+ background_color: Background color (hex, e.g., '#ffffff').
1865
+ """
1866
+ try:
1867
+ body: dict[str, Any] = {}
1868
+
1869
+ if name is not None:
1870
+ body["name"] = name
1871
+ if message_list_visibility is not None:
1872
+ body["messageListVisibility"] = message_list_visibility
1873
+ if label_list_visibility is not None:
1874
+ body["labelListVisibility"] = label_list_visibility
1875
+ if text_color is not None or background_color is not None:
1876
+ body["color"] = {}
1877
+ if text_color:
1878
+ body["color"]["textColor"] = text_color
1879
+ if background_color:
1880
+ body["color"]["backgroundColor"] = background_color
1881
+
1882
+ if not body:
1883
+ output_error(
1884
+ error_code="INVALID_ARGUMENT",
1885
+ operation="gmail.update_label",
1886
+ message="At least one update field required",
1887
+ )
1888
+ raise SystemExit(ExitCode.INVALID_ARGS)
1889
+
1890
+ result = self.execute(
1891
+ self.service.users()
1892
+ .labels()
1893
+ .patch(userId="me", id=label_id, body=body)
1894
+ )
1895
+
1896
+ output_success(
1897
+ operation="gmail.update_label",
1898
+ label_id=label_id,
1899
+ name=result.get("name"),
1900
+ )
1901
+ return result
1902
+ except HttpError as e:
1903
+ if e.resp.status == 404:
1904
+ output_error(
1905
+ error_code="NOT_FOUND",
1906
+ operation="gmail.update_label",
1907
+ message=f"Label not found: {label_id}",
1908
+ )
1909
+ raise SystemExit(ExitCode.NOT_FOUND)
1910
+ output_error(
1911
+ error_code="API_ERROR",
1912
+ operation="gmail.update_label",
1913
+ message=f"Gmail API error: {e.reason}",
1914
+ )
1915
+ raise SystemExit(ExitCode.API_ERROR)
1916
+
1917
+ # =========================================================================
1918
+ # THREAD OPERATIONS (extended)
1919
+ # =========================================================================
1920
+
1921
+ def delete_thread(self, thread_id: str) -> dict[str, Any]:
1922
+ """Permanently delete a thread (cannot be undone)."""
1923
+ try:
1924
+ self.execute(
1925
+ self.service.users()
1926
+ .threads()
1927
+ .delete(userId="me", id=thread_id)
1928
+ )
1929
+
1930
+ output_success(
1931
+ operation="gmail.delete_thread",
1932
+ thread_id=thread_id,
1933
+ deleted=True,
1934
+ )
1935
+ return {"deleted": True, "thread_id": thread_id}
1936
+ except HttpError as e:
1937
+ if e.resp.status == 404:
1938
+ output_error(
1939
+ error_code="NOT_FOUND",
1940
+ operation="gmail.delete_thread",
1941
+ message=f"Thread not found: {thread_id}",
1942
+ )
1943
+ raise SystemExit(ExitCode.NOT_FOUND)
1944
+ output_error(
1945
+ error_code="API_ERROR",
1946
+ operation="gmail.delete_thread",
1947
+ message=f"Gmail API error: {e.reason}",
1948
+ )
1949
+ raise SystemExit(ExitCode.API_ERROR)
1950
+
1951
+ # =========================================================================
1952
+ # HISTORY
1953
+ # =========================================================================
1954
+
1955
+ def list_history(
1956
+ self,
1957
+ start_history_id: str,
1958
+ max_results: int = 100,
1959
+ history_types: list[str] | None = None,
1960
+ label_id: str | None = None,
1961
+ ) -> dict[str, Any]:
1962
+ """List changes to the mailbox since a given history ID.
1963
+
1964
+ Args:
1965
+ start_history_id: History ID to start from (from a previous sync).
1966
+ max_results: Maximum number of history records to return.
1967
+ history_types: Types to filter (messageAdded, messageDeleted, labelAdded, labelRemoved).
1968
+ label_id: Only return changes to messages with this label.
1969
+ """
1970
+ try:
1971
+ params: dict[str, Any] = {
1972
+ "userId": "me",
1973
+ "startHistoryId": start_history_id,
1974
+ "maxResults": max_results,
1975
+ }
1976
+ if history_types:
1977
+ params["historyTypes"] = history_types
1978
+ if label_id:
1979
+ params["labelId"] = label_id
1980
+
1981
+ result = self.execute(
1982
+ self.service.users()
1983
+ .history()
1984
+ .list(**params)
1985
+ )
1986
+
1987
+ history_records = result.get("history", [])
1988
+ output_success(
1989
+ operation="gmail.list_history",
1990
+ history_count=len(history_records),
1991
+ history_id=result.get("historyId"),
1992
+ next_page_token=result.get("nextPageToken"),
1993
+ )
1994
+ return result
1995
+ except HttpError as e:
1996
+ output_error(
1997
+ error_code="API_ERROR",
1998
+ operation="gmail.list_history",
1999
+ message=f"Gmail API error: {e.reason}",
2000
+ )
2001
+ raise SystemExit(ExitCode.API_ERROR)