-
Notifications
You must be signed in to change notification settings - Fork 70
Expand file tree
/
Copy pathclassic.py
More file actions
1008 lines (869 loc) · 39.5 KB
/
classic.py
File metadata and controls
1008 lines (869 loc) · 39.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import email.utils
import mimetypes
from collections.abc import AsyncGenerator
from datetime import datetime, timezone
from email.header import Header
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.parser import BytesParser
from email.policy import default
from pathlib import Path
from typing import Any
import aioimaplib
import aiosmtplib
import justhtml
from mcp_email_server.config import EmailServer, EmailSettings
from mcp_email_server.emails import EmailHandler
from mcp_email_server.emails.models import (
AttachmentDownloadResponse,
EmailBodyResponse,
EmailContentBatchResponse,
EmailMetadata,
EmailMetadataPageResponse,
)
from mcp_email_server.log import logger
def _quote_mailbox(mailbox: str) -> str:
"""Quote mailbox name for IMAP compatibility.
Some IMAP servers (notably Proton Mail Bridge) require mailbox names
to be quoted. This is valid per RFC 3501 and works with all IMAP servers.
Per RFC 3501 Section 9 (Formal Syntax), quoted strings must escape
backslashes and double-quote characters with a preceding backslash.
See: https://github.com/ai-zerolab/mcp-email-server/issues/87
See: https://www.rfc-editor.org/rfc/rfc3501#section-9
"""
# Per RFC 3501, literal double-quote characters in a quoted string must
# be escaped with a backslash. Backslashes themselves must also be escaped.
escaped = mailbox.replace("\\", "\\\\").replace('"', r"\"")
return f'"{escaped}"'
async def _send_imap_id(imap: aioimaplib.IMAP4 | aioimaplib.IMAP4_SSL) -> None:
"""Send IMAP ID command with fallback for strict servers like 163.com.
aioimaplib's id() method sends ID command with spaces between parentheses
and content (e.g., 'ID ( "name" "value" )'), which some strict IMAP servers
like 163.com reject with 'BAD Parse command error'.
This function first tries the standard id() method, and if it fails,
falls back to sending a raw command with correct format.
See: https://github.com/ai-zerolab/mcp-email-server/issues/85
"""
try:
response = await imap.id(name="mcp-email-server", version="1.0.0")
if response.result != "OK":
# Fallback for strict servers (e.g., 163.com)
# Send raw command with correct parenthesis format
await imap.protocol.execute(
aioimaplib.Command(
"ID",
imap.protocol.new_tag(),
'("name" "mcp-email-server" "version" "1.0.0")',
)
)
except Exception as e:
logger.warning(f"IMAP ID command failed: {e!s}")
def _format_body_content(body: str, html_body: str, content_format: str) -> str:
"""Format email body content based on the requested format.
Args:
body: Plain text body content.
html_body: HTML body content.
content_format: One of "raw", "html", "text", "markdown".
Returns:
Formatted body content.
"""
if content_format == "raw":
# Return plain text if available, else HTML
return body if body else html_body
if content_format == "html":
# Return HTML content, fall back to plain text if no HTML
return html_body if html_body else body
if content_format == "text":
# Convert HTML to clean text, or return plain text
if html_body:
return justhtml.JustHTML(html_body).to_text()
return body
if content_format == "markdown":
# Convert HTML to markdown
if html_body:
return justhtml.JustHTML(html_body).to_markdown()
return body
# Unknown format, return raw
logger.warning(f"Unknown content_format: {content_format}, returning raw content")
return body if body else html_body
class EmailClient:
def __init__(self, email_server: EmailServer, sender: str | None = None):
self.email_server = email_server
self.sender = sender or email_server.user_name
self.imap_class = aioimaplib.IMAP4_SSL if self.email_server.use_ssl else aioimaplib.IMAP4
self.smtp_use_tls = self.email_server.use_ssl
self.smtp_start_tls = self.email_server.start_ssl
def _parse_email_data(self, raw_email: bytes, email_id: str | None = None) -> dict[str, Any]: # noqa: C901
"""Parse raw email data into a structured dictionary."""
parser = BytesParser(policy=default)
email_message = parser.parsebytes(raw_email)
# Extract email parts
subject = email_message.get("Subject", "")
sender = email_message.get("From", "")
date_str = email_message.get("Date", "")
# Extract Message-ID for reply threading
message_id = email_message.get("Message-ID")
# Extract recipients
to_addresses = []
to_header = email_message.get("To", "")
if to_header:
# Simple parsing - split by comma and strip whitespace
to_addresses = [addr.strip() for addr in to_header.split(",")]
# Also check CC recipients
cc_header = email_message.get("Cc", "")
if cc_header:
to_addresses.extend([addr.strip() for addr in cc_header.split(",")])
# Parse date
try:
date_tuple = email.utils.parsedate_tz(date_str)
date = (
datetime.fromtimestamp(email.utils.mktime_tz(date_tuple), tz=timezone.utc)
if date_tuple
else datetime.now(timezone.utc)
)
except Exception:
date = datetime.now(timezone.utc)
# Get body content - extract both plain text and HTML
body = ""
html_body = ""
attachments = []
if email_message.is_multipart():
for part in email_message.walk():
content_type = part.get_content_type()
content_disposition = str(part.get("Content-Disposition", ""))
# Handle attachments
if "attachment" in content_disposition:
filename = part.get_filename()
if filename:
attachments.append(filename)
# Handle text parts
elif content_type == "text/plain":
body_part = part.get_payload(decode=True)
if body_part:
charset = part.get_content_charset("utf-8")
try:
body += body_part.decode(charset)
except UnicodeDecodeError:
body += body_part.decode("utf-8", errors="replace")
elif content_type == "text/html":
html_part = part.get_payload(decode=True)
if html_part:
charset = part.get_content_charset("utf-8")
try:
html_body += html_part.decode(charset)
except UnicodeDecodeError:
html_body += html_part.decode("utf-8", errors="replace")
else:
# Handle single-part emails
payload = email_message.get_payload(decode=True)
if payload:
charset = email_message.get_content_charset("utf-8")
content_type = email_message.get_content_type()
try:
decoded = payload.decode(charset)
except UnicodeDecodeError:
decoded = payload.decode("utf-8", errors="replace")
if content_type == "text/html":
html_body = decoded
else:
body = decoded
# Truncate if too long
if body and len(body) > 20000:
body = body[:20000] + "...[TRUNCATED]"
if html_body and len(html_body) > 20000:
html_body = html_body[:20000] + "...[TRUNCATED]"
return {
"email_id": email_id or "",
"message_id": message_id,
"subject": subject,
"from": sender,
"to": to_addresses,
"body": body,
"html_body": html_body,
"date": date,
"attachments": attachments,
}
@staticmethod
def _build_search_criteria(
before: datetime | None = None,
since: datetime | None = None,
subject: str | None = None,
body: str | None = None,
text: str | None = None,
from_address: str | None = None,
to_address: str | None = None,
):
search_criteria = []
if before:
search_criteria.extend(["BEFORE", before.strftime("%d-%b-%Y").upper()])
if since:
search_criteria.extend(["SINCE", since.strftime("%d-%b-%Y").upper()])
if subject:
search_criteria.extend(["SUBJECT", subject])
if body:
search_criteria.extend(["BODY", body])
if text:
search_criteria.extend(["TEXT", text])
if from_address:
search_criteria.extend(["FROM", from_address])
if to_address:
search_criteria.extend(["TO", to_address])
# If no specific criteria, search for ALL
if not search_criteria:
search_criteria = ["ALL"]
return search_criteria
async def get_email_count(
self,
before: datetime | None = None,
since: datetime | None = None,
subject: str | None = None,
from_address: str | None = None,
to_address: str | None = None,
mailbox: str = "INBOX",
) -> int:
imap = self.imap_class(self.email_server.host, self.email_server.port)
try:
# Wait for the connection to be established
await imap._client_task
await imap.wait_hello_from_server()
# Login and select inbox
await imap.login(self.email_server.user_name, self.email_server.password)
await _send_imap_id(imap)
await imap.select(_quote_mailbox(mailbox))
search_criteria = self._build_search_criteria(
before, since, subject, from_address=from_address, to_address=to_address
)
logger.info(f"Count: Search criteria: {search_criteria}")
# Search for messages and count them - use UID SEARCH for consistency
_, messages = await imap.uid_search(*search_criteria)
return len(messages[0].split())
finally:
# Ensure we logout properly
try:
await imap.logout()
except Exception as e:
logger.info(f"Error during logout: {e}")
async def get_emails_metadata_stream( # noqa: C901
self,
page: int = 1,
page_size: int = 10,
before: datetime | None = None,
since: datetime | None = None,
subject: str | None = None,
from_address: str | None = None,
to_address: str | None = None,
order: str = "desc",
mailbox: str = "INBOX",
) -> AsyncGenerator[dict[str, Any], None]:
imap = self.imap_class(self.email_server.host, self.email_server.port)
try:
# Wait for the connection to be established
await imap._client_task
await imap.wait_hello_from_server()
# Login and select inbox
await imap.login(self.email_server.user_name, self.email_server.password)
await _send_imap_id(imap)
await imap.select(_quote_mailbox(mailbox))
search_criteria = self._build_search_criteria(
before, since, subject, from_address=from_address, to_address=to_address
)
logger.info(f"Get metadata: Search criteria: {search_criteria}")
# Search for messages - use UID SEARCH for better compatibility
_, messages = await imap.uid_search(*search_criteria)
# Handle empty or None responses
if not messages or not messages[0]:
logger.warning("No messages returned from search")
email_ids = []
else:
email_ids = messages[0].split()
logger.info(f"Found {len(email_ids)} email IDs")
# Fetch metadata for all emails first, then sort by date
# (UID order doesn't guarantee chronological order on all IMAP servers)
all_metadata: list[dict[str, Any]] = []
# Fetch each message's metadata only
for _, email_id in enumerate(email_ids):
try:
# Convert email_id from bytes to string
email_id_str = email_id.decode("utf-8")
# Fetch only headers to get metadata without body
_, data = await imap.uid("fetch", email_id_str, "BODY.PEEK[HEADER]")
if not data:
logger.error(f"Failed to fetch headers for UID {email_id_str}")
continue
# Find the email headers in the response
raw_headers = None
if len(data) > 1 and isinstance(data[1], bytearray):
raw_headers = bytes(data[1])
else:
# Search through all items for header content
for item in data:
if isinstance(item, bytes | bytearray) and len(item) > 10:
# Skip IMAP protocol responses
if isinstance(item, bytes) and b"FETCH" in item:
continue
# This is likely the header content
raw_headers = bytes(item) if isinstance(item, bytearray) else item
break
if raw_headers:
try:
# Parse headers only
parser = BytesParser(policy=default)
email_message = parser.parsebytes(raw_headers)
# Extract metadata
subject = email_message.get("Subject", "")
sender = email_message.get("From", "")
date_str = email_message.get("Date", "")
# Extract recipients
to_addresses = []
to_header = email_message.get("To", "")
if to_header:
to_addresses = [addr.strip() for addr in to_header.split(",")]
cc_header = email_message.get("Cc", "")
if cc_header:
to_addresses.extend([addr.strip() for addr in cc_header.split(",")])
# Parse date
try:
date_tuple = email.utils.parsedate_tz(date_str)
date = (
datetime.fromtimestamp(email.utils.mktime_tz(date_tuple), tz=timezone.utc)
if date_tuple
else datetime.now(timezone.utc)
)
except Exception:
date = datetime.now(timezone.utc)
# For metadata, we don't fetch attachments to save bandwidth
# We'll mark it as unknown for now
metadata = {
"email_id": email_id_str,
"subject": subject,
"from": sender,
"to": to_addresses,
"date": date,
"attachments": [], # We don't fetch attachment info for metadata
}
all_metadata.append(metadata)
except Exception as e:
# Log error but continue with other emails
logger.error(f"Error parsing email metadata: {e!s}")
else:
logger.error(f"Could not find header data in response for email ID: {email_id_str}")
except Exception as e:
logger.error(f"Error fetching email metadata {email_id}: {e!s}")
# Sort by date (desc = newest first, asc = oldest first)
all_metadata.sort(key=lambda x: x["date"], reverse=(order == "desc"))
# Apply pagination after sorting
start = (page - 1) * page_size
end = start + page_size
for metadata in all_metadata[start:end]:
yield metadata
finally:
# Ensure we logout properly
try:
await imap.logout()
except Exception as e:
logger.info(f"Error during logout: {e}")
def _check_email_content(self, data: list) -> bool:
"""Check if the fetched data contains actual email content."""
for item in data:
if isinstance(item, bytes) and b"FETCH (" in item and b"RFC822" not in item and b"BODY" not in item:
# This is just metadata, not actual content
continue
elif isinstance(item, bytes | bytearray) and len(item) > 100:
# This looks like email content
return True
return False
def _extract_raw_email(self, data: list) -> bytes | None:
"""Extract raw email bytes from IMAP response data."""
# The email content is typically at index 1 as a bytearray
if len(data) > 1 and isinstance(data[1], bytearray):
return bytes(data[1])
# Search through all items for email content
for item in data:
if isinstance(item, bytes | bytearray) and len(item) > 100:
# Skip IMAP protocol responses
if isinstance(item, bytes) and b"FETCH" in item:
continue
# This is likely the email content
return bytes(item) if isinstance(item, bytearray) else item
return None
async def _fetch_email_with_formats(self, imap, email_id: str) -> list | None:
"""Try different fetch formats to get email data."""
fetch_formats = ["RFC822", "BODY[]", "BODY.PEEK[]", "(BODY.PEEK[])"]
for fetch_format in fetch_formats:
try:
_, data = await imap.uid("fetch", email_id, fetch_format)
if data and len(data) > 0 and self._check_email_content(data):
return data
except Exception as e:
logger.debug(f"Fetch format {fetch_format} failed: {e}")
return None
async def get_email_body_by_id(self, email_id: str, mailbox: str = "INBOX") -> dict[str, Any] | None:
imap = self.imap_class(self.email_server.host, self.email_server.port)
try:
# Wait for the connection to be established
await imap._client_task
await imap.wait_hello_from_server()
# Login and select inbox
await imap.login(self.email_server.user_name, self.email_server.password)
await _send_imap_id(imap)
await imap.select(_quote_mailbox(mailbox))
# Fetch the specific email by UID
data = await self._fetch_email_with_formats(imap, email_id)
if not data:
logger.error(f"Failed to fetch UID {email_id} with any format")
return None
# Extract raw email data
raw_email = self._extract_raw_email(data)
if not raw_email:
logger.error(f"Could not find email data in response for email ID: {email_id}")
return None
# Parse the email
try:
return self._parse_email_data(raw_email, email_id)
except Exception as e:
logger.error(f"Error parsing email: {e!s}")
return None
finally:
# Ensure we logout properly
try:
await imap.logout()
except Exception as e:
logger.info(f"Error during logout: {e}")
async def download_attachment(
self,
email_id: str,
attachment_name: str,
save_path: str,
mailbox: str = "INBOX",
) -> dict[str, Any]:
"""Download a specific attachment from an email and save it to disk.
Args:
email_id: The UID of the email containing the attachment.
attachment_name: The filename of the attachment to download.
save_path: The local path where the attachment will be saved.
mailbox: The mailbox to search in (default: "INBOX").
Returns:
A dictionary with download result information.
"""
imap = self.imap_class(self.email_server.host, self.email_server.port)
try:
await imap._client_task
await imap.wait_hello_from_server()
await imap.login(self.email_server.user_name, self.email_server.password)
await _send_imap_id(imap)
await imap.select(_quote_mailbox(mailbox))
data = await self._fetch_email_with_formats(imap, email_id)
if not data:
msg = f"Failed to fetch email with UID {email_id}"
logger.error(msg)
raise ValueError(msg)
raw_email = self._extract_raw_email(data)
if not raw_email:
msg = f"Could not find email data for email ID: {email_id}"
logger.error(msg)
raise ValueError(msg)
parser = BytesParser(policy=default)
email_message = parser.parsebytes(raw_email)
# Find the attachment
attachment_data = None
mime_type = None
if email_message.is_multipart():
for part in email_message.walk():
content_disposition = str(part.get("Content-Disposition", ""))
if "attachment" in content_disposition:
filename = part.get_filename()
if filename == attachment_name:
attachment_data = part.get_payload(decode=True)
mime_type = part.get_content_type()
break
if attachment_data is None:
msg = f"Attachment '{attachment_name}' not found in email {email_id}"
logger.error(msg)
raise ValueError(msg)
# Save to disk
save_file = Path(save_path)
save_file.parent.mkdir(parents=True, exist_ok=True)
save_file.write_bytes(attachment_data)
logger.info(f"Attachment '{attachment_name}' saved to {save_path}")
return {
"email_id": email_id,
"attachment_name": attachment_name,
"mime_type": mime_type or "application/octet-stream",
"size": len(attachment_data),
"saved_path": str(save_file.resolve()),
}
finally:
try:
await imap.logout()
except Exception as e:
logger.info(f"Error during logout: {e}")
def _validate_attachment(self, file_path: str) -> Path:
"""Validate attachment file path."""
path = Path(file_path)
if not path.exists():
msg = f"Attachment file not found: {file_path}"
logger.error(msg)
raise FileNotFoundError(msg)
if not path.is_file():
msg = f"Attachment path is not a file: {file_path}"
logger.error(msg)
raise ValueError(msg)
return path
def _create_attachment_part(self, path: Path) -> MIMEApplication:
"""Create MIME attachment part from file."""
with open(path, "rb") as f:
file_data = f.read()
mime_type, _ = mimetypes.guess_type(str(path))
if mime_type is None:
mime_type = "application/octet-stream"
attachment_part = MIMEApplication(file_data, _subtype=mime_type.split("/")[1])
attachment_part.add_header(
"Content-Disposition",
"attachment",
filename=path.name,
)
logger.info(f"Attached file: {path.name} ({mime_type})")
return attachment_part
def _create_message_with_attachments(self, body: str, html: bool, attachments: list[str]) -> MIMEMultipart:
"""Create multipart message with attachments."""
msg = MIMEMultipart()
content_type = "html" if html else "plain"
text_part = MIMEText(body, content_type, "utf-8")
msg.attach(text_part)
for file_path in attachments:
try:
path = self._validate_attachment(file_path)
attachment_part = self._create_attachment_part(path)
msg.attach(attachment_part)
except Exception as e:
logger.error(f"Failed to attach file {file_path}: {e}")
raise
return msg
async def send_email(
self,
recipients: list[str],
subject: str,
body: str,
cc: list[str] | None = None,
bcc: list[str] | None = None,
html: bool = False,
attachments: list[str] | None = None,
in_reply_to: str | None = None,
references: str | None = None,
):
# Create message with or without attachments
if attachments:
msg = self._create_message_with_attachments(body, html, attachments)
else:
content_type = "html" if html else "plain"
msg = MIMEText(body, content_type, "utf-8")
# Handle subject with special characters
if any(ord(c) > 127 for c in subject):
msg["Subject"] = Header(subject, "utf-8")
else:
msg["Subject"] = subject
# Handle sender name with special characters
if any(ord(c) > 127 for c in self.sender):
msg["From"] = Header(self.sender, "utf-8")
else:
msg["From"] = self.sender
msg["To"] = ", ".join(recipients)
# Add CC header if provided (visible to recipients)
if cc:
msg["Cc"] = ", ".join(cc)
# Set threading headers for replies
if in_reply_to:
msg["In-Reply-To"] = in_reply_to
if references:
msg["References"] = references
# Note: BCC recipients are not added to headers (they remain hidden)
# but will be included in the actual recipients for SMTP delivery
async with aiosmtplib.SMTP(
hostname=self.email_server.host,
port=self.email_server.port,
start_tls=self.smtp_start_tls,
use_tls=self.smtp_use_tls,
) as smtp:
await smtp.login(self.email_server.user_name, self.email_server.password)
# Create a combined list of all recipients for delivery
all_recipients = recipients.copy()
if cc:
all_recipients.extend(cc)
if bcc:
all_recipients.extend(bcc)
await smtp.send_message(msg, recipients=all_recipients)
# Return the message for potential saving to Sent folder
return msg
async def _find_sent_folder_by_flag(self, imap) -> str | None:
"""Find the Sent folder by searching for the \\Sent IMAP flag.
Args:
imap: Connected IMAP client
Returns:
The folder name with the \\Sent flag, or None if not found
"""
try:
# List all folders - aioimaplib requires reference_name and mailbox_pattern
_, folders = await imap.list('""', "*")
# Search for folder with \Sent flag
for folder in folders:
folder_str = folder.decode("utf-8") if isinstance(folder, bytes) else str(folder)
# IMAP LIST response format: (flags) "delimiter" "name"
# Example: (\Sent \HasNoChildren) "/" "Gesendete Objekte"
if r"\Sent" in folder_str or "\\Sent" in folder_str:
# Extract folder name from the response
# Split by quotes and get the last quoted part
parts = folder_str.split('"')
if len(parts) >= 3:
folder_name = parts[-2] # The folder name is the second-to-last quoted part
logger.info(f"Found Sent folder by \\Sent flag: '{folder_name}'")
return folder_name
except Exception as e:
logger.debug(f"Error finding Sent folder by flag: {e}")
return None
async def append_to_sent(
self,
msg: MIMEText | MIMEMultipart,
incoming_server: EmailServer,
sent_folder_name: str | None = None,
) -> bool:
"""Append a sent message to the IMAP Sent folder.
Args:
msg: The email message that was sent
incoming_server: IMAP server configuration for accessing Sent folder
sent_folder_name: Override folder name, or None for auto-detection
Returns:
True if successfully saved, False otherwise
"""
imap_class = aioimaplib.IMAP4_SSL if incoming_server.use_ssl else aioimaplib.IMAP4
imap = imap_class(incoming_server.host, incoming_server.port)
# Common Sent folder names across different providers
sent_folder_candidates = [
sent_folder_name, # User-specified override (if provided)
"Sent",
"INBOX.Sent",
"Sent Items",
"Sent Mail",
"[Gmail]/Sent Mail",
"INBOX/Sent",
]
# Filter out None values
sent_folder_candidates = [f for f in sent_folder_candidates if f]
try:
await imap._client_task
await imap.wait_hello_from_server()
await imap.login(incoming_server.user_name, incoming_server.password)
await _send_imap_id(imap)
# Try to find Sent folder by IMAP \Sent flag first
flag_folder = await self._find_sent_folder_by_flag(imap)
if flag_folder and flag_folder not in sent_folder_candidates:
# Add it at the beginning (high priority)
sent_folder_candidates.insert(0, flag_folder)
# Try to find and use the Sent folder
for folder in sent_folder_candidates:
try:
logger.debug(f"Trying Sent folder: '{folder}'")
# Try to select the folder to verify it exists
result = await imap.select(_quote_mailbox(folder))
logger.debug(f"Select result for '{folder}': {result}")
# aioimaplib returns (status, data) where status is a string like 'OK' or 'NO'
status = result[0] if isinstance(result, tuple) else result
if str(status).upper() == "OK":
# Folder exists, append the message
msg_bytes = msg.as_bytes()
logger.debug(f"Appending message to '{folder}'")
# aioimaplib.append signature: (message_bytes, mailbox, flags, date)
append_result = await imap.append(
msg_bytes,
mailbox=_quote_mailbox(folder),
flags=r"(\Seen)",
)
logger.debug(f"Append result: {append_result}")
append_status = append_result[0] if isinstance(append_result, tuple) else append_result
if str(append_status).upper() == "OK":
logger.info(f"Saved sent email to '{folder}'")
return True
else:
logger.warning(f"Failed to append to '{folder}': {append_status}")
else:
logger.debug(f"Folder '{folder}' select returned: {status}")
except Exception as e:
logger.debug(f"Folder '{folder}' not available: {e}")
continue
logger.warning("Could not find a valid Sent folder to save the message")
return False
except Exception as e:
logger.error(f"Error saving to Sent folder: {e}")
return False
finally:
try:
await imap.logout()
except Exception as e:
logger.debug(f"Error during logout: {e}")
async def delete_emails(self, email_ids: list[str], mailbox: str = "INBOX") -> tuple[list[str], list[str]]:
"""Delete emails by their UIDs. Returns (deleted_ids, failed_ids)."""
imap = self.imap_class(self.email_server.host, self.email_server.port)
deleted_ids = []
failed_ids = []
try:
await imap._client_task
await imap.wait_hello_from_server()
await imap.login(self.email_server.user_name, self.email_server.password)
await _send_imap_id(imap)
await imap.select(_quote_mailbox(mailbox))
for email_id in email_ids:
try:
await imap.uid("store", email_id, "+FLAGS", r"(\Deleted)")
deleted_ids.append(email_id)
except Exception as e:
logger.error(f"Failed to delete email {email_id}: {e}")
failed_ids.append(email_id)
await imap.expunge()
finally:
try:
await imap.logout()
except Exception as e:
logger.info(f"Error during logout: {e}")
return deleted_ids, failed_ids
class ClassicEmailHandler(EmailHandler):
def __init__(self, email_settings: EmailSettings):
self.email_settings = email_settings
self.incoming_client = EmailClient(email_settings.incoming)
self.outgoing_client = EmailClient(
email_settings.outgoing,
sender=f"{email_settings.full_name} <{email_settings.email_address}>",
)
self.save_to_sent = email_settings.save_to_sent
self.sent_folder_name = email_settings.sent_folder_name
async def get_emails_metadata(
self,
page: int = 1,
page_size: int = 10,
before: datetime | None = None,
since: datetime | None = None,
subject: str | None = None,
from_address: str | None = None,
to_address: str | None = None,
order: str = "desc",
mailbox: str = "INBOX",
) -> EmailMetadataPageResponse:
emails = []
async for email_data in self.incoming_client.get_emails_metadata_stream(
page, page_size, before, since, subject, from_address, to_address, order, mailbox
):
emails.append(EmailMetadata.from_email(email_data))
total = await self.incoming_client.get_email_count(
before, since, subject, from_address=from_address, to_address=to_address, mailbox=mailbox
)
return EmailMetadataPageResponse(
page=page,
page_size=page_size,
before=before,
since=since,
subject=subject,
emails=emails,
total=total,
)
async def get_emails_content(
self,
email_ids: list[str],
mailbox: str = "INBOX",
content_format: str = "raw",
) -> EmailContentBatchResponse:
"""Batch retrieve email body content.
Args:
email_ids: List of email UIDs to retrieve.
mailbox: The mailbox to search in (default: "INBOX").
content_format: How to format the body content:
- "raw": Return original content (text/plain preferred, falls back to HTML)
- "html": Return HTML content as-is
- "text": Strip HTML tags and return clean plain text
- "markdown": Convert HTML to markdown format
"""
emails = []
failed_ids = []
for email_id in email_ids:
try:
email_data = await self.incoming_client.get_email_body_by_id(email_id, mailbox)
if email_data:
# Apply content format conversion
formatted_body = _format_body_content(
email_data.get("body", ""),
email_data.get("html_body", ""),
content_format,
)
emails.append(
EmailBodyResponse(
email_id=email_data["email_id"],
message_id=email_data.get("message_id"),
subject=email_data["subject"],
sender=email_data["from"],
recipients=email_data["to"],
date=email_data["date"],
body=formatted_body,
attachments=email_data["attachments"],
)
)
else:
failed_ids.append(email_id)
except Exception as e:
logger.error(f"Failed to retrieve email {email_id}: {e}")
failed_ids.append(email_id)
return EmailContentBatchResponse(
emails=emails,
requested_count=len(email_ids),
retrieved_count=len(emails),
failed_ids=failed_ids,
)
async def send_email(
self,
recipients: list[str],
subject: str,
body: str,
cc: list[str] | None = None,
bcc: list[str] | None = None,
html: bool = False,
attachments: list[str] | None = None,
in_reply_to: str | None = None,
references: str | None = None,
) -> None:
msg = await self.outgoing_client.send_email(
recipients, subject, body, cc, bcc, html, attachments, in_reply_to, references
)
# Save to Sent folder if enabled
if self.save_to_sent and msg:
try:
await self.outgoing_client.append_to_sent(
msg,
self.email_settings.incoming,
self.sent_folder_name,
)
except Exception as e:
logger.error(f"Failed to save email to Sent folder: {e}", exc_info=True)
async def delete_emails(self, email_ids: list[str], mailbox: str = "INBOX") -> tuple[list[str], list[str]]:
"""Delete emails by their UIDs. Returns (deleted_ids, failed_ids)."""
return await self.incoming_client.delete_emails(email_ids, mailbox)
async def download_attachment(
self,
email_id: str,
attachment_name: str,
save_path: str,
mailbox: str = "INBOX",
) -> AttachmentDownloadResponse:
"""Download an email attachment and save it to the specified path.
Args:
email_id: The UID of the email containing the attachment.
attachment_name: The filename of the attachment to download.
save_path: The local path where the attachment will be saved.
mailbox: The mailbox to search in (default: "INBOX").
Returns:
AttachmentDownloadResponse with download result information.
"""