Coverage for apps / backend / src / orcheo_backend / app / mcp_server / email_client.py: 99%
1696 statements
« prev ^ index » next coverage.py v7.13.0, created at 2026-11-16 14:04 +0000
« prev ^ index » next coverage.py v7.13.0, created at 2026-11-16 14:04 +0000
1"""IMAP/SMTP operations for Orcheo's MCP tools.
3Mailbox settings and passwords are stored as encrypted Orcheo vault secrets and
4are never included in a tool result. Outbound connections require TLS and pin a
5public DNS result for the lifetime of the socket so a configured host cannot
6reach private services.
7"""
9# The mailbox protocol implementation preserves the compact public schemas and
10# interoperable parsing helpers of the migrated client.
11# ruff: noqa: D101,D102,D103,D107,E501,C901,PLR0911,PLR0912,PLR0915
13from __future__ import annotations
14import base64
15import email
16import email.policy
17import hashlib
18import html
19import imaplib
20import io
21import ipaddress
22import itertools
23import json
24import logging
25import re
26import smtplib
27import socket
28import ssl
29import time
30import uuid
31from collections.abc import Callable, Sequence
32from datetime import UTC, date, datetime, timedelta
33from email.header import decode_header, make_header
34from email.message import EmailMessage, Message
35from email.parser import BytesParser
36from email.utils import formataddr, formatdate, getaddresses, make_msgid, parseaddr
37from html.parser import HTMLParser
38from typing import Annotated, Any, Literal, cast
39from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
40from orcheo.models import CredentialAccessContext, CredentialMetadata, CredentialScope
41from orcheo.vault import (
42 BaseCredentialVault,
43 CredentialNotFoundError,
44 WorkflowScopeError,
45)
46from orcheo.workspace import WorkspaceAuditEvent
47from orcheo_backend.app.credential_internal import EMAIL_ACCOUNT_CREDENTIAL_PROVIDER
48from orcheo_backend.app.mcp_server.email_errors import ServiceError
51MAX_READ_BATCH = 100
52MAX_EMAIL_SIZE = 4_000_000
53MAX_ATTACHMENT_SIZE = 500_000
54EMAIL_RESULT_RETENTION = timedelta(days=1)
55EMAIL_FAILURE_RETENTION = timedelta(days=30)
56SCHEDULE_INTERRUPTED_AFTER = timedelta(minutes=15)
57EMAIL_CREDENTIAL_ROLE = "email-tools"
58# smtplib only negotiates BODY=8BITMIME for international envelope addresses.
59# Encode bodies safely even when ordinary addresses carry Unicode text.
60OUTBOUND_POLICY = email.policy.SMTP.clone(cte_type="7bit")
61logger = logging.getLogger("orcheo.mcp_email")
62MessageIdentifier = Annotated[str, Field(min_length=1, max_length=1000)]
63EmailIdentifier = Annotated[str, Field(min_length=1, max_length=200)]
64ShortText = Annotated[str, Field(max_length=500)]
67class EmailArguments(BaseModel):
68 model_config = ConfigDict(extra="forbid", strict=True)
71class EmailProtocol(EmailArguments):
72 host: str = Field(min_length=1, max_length=253)
73 port: int = Field(ge=1, le=65535)
74 security: Literal["ssl", "starttls"] = "ssl"
75 username: str = Field(min_length=1, max_length=320)
76 password: str | None = Field(default=None, max_length=512)
78 @field_validator("host", "username")
79 @classmethod
80 def trim_required(cls, value: str) -> str:
81 value = value.strip() 2gb$chbOc3 X eb~ - 8 4 + lb{ rcqc] @ ` fbkb; dbmbnbobv % pbqbE rbm sbB tbubvbwbxbk w L =c}c~c)c*c9c$dybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUbVbWbXbYbZb0b1b2b3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcc gchcicJ jckclc0 mcncf
82 if not value or any(ord(character) < 32 for character in value): 2gb$chbOc3 X eb~ - 8 4 + lb{ rcqc] @ ` fbkb; dbmbnbobv % pbqbE rbm sbB tbubvbwbxbk w L =c}c~c)c*c9c$dybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUbVbWbXbYbZb0b1b2b3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcc gchcicJ jckclc0 mcncf
83 raise ValueError("Enter a valid server name or username.") 2$d
84 return value 2gb$chbOc3 X eb~ - 8 4 + lb{ rcqc] @ ` fbkb; dbmbnbobv % pbqbE rbm sbB tbubvbwbxbk w L =c}c~c)c*c9c$dybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUbVbWbXbYbZb0b1b2b3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcc gchcicJ jckclc0 mcncf
87class EmailAccountSave(EmailArguments):
88 account_id: EmailIdentifier | None = None
89 display_name: str = Field(min_length=1, max_length=100)
90 email_address: str = Field(min_length=3, max_length=320)
91 labels: list[ShortText] = Field(default_factory=list, max_length=20)
92 is_default: bool = False
93 enabled: bool = True
94 imap: EmailProtocol
95 smtp: EmailProtocol
96 signature_text: str = Field(default="", max_length=2000)
97 save_sent_copy: bool = True
99 @field_validator("display_name", "email_address")
100 @classmethod
101 def trim_value(cls, value: str) -> str:
102 value = value.strip() 2gb$chbOc3 X eb~ - 8 4 + lb{ rcqc] @ ` fbkb; dbmbnbobv % pbqbE rbm sbB tbubvbwbxbk w L =c}c~c)c*c9cybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUbVbWbXbYbZb0b1b2b3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcc gchcicJ jckclc0 mcncf
103 if not value or any(ord(character) < 32 for character in value): 2gb$chbOc3 X eb~ - 8 4 + lb{ rcqc] @ ` fbkb; dbmbnbobv % pbqbE rbm sbB tbubvbwbxbk w L =c}c~c)c*c9cybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUbVbWbXbYbZb0b1b2b3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcc gchcicJ jckclc0 mcncf
104 raise ValueError("Enter valid text without control characters.") 2=c
105 return value 2gb$chbOc3 X eb~ - 8 4 + lb{ rcqc] @ ` fbkb; dbmbnbobv % pbqbE rbm sbB tbubvbwbxbk w L =c}c~c)c*c9cybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUbVbWbXbYbZb0b1b2b3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcc gchcicJ jckclc0 mcncf
107 @field_validator("email_address")
108 @classmethod
109 def valid_email(cls, value: str) -> str:
110 name, address = parseaddr(value) 2gb$chbOc3 X eb~ - 8 4 + lb{ rcqc] @ ` fbkb; dbmbnbobv % pbqbE rbm sbB tbubvbwbxbk w L =c}c~c)c*c9cybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUbVbWbXbYbZb0b1b2b3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcc gchcicJ jckclc0 mcncf
111 if name or address != value or not re.fullmatch(r"[^\s@<>]+@[^\s@<>]+", value): 2gb$chbOc3 X eb~ - 8 4 + lb{ rcqc] @ ` fbkb; dbmbnbobv % pbqbE rbm sbB tbubvbwbxbk w L =c}c~c)c*c9cybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUbVbWbXbYbZb0b1b2b3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcc gchcicJ jckclc0 mcncf
112 raise ValueError("Enter a valid email address.") 2}c~c
113 return value 2gb$chbOc3 X eb~ - 8 4 + lb{ rcqc] @ ` fbkb; dbmbnbobv % pbqbE rbm sbB tbubvbwbxbk w L =c)c*c9cybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUbVbWbXbYbZb0b1b2b3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcc gchcicJ jckclc0 mcncf
115 @field_validator("labels")
116 @classmethod
117 def clean_labels(cls, labels: list[str]) -> list[str]:
118 cleaned = list( 2gb$chbOc3 X eb~ )c*c9c
119 dict.fromkeys(label.strip() for label in labels if label.strip())
120 )
121 if any( 2gb$chbOc3 X eb~ )c*c9c
122 len(label) > 100 or any(ord(char) < 32 for char in label)
123 for label in cleaned
124 ):
125 raise ValueError("Labels must be 1–100 characters.") 2)c*c
126 return cleaned 2gb$chbOc3 X eb~ 9c
128 @model_validator(mode="after")
129 def require_new_account_passwords(self) -> EmailAccountSave:
130 if not self.account_id and (not self.imap.password or not self.smtp.password): 2gb$chbOc3 X eb~ - 8 4 + lb{ rcqc] @ ` fbkb; dbmbnbobv % pbqbE rbm sbB tbubvbwbxbk w L 9cybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUbVbWbXbYbZb0b1b2b3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcc gchcicJ jckclc0 mcncf
131 raise ValueError("Enter an IMAP and SMTP password for a new account.") 29c
132 return self 2gb$chbOc3 X eb~ - 8 4 + lb{ rcqc] @ ` fbkb; dbmbnbobv % pbqbE rbm sbB tbubvbwbxbk w L 9cybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUbVbWbXbYbZb0b1b2b3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcc gchcicJ jckclc0 mcncf
135class EmailAccountIdentifier(EmailArguments):
136 account_id: EmailIdentifier
139class TestEmailAccount(EmailAccountIdentifier):
140 protocol: Literal["imap", "smtp", "both"] = "both"
143class SearchEmails(EmailArguments):
144 account_id: EmailIdentifier | None = None
145 folder: str = Field(
146 default="INBOX",
147 min_length=1,
148 max_length=255,
149 description="A folder name, or one of inbox, sent, drafts, trash, junk, archive, all.",
150 )
151 unread_only: bool = False
152 from_address: ShortText | None = None
153 to_address: ShortText | None = None
154 subject: ShortText | None = None
155 text: ShortText | None = Field(
156 default=None, description="Words anywhere in the headers or body."
157 )
158 flagged: bool | None = None
159 answered: bool | None = None
160 larger_than_kb: int | None = Field(default=None, ge=1, le=100_000)
161 has_attachments: bool | None = None
162 after: str | None = Field(default=None, max_length=10)
163 before: str | None = Field(default=None, max_length=10)
164 limit: int = Field(default=20, ge=1, le=50)
165 cursor: str | None = Field(default=None, max_length=40)
167 @field_validator("cursor")
168 @classmethod
169 def numeric_cursor(cls, value: str | None) -> str | None:
170 if value is not None and not re.fullmatch(r"(\d+\.)?\d+", value): 2id[dq y
171 raise ValueError("Email page cursor is invalid.") 2[d
172 return value 2idq y
174 @model_validator(mode="after")
175 def valid_range(self) -> SearchEmails:
176 for value in (self.after, self.before): 2d 'did%dsd2d# a u q y o x
177 if value is not None: 2d 'did%dsd2d# a u q y o x
178 if not re.fullmatch(r"\d{4}-\d{2}-\d{2}", value): 2id%dsd2dx
179 raise ValueError("Use dates in YYYY-MM-DD format.") 2%d
180 try: 2idsd2dx
181 date.fromisoformat(value) 2idsd2dx
182 except ValueError as error: 2sd
183 raise ValueError("Use dates in YYYY-MM-DD format.") from error 2sd
184 if (
185 self.after
186 and self.before
187 and date.fromisoformat(self.after) > date.fromisoformat(self.before)
188 ):
189 raise ValueError("The start date must not be after the end date.") 22d
190 return self 2d 'did# a u q y o x
193class GetEmail(EmailArguments):
194 message_id: MessageIdentifier
195 include_html: bool = Field(
196 default=False,
197 description="Also return the HTML body. The text body is usually enough.",
198 )
199 max_body_chars: int = Field(default=20_000, ge=500, le=100_000)
202class EmailAttachment(EmailArguments):
203 filename: str = Field(min_length=1, max_length=255)
204 content_type: str = Field(default="application/octet-stream", max_length=150)
205 content_base64: str = Field(min_length=1, max_length=700_000)
207 @field_validator("filename")
208 @classmethod
209 def valid_filename(cls, value: str) -> str:
210 if (
211 any(ord(character) < 32 for character in value)
212 or "/" in value
213 or "\\" in value
214 ):
215 raise ValueError("Attachment filename is invalid.") 2]d
216 return value 2]d6c4cab
219class DraftEmail(EmailArguments):
220 account_id: EmailIdentifier | None = None
221 to: list[str] = Field(default_factory=list, max_length=50)
222 cc: list[str] = Field(default_factory=list, max_length=50)
223 bcc: list[str] = Field(default_factory=list, max_length=50)
224 reply_to: str | None = Field(default=None, max_length=320)
225 subject: str = Field(min_length=1, max_length=998)
226 body_text: str | None = Field(default=None, max_length=100_000)
227 body_html: str | None = Field(default=None, max_length=100_000)
228 in_reply_to: str | None = Field(default=None, max_length=998)
229 references: list[str] = Field(default_factory=list, max_length=20)
230 attachments: list[EmailAttachment] = Field(default_factory=list, max_length=3)
231 include_signature: bool = True
232 idempotency_key: str | None = Field(
233 default=None,
234 max_length=100,
235 description="Your own key for this send; a retry with the same key is not sent twice.",
236 )
238 @field_validator("to", "cc", "bcc")
239 @classmethod
240 def valid_addresses(cls, values: list[str]) -> list[str]:
241 for value in values: 2eb7d+c,c(c3d8dtdjd?cudkdad-c.cbdvd6c4c2c! ibt ^ ocs ( jbEcz ? DcQ abzcBci e xcCcV 9 5 J U 0 6 ' f
242 if "\r" in value or "\n" in value: 2eb7d+c,c(c3d8dtdjd?cudkdad-c.cbd6c4c2c! ibt ^ ocs ( jbEcz ? DcQ abzcBci e xcCcV 9 5 J U 0 6 ' f
243 raise ValueError("Use valid email addresses.") 28d
244 name, address = parseaddr(value) 2eb7d+c,c(c3dtdjd?cudkdad-c.cbd6c4c2c! ibt ^ ocs ( jbEcz ? DcQ abzcBci e xcCcV 9 5 J U 0 6 ' f
245 if not re.fullmatch(r"[^\s@<>]+@[^\s@<>]+", address) or ( 2eb7d+c,c(c3dtdjd?cudkdad-c.cbd6c4c2c! ibt ^ ocs ( jbEcz ? DcQ abzcBci e xcCcV 9 5 J U 0 6 ' f
246 not name and address != value.strip()
247 ):
248 raise ValueError( 2eb(c3dtdjd?c
249 "Use email addresses, optionally with a name: Ada <ada@example.com>."
250 )
251 return list(dict.fromkeys(values)) 2eb7d+c,c(c3djd?cudkdad-c.cbdvd6c4c2c! ibt ^ ocs ( jbEcz ? DcQ abzcBci e xcCcV 9 5 J U 0 6 ' f
253 @field_validator("reply_to")
254 @classmethod
255 def valid_reply_to(cls, value: str | None) -> str | None:
256 if value is None: 2eb?c2cab
257 return None 2eb2c
258 return cls.valid_addresses([value])[0] 2?cab
260 @field_validator("subject", "in_reply_to")
261 @classmethod
262 def no_header_injection(cls, value: str | None) -> str | None:
263 if value is not None and ("\r" in value or "\n" in value): 2eb+c,c(c8dtdjd?cudkdad-c.cbdvd6c4c2c! ibt ^ ocs ( jbEcz ? DcQ abzcBcxcCcV 9 5 J U 0 6 ' f
264 raise ValueError("Email headers cannot contain line breaks.") 2udkd
265 return value 2eb+c,c(c8dtdjd?ckdad-c.cbdvd6c4c2c! ibt ^ ocs ( jbEcz ? DcQ abzcBcxcCcV 9 5 J U 0 6 ' f
267 @field_validator("references")
268 @classmethod
269 def valid_references(cls, values: list[str]) -> list[str]:
270 if any("\r" in value or "\n" in value for value in values): 2ebadab
271 raise ValueError("Email references cannot contain line breaks.") 2ad
272 return values 2ebab
274 @model_validator(mode="after")
275 def valid_message(self) -> DraftEmail:
276 if not self.body_text and not self.body_html: 2eb+c,c(cbdvd6c4c2c! ibt ^ ocs ( jbEcz ? DcQ abzcBcxcCcV 9 5 J U 0 6 ' f
277 raise ValueError("Provide a text or HTML message body.") 2bd
278 if sum(map(len, (self.to, self.cc, self.bcc))) == 0: 2eb+c,c(cvd6c4c2c! ibt ^ ocs ( jbEcz ? DcQ abzcBcxcCcV 9 5 J U 0 6 ' f
279 raise ValueError("Provide at least one recipient.") 2vd
280 if sum(len(item.content_base64) for item in self.attachments) > 700_000: 2eb+c,c(c6c4c2c! ibt ^ ocs ( jbEcz ? DcQ abzcBcxcCcV 9 5 J U 0 6 ' f
281 raise ValueError("Attachments must total 500 KB or less.") 24c
282 for item in self.attachments: 2eb+c,c(c6c4c2c! ibt ^ ocs ( jbEcz ? DcQ abzcBcxcCcV 9 5 J U 0 6 ' f
283 try: 26c4cab
284 raw = base64.b64decode(item.content_base64, validate=True) 26c4cab
285 except ValueError as error: 26c
286 raise ValueError("Attachment content must be valid base64.") from error 26c
287 if len(raw) > MAX_ATTACHMENT_SIZE: 24cab
288 raise ValueError("Each attachment must be 500 KB or less.") 24c
289 return self 2eb+c,c(c2c! ibt ^ ocs ( jbEcz ? DcQ abzcBcxcCcV 9 5 J U 0 6 ' f
292class SendEmail(DraftEmail):
293 send_at: str | None = Field(
294 default=None,
295 max_length=40,
296 description="Schedule for later (ISO 8601 with offset), up to 30 days ahead.",
297 )
299 @field_validator("send_at")
300 @classmethod
301 def aware_send_at(cls, value: str | None) -> str | None:
302 if value is not None: 2eb-c.c2c
303 try: 2-c.c2c
304 parsed = datetime.fromisoformat(value.replace("Z", "+00:00")) 2-c.c2c
305 except ValueError as error: 2-c
306 raise ValueError("Use an ISO 8601 time with a UTC offset.") from error 2-c
307 if parsed.utcoffset() is None: 2.c2c
308 raise ValueError("Use an ISO 8601 time with a UTC offset.") 2.c
309 return value 2eb2c
312class EmailMessageIds(EmailArguments):
313 message_ids: list[MessageIdentifier] = Field(
314 min_length=1, max_length=MAX_READ_BATCH
315 )
317 @field_validator("message_ids")
318 @classmethod
319 def unique_ids(cls, values: list[str]) -> list[str]:
320 if len(values) != len(set(values)): 2cd^d_dP 1 Y v % K E Z m B W M k w L (d9d!d4dwdldmdddedfd
321 raise ValueError("Provide each email identifier once.") 2(d
322 return values 2cd^d_dP 1 Y v % K E Z m B W M k w L (d9d!d4dwdldmdddedfd
325class DownloadEmailAttachment(EmailArguments):
326 attachment_id: MessageIdentifier
329class EmailActions(EmailMessageIds):
330 action: Literal[
331 "archive",
332 "move",
333 "copy",
334 "flag",
335 "unflag",
336 "delete",
337 "junk",
338 "not_junk",
339 "add_labels",
340 "remove_labels",
341 "mark_answered",
342 ]
343 target_folder: str | None = Field(default=None, max_length=255)
344 labels: list[ShortText] = Field(default_factory=list, max_length=10)
345 # Deleting moves to Trash, where the user can still recover a message an
346 # assistant picked by mistake. Expunging is the explicit exception.
347 permanent: bool = False
349 @model_validator(mode="after")
350 def move_requires_folder(self) -> EmailActions:
351 needs_folder = self.action in {"move", "copy"} 2cdP 1 Y v % K E Z m B W M k w L 9d!d4dwdldmdddedfd
352 if needs_folder and not self.target_folder: 2cdP 1 Y v % K E Z m B W M k w L 9d!d4dwdldmdddedfd
353 raise ValueError("Choose a destination folder for moving or copying.") 29d!d
354 if not needs_folder and self.target_folder: 2cdP 1 Y v % K E Z m B W M k w L 4dwdldmdddedfd
355 raise ValueError( 24d
356 "A destination folder is only used when moving or copying."
357 )
358 if self.permanent and self.action != "delete": 2cdP 1 Y v % K E Z m B W M k w L wdldmdddedfd
359 raise ValueError("permanent only applies to deleting messages.") 2wd
360 if (self.action in {"add_labels", "remove_labels"}) != bool(self.labels): 2cdP 1 Y v % K E Z m B W M k w L ldmdddedfd
361 raise ValueError( 2ldmd
362 "Labels go with add_labels or remove_labels, and only then."
363 )
364 if any( 2cdP 1 Y v % K E Z m B W M k w L ddedfd
365 not label.strip() or re.search(r'[\s()"\\{}%*\]]', label)
366 for label in self.labels
367 ) and not all(label.startswith("\\") for label in self.labels):
368 raise ValueError("Labels are single words without brackets or quotes.") 2dded
369 return self 2cdP 1 Y v % K E Z m B W M k w L fd
372_SPECIAL_FOLDERS = {
373 "archive": (rb"\\archive", {"archive", "archives"}),
374 "trash": (
375 rb"\\trash",
376 {"trash", "deleted items", "deleted messages", "[gmail]/trash", "inbox.trash"},
377 ),
378 "sent": (
379 rb"\\sent",
380 {
381 "sent",
382 "sent items",
383 "sent messages",
384 "sent mail",
385 "[gmail]/sent mail",
386 "inbox.sent",
387 },
388 ),
389 "drafts": (rb"\\drafts", {"drafts", "draft", "[gmail]/drafts", "inbox.drafts"}),
390 "junk": (
391 rb"\\junk",
392 {"junk", "spam", "junk e-mail", "junk email", "[gmail]/spam", "inbox.junk"},
393 ),
394 "all": (rb"\\all", {"all mail", "[gmail]/all mail"}),
395}
396FOLDER_ALIASES = frozenset({"sent", "drafts", "trash", "junk", "archive", "all"})
399def _special_folders(client: imaplib.IMAP4, kind: str) -> list[str]:
400 r"""The server's own names for a special-use folder, best first.
402 The RFC 6154 special-use flag wins; a conventional name is the fallback
403 for servers that do not advertise one. Several folders can carry the
404 same flag: Dovecot's stock config marks both "Sent" and Apple Mail's
405 "Sent Messages" as \\Sent. The one named after the role is the server's
406 own, the folder its webmail shows, so that one comes first.
407 """
408 flag, names = _SPECIAL_FOLDERS[kind] 2Fcv K E m M k w a 7 , o G R H T O I s z A Q i e V j h p g 9 5 J U C f
409 _, folders = client.list() 2Fcv K E m M k w a 7 , o G R H T O I s z A Q i e V j h p g 9 5 J U C f
410 named: list[str] = [] 2Fcv K E m M k w a 7 , o G R H T O I s z A Q i e V j h p g 9 5 J U C f
411 flagged: list[str] = [] 2Fcv K E m M k w a 7 , o G R H T O I s z A Q i e V j h p g 9 5 J U C f
412 by_name = None 2Fcv K E m M k w a 7 , o G R H T O I s z A Q i e V j h p g 9 5 J U C f
413 for folder_row in folders or []: 2Fcv K E m M k w a 7 , o G R H T O I s z A Q i e V j h p g 9 5 J U C f
414 if not isinstance(folder_row, bytes): 2Fcv K E m M k w a 7 , o G R H T O I s z A Q i e V j h p g 9 5 J U C f
415 continue 2Fc
416 match = re.search( 2Fcv K E m M k w a 7 , o G R H T O I s z A Q i e V j h p g 9 5 J U C f
417 rb'\((.*?)\)\s+(?:"([^"]*)"|NIL)\s+("(?:[^"\\]|\\.)*"|[^\s]+)$',
418 folder_row,
419 )
420 if not match: 2Fcv K E m M k w a 7 , o G R H T O I s z A Q i e V j h p g 9 5 J U C f
421 continue 2Fc
422 candidate = match.group(3).decode("utf-8", "replace").strip('"') 2Fcv K E m M k w a 7 , o G R H T O I s z A Q i e V j h p g 9 5 J U C f
423 if re.search(flag + rb"(?:\s|$)", match.group(1).lower()): 2Fcv K E m M k w a 7 , o G R H T O I s z A Q i e V j h p g 9 5 J U C f
424 delimiter = (match.group(2) or b"").decode("utf-8", "replace") 2FcK m M k w a 7 , o G R H T O I s z A Q i e V j h p g 9 5 J U C f
425 leaf = candidate.rsplit(delimiter, 1)[-1] if delimiter else candidate 2FcK m M k w a 7 , o G R H T O I s z A Q i e V j h p g 9 5 J U C f
426 (named if leaf.lower() == kind else flagged).append(candidate) 2FcK m M k w a 7 , o G R H T O I s z A Q i e V j h p g 9 5 J U C f
427 if by_name is None and candidate.lower() in names: 2Fcv K E m M k w a 7 , o G R H T O I s z A Q i e V j h p g 9 5 J U C f
428 by_name = candidate 2FcK m M k w a 7 , o G R H T O I s z A Q i e V j h p g 9 5 J U C f
429 return named + flagged or ([by_name] if by_name else []) 2Fcv K E m M k w a 7 , o G R H T O I s z A Q i e V j h p g 9 5 J U C f
432def _special_folder(client: imaplib.IMAP4, kind: str) -> str | None:
433 """The one folder to store into or move to for a special-use role."""
434 return next(iter(_special_folders(client, kind)), None) 2Fcv K E m M k w o s z A Q i e V j h p g 9 5 J U C f
437def _decode_imap_utf7(value: str) -> str:
438 """A mailbox name from LIST, in modified UTF-7, as the Unicode it names."""
440 def decode(match: re.Match[str]) -> str: 20cYcZc@cSc1cFcP 1 Y v K E Z m B W : * M k w L # a n F 2 S ) 7 , N l [ . r u q y o x G _ R H T O I D s z A i e V j h p c g 5 J U C $ f
441 chunk = match.group(1) 20cYcZc@cSc1c
442 if not chunk: 20cYcZc@cSc1c
443 return "&" 20c
444 raw = chunk.replace(",", "/") 20cYcZc@cSc1c
445 raw += "=" * (-len(raw) % 4) 20cYcZc@cSc1c
446 try: 20cYcZc@cSc1c
447 return base64.b64decode(raw).decode("utf-16-be") 20cYcZc@cSc1c
448 except (ValueError, UnicodeDecodeError): 2@c
449 return match.group(0) 2@c
451 return re.sub(r"&([A-Za-z0-9+,]*)-", decode, value) 20cYcZc@cSc1cFcP 1 Y v K E Z m B W : * M k w L # a n F 2 S ) 7 , N l [ . r u q y o x G _ R H T O I D s z A i e V j h p c g 5 J U C $ f
454def _list_folders(client: imaplib.IMAP4) -> list[tuple[str, str]]:
455 """Each folder as (Unicode name, lowercased LIST attributes)."""
456 _, rows = client.list() 2Fca [ .
457 folders = [] 2Fca [ .
458 for folder_row in rows or []: 2Fca [ .
459 if not isinstance(folder_row, bytes): 2Fca [ .
460 continue 2Fc.
461 match = re.search( 2Fca [ .
462 rb'\((.*?)\)\s+(?:"(?:[^"]*)"|NIL)\s+("(?:[^"\\]|\\.)*"|[^\s]+)$',
463 folder_row,
464 )
465 if not match: 2Fca [ .
466 continue 2Fc.
467 wire = match.group(2).decode("utf-8", "replace").strip('"') 2Fca [ .
468 folders.append( 2Fca [ .
469 (_decode_imap_utf7(wire), match.group(1).decode("ascii", "replace").lower())
470 )
471 return folders 2Fca [ .
474def _resolve_folder(client: imaplib.IMAP4, folder: str) -> str:
475 """A folder name, with the special-use aliases looked up on this server."""
476 alias = folder.strip().lower() 2d FcM k w # a u q y o x
477 if alias == "inbox": 2d FcM k w # a u q y o x
478 return "INBOX" 1d#auqyox
479 if alias in FOLDER_ALIASES: 2FcM k w q o
480 found = _special_folder(client, alias) 2FcM k w o
481 # No special-use folder: the name may be a real folder all the same.
482 if found: 2FcM k w o
483 return _decode_imap_utf7(found) 2FcM k w o
484 return _clean_folder(folder) 2FcM q o
487def _clean_folder(folder: str) -> str:
488 if (
489 len(folder) > 255
490 or any(ord(character) < 32 for character in folder)
491 or "\x7f" in folder
492 ):
493 raise ServiceError("email.invalid_folder", "Folder name is invalid.", 400) 2!cq
494 return folder 2d bbcb0cYcZcSc1c!cFcP 1 Y v K E Z m B W : * M k w L # a n F 2 S ) 7 , N l [ . r u q y o x G _ R H T O I D s z A Q i e V j h p c g 9 5 J U C $ f
497def _imap_quote(value: str) -> str:
498 _clean_folder(value) 2d bbcb0cYcZcSc1c!cP 1 Y v K E Z m B W : * M k w L # a n F 2 S ) 7 , N l [ . r u q y o x G _ R H T O I D A i e j h p c g C $
499 # IMAP mailbox names use modified UTF-7 unless UTF8=ACCEPT is negotiated.
500 encoded: list[str] = [] 2d bbcb0cYcZcSc1c!cP 1 Y v K E Z m B W : * M k w L # a n F 2 S ) 7 , N l [ . r u q y o x G _ R H T O I D A i e j h p c g C $
501 non_ascii: list[str] = [] 2d bbcb0cYcZcSc1c!cP 1 Y v K E Z m B W : * M k w L # a n F 2 S ) 7 , N l [ . r u q y o x G _ R H T O I D A i e j h p c g C $
503 def flush() -> None: 2d bbcb0cYcZcSc1c!cP 1 Y v K E Z m B W : * M k w L # a n F 2 S ) 7 , N l [ . r u q y o x G _ R H T O I D A i e j h p c g C $
504 if non_ascii: 2d bbcb0cYcZcSc1c!cP 1 Y v K E Z m B W : * M k w L # a n F 2 S ) 7 , N l [ . r u q y o x G _ R H T O I D A i e j h p c g C $
505 raw = "".join(non_ascii).encode("utf-16-be") 2YcZcSc
506 encoded.append( 2YcZcSc
507 "&" + base64.b64encode(raw).decode().rstrip("=").replace("/", ",") + "-"
508 )
509 non_ascii.clear() 2YcZcSc
511 for character in value: 2d bbcb0cYcZcSc1c!cP 1 Y v K E Z m B W : * M k w L # a n F 2 S ) 7 , N l [ . r u q y o x G _ R H T O I D A i e j h p c g C $
512 if 0x20 <= ord(character) <= 0x7E: 2d bbcb0cYcZcSc1c!cP 1 Y v K E Z m B W : * M k w L # a n F 2 S ) 7 , N l [ . r u q y o x G _ R H T O I D A i e j h p c g C $
513 flush() 2d bbcb0cSc1c!cP 1 Y v K E Z m B W : * M k w L # a n F 2 S ) 7 , N l [ . r u q y o x G _ R H T O I D A i e j h p c g C $
514 encoded.append("&-" if character == "&" else character) 2d bbcb0cSc1c!cP 1 Y v K E Z m B W : * M k w L # a n F 2 S ) 7 , N l [ . r u q y o x G _ R H T O I D A i e j h p c g C $
515 else:
516 non_ascii.append(character) 2YcZcSc
517 flush() 2d bbcb0cYcZcSc1c!cP 1 Y v K E Z m B W : * M k w L # a n F 2 S ) 7 , N l [ . r u q y o x G _ R H T O I D A i e j h p c g C $
518 return _imap_raw_quote("".join(encoded)) 2d bbcb0cYcZcSc1c!cP 1 Y v K E Z m B W : * M k w L # a n F 2 S ) 7 , N l [ . r u q y o x G _ R H T O I D A i e j h p c g C $
521def _imap_raw_quote(value: str) -> str:
522 _clean_folder(value) 2d bbcb0cYcZcSc1c!cP 1 Y v K E Z m B W : * M k w L # a n F 2 S ) 7 , N l [ . r u q y o x G _ R H T O I D s z A Q i e V j h p c g 9 5 J U C $ f
523 return '"' + value.replace("\\", "\\\\").replace('"', '\\"') + '"' 2d bbcb0cYcZcSc1c!cP 1 Y v K E Z m B W : * M k w L # a n F 2 S ) 7 , N l [ . r u q y o x G _ R H T O I D s z A Q i e V j h p c g 9 5 J U C $ f
526def _b64(value: bytes) -> str:
527 return base64.urlsafe_b64encode(value).decode().rstrip("=") 2d bbcb#dP 1 Y v % ndK E Z m B W : * M k w L # a [c]c^c_c`cn F 2 S ) N l r u q y o x G _ R H T O I D A i e j h p c g 5 C $
530def _unb64(value: str) -> bytes:
531 try: 2ebd bbcb#dP 1 Y v % K E Z m B W : * M k w L # a od[c]c^c_c`cn F 2 S ) N l r pd/c%c'c{c:c;cqd|cG _ R H T O I D A i e j h p c g C $
532 return base64.urlsafe_b64decode(value + "=" * (-len(value) % 4)) 2ebd bbcb#dP 1 Y v % K E Z m B W : * M k w L # a od[c]c^c_c`cn F 2 S ) N l r pd/c%c'c{c:c;cqd|cG _ R H T O I D A i e j h p c g C $
533 except (ValueError, UnicodeDecodeError) as error: 2#d
534 raise ServiceError( 2#d
535 "email.invalid_id", "Email identifier is invalid.", 400
536 ) from error
539def _uidvalidity(client: imaplib.IMAP4) -> int | None:
540 """The selected folder's UIDVALIDITY, or None when the server gave no number."""
541 values = client.response("UIDVALIDITY")[1] 1dP1YvKEZmBW:*MkwL#anF2S)NlruqyoxG_RHTOIDAiejhpcgC$
542 value = values[0] if values else None 1dP1YvKEZmBW:*MkwL#anF2S)NlruqyoxG_RHTOIDAiejhpcgC$
543 return int(value) if isinstance(value, bytes) and value.isdigit() else None 1dP1YvKEZmBW:*MkwL#anF2S)NlruqyoxG_RHTOIDAiejhpcgC$
546def _parse_attachment_id(attachment_id: str) -> tuple[str, int]:
547 """The message and MIME part index an attachment identifier names."""
548 try: 2d a od[c]c^c_c`cn F l r D
549 kind, message_id, index = json.loads(_unb64(attachment_id)) 2d a od[c]c^c_c`cn F l r D
550 if (
551 kind != "attachment"
552 or not isinstance(message_id, str)
553 or not isinstance(index, int)
554 or isinstance(index, bool)
555 or index < 0
556 ):
557 raise ValueError 2od[c]c^c_c`cF
558 except (ValueError, TypeError, json.JSONDecodeError) as error: 2od[c]c^c_c`cn F
559 raise ServiceError( 2od[c]c^c_c`cn F
560 "email.invalid_attachment", "Attachment identifier is invalid.", 400
561 ) from error
562 return message_id, index 1danFlrD
565def _decode_header(value: str | None) -> str:
566 if not value: 2d bbcb5da n F S N l r u q y o x G H I D A i e j h p c g C
567 return "" 2d 5da n F S N l r u q y o x G H I D
568 try: 2d bbcb5da n F S N l r u q y o x G H I D A i e j h p c g C
569 return str(make_header(decode_header(value))) 2d bbcb5da n F S N l r u q y o x G H I D A i e j h p c g C
570 except (LookupError, UnicodeDecodeError, ValueError): 25d
571 return value 25d
574def _is_attachment(part: Message) -> bool:
575 disposition = part.get_content_disposition() 1danFSNlrDie
576 return disposition == "attachment" or ( 1danFSNlrDie
577 disposition != "inline" and bool(part.get_filename())
578 )
581_IMAP_QUOTED_STRING = rb'"(?:[^"\\]|\\.)*"'
582_IMAP_VALUE = re.compile(_IMAP_QUOTED_STRING + rb'|[()]|[^\s()"]+')
583_FETCH_START = re.compile(rb"^\d+ \(")
584_HEADER_LITERAL = re.compile(rb"BODY\[HEADER\.FIELDS \([^)]*\)\] \{\d+\}$", re.I)
585_LITERAL_MARKER = re.compile(rb"\{\d+\}$")
588def _bodystructure_has_attachment(metadata: bytes) -> bool | None:
589 """Read disposition and filename parameters from IMAP MIME metadata."""
590 start = re.search(rb"\bBODYSTRUCTURE\s+(?=\()", metadata, re.I) 2d TcUcVcPcIcWcKcJc7ca u q y o x
591 if not start: 2d TcUcVcPcIcWcKcJc7ca u q y o x
592 return None 27c
593 stack: list[list[Any]] = [] 2d TcUcVcPcIcWcKcJc7ca u q y o x
594 for match in _IMAP_VALUE.finditer(metadata, start.end()): 2d TcUcVcPcIcWcKcJc7ca u q y o x
595 token = match.group() 2d TcUcVcPcIcWcKcJc7ca u q y o x
596 if token == b"(": 2d TcUcVcPcIcWcKcJc7ca u q y o x
597 child: list[Any] = [] 2d TcUcVcPcIcWcKcJc7ca u q y o x
598 if stack: 2d TcUcVcPcIcWcKcJc7ca u q y o x
599 stack[-1].append(child) 2d TcUcVcPcIcWcKcJc7ca u q y o x
600 stack.append(child) 2d TcUcVcPcIcWcKcJc7ca u q y o x
601 if len(stack) > 100: 2d TcUcVcPcIcWcKcJc7ca u q y o x
602 return None 27c
603 elif token == b")": 2d TcUcVcPcIcWcKcJca u q y o x
604 body = stack.pop() 2d TcUcVcPcIcWcKcJca u q y o x
605 if not stack: 2d TcUcVcPcIcWcKcJca u q y o x
606 return _mime_structure_has_attachment(body) 2d TcUcVcPcIcWcKcJca u q y o x
607 else:
608 stack[-1].append(token.strip(b'"').upper()) 2d TcUcVcPcIcWcKcJca u q y o x
609 return None 27c
612def _mime_structure_has_attachment(body: list[Any]) -> bool:
613 if not body: 2d TcUcVcPcIcWcKcJc7ca u q y o x
614 return False 27c
615 if isinstance(body[0], list): 2d TcUcVcPcIcWcKcJca u q y o x
616 children = list(itertools.takewhile(lambda part: isinstance(part, list), body)) 2d IcKcJca u
617 params_index = len(children) + 1 2d IcKcJca u
618 disposition_index = params_index + 1 2d IcKcJca u
619 else:
620 media = tuple(body[:2]) 2d TcUcVcPcIcWcKcJca u q y o x
621 children = ( 2d TcUcVcPcIcWcKcJca u q y o x
622 body[8:9]
623 if media in {(b"MESSAGE", b"RFC822"), (b"MESSAGE", b"GLOBAL")}
624 else []
625 )
626 params_index = 2 2d TcUcVcPcIcWcKcJca u q y o x
627 # Single parts have seven base fields. Text adds a line count, and
628 # embedded messages add an envelope, body and line count before MD5.
629 disposition_index = 11 if children else 9 if body[0] == b"TEXT" else 8 2d TcUcVcPcIcWcKcJca u q y o x
630 disposition = next(iter(body[disposition_index:]), None) 2d TcUcVcPcIcWcKcJca u q y o x
631 if isinstance(disposition, list) and disposition: 2d TcUcVcPcIcWcKcJca u q y o x
632 if disposition[0] == b"ATTACHMENT": 2d VcPca u
633 return True 2d Vca u
634 params = next(iter(body[params_index:]), None) 2d TcUcPcIcWcKcJca u q y o x
635 if (
636 not (isinstance(disposition, list) and disposition[0:1] == [b"INLINE"])
637 and isinstance(params, list)
638 and any(
639 name == b"NAME" or isinstance(name, bytes) and name.startswith(b"NAME*")
640 for name in params[::2]
641 )
642 ):
643 return True 2TcUcIcJc
644 return any( 2d PcIcWcKcJca u q y o x
645 _mime_structure_has_attachment(child)
646 for child in children
647 if isinstance(child, list)
648 )
651def _fetch_search_page(
652 client: imaplib.IMAP4, uids: Sequence[int]
653) -> dict[int, tuple[bytes, bytes]]:
654 """Fetch a page of headers and MIME structures, keyed by returned UID."""
655 kind, data = client.uid( 2d Lca u q y o x
656 "fetch",
657 ",".join(map(str, uids)),
658 "(UID FLAGS RFC822.SIZE BODYSTRUCTURE BODY.PEEK[HEADER.FIELDS "
659 "(FROM TO CC SUBJECT DATE MESSAGE-ID)])",
660 )
661 if kind != "OK": 2d Lca u q y o x
662 return {} 2Lc
663 results: dict[int, tuple[bytes, bytes]] = {} 2d Lca u q y o x
664 metadata = bytearray() 2d Lca u q y o x
665 headers = None 2d Lca u q y o x
666 for entry in [*data, b"0 ("]: 2d Lca u q y o x
667 if entry is None: 2d Lca u q y o x
668 continue 2Lc
669 fragment = entry[0] if isinstance(entry, tuple) else entry 2d Lca u q y o x
670 if _FETCH_START.match(fragment): 2d Lca u q y o x
671 if headers is not None: 2d Lca u q y o x
672 attributes = re.sub(_IMAP_QUOTED_STRING, b'""', metadata) 2d Lca u q y o x
673 uid = re.search(rb"\bUID (\d+)", attributes, re.I) 2d Lca u q y o x
674 if uid: 674 ↛ 676line 674 didn't jump to line 676 because the condition on line 674 was always true2d Lca u q y o x
675 results[int(uid.group(1))] = (bytes(metadata), headers) 2d Lca u q y o x
676 metadata.clear() 2d Lca u q y o x
677 headers = None 2d Lca u q y o x
678 if isinstance(entry, tuple): 2d Lca u q y o x
679 if _HEADER_LITERAL.search(fragment): 2d Lca u q y o x
680 headers = entry[1] 2d Lca u q y o x
681 literal = b'""' 2d Lca u q y o x
682 else:
683 literal = ( 2Lc
684 b'"' + entry[1].replace(b"\\", b"\\\\").replace(b'"', b'\\"') + b'"'
685 )
686 marker = _LITERAL_MARKER.search(fragment) 2d Lca u q y o x
687 if marker: 2d Lca u q y o x
688 fragment = fragment[: marker.start()] + literal 2d Lca u q y o x
689 metadata.extend(fragment) 2d Lca u q y o x
690 return results 2d Lca u q y o x
693def _part_payload(part: Message) -> bytes:
694 payload = part.get_payload(decode=True) 2/ = Acd sctca n F l r D i e
695 return payload if isinstance(payload, bytes) else b"" 2/ = Acd sctca n F l r D i e
698def _part_text(part: Message) -> str:
699 """A text part's content, decoded leniently.
701 Senders name charsets Python has never heard of; the words in the message
702 are still worth returning, so those fall back to UTF-8.
703 """
704 payload = _part_payload(part) 2/ = Acsctcn l r
705 try: 2/ = Acsctcn l r
706 return payload.decode(part.get_content_charset() or "utf-8", "replace") 2/ = Acsctcn l r
707 except LookupError: 2sctcr
708 return payload.decode("utf-8", "replace") 2sctcr
711def _append_imap_message(
712 client: imaplib.IMAP4, folder: str, message: EmailMessage, flags: str
713) -> tuple[str, list[bytes | None]]:
714 # imaplib returns the status and response data, though typeshed says str.
715 return cast( 1szAQieVjhpg95JUCf
716 tuple[str, list[bytes | None]],
717 client.append(
718 _imap_raw_quote(folder),
719 flags,
720 imaplib.Time2Internaldate(time.time()),
721 message.as_bytes(policy=OUTBOUND_POLICY),
722 ),
723 )
726def _email_text(message: EmailMessage, *, html_body: bool = False) -> str:
727 chunks: list[str] = [] 2d sctca n F 2 S N l r D i e h p c g
728 wanted = "html" if html_body else "plain" 2d sctca n F 2 S N l r D i e h p c g
729 parts = message.walk() if message.is_multipart() else [message] 2d sctca n F 2 S N l r D i e h p c g
730 for part in parts: 2d sctca n F 2 S N l r D i e h p c g
731 if part.get_content_maintype() == "multipart": 2d sctca n F 2 S N l r D i e h p c g
732 continue 1danF2lrDie
733 if part.get_content_disposition() == "attachment" or part.get_filename(): 2d sctca n F 2 S N l r D i e h p c g
734 continue 1danFlrDie
735 if part.get_content_type() != f"text/{wanted}": 2d sctca n F 2 S N l r D i e h p c g
736 continue 1danF2SNlrDi
737 try: 2d sctca n F 2 S N l r D i e h p c g
738 content = cast(EmailMessage, part).get_content() 2d sctca n F 2 S N l r D i e h p c g
739 except (LookupError, UnicodeDecodeError, email.errors.MessageError): 2sctcr
740 content = _part_text(part) 2sctcr
741 if isinstance(content, str): 741 ↛ 730line 741 didn't jump to line 730 because the condition on line 741 was always true2d sctca n F 2 S N l r D i e h p c g
742 chunks.append(content) 2d sctca n F 2 S N l r D i e h p c g
743 return "\n".join(chunks) 2d sctca n F 2 S N l r D i e h p c g
746class _TextOfHTML(HTMLParser):
747 """Readable text from an HTML body: block breaks kept, scripts dropped."""
749 BLOCKS = {"p", "div", "br", "li", "tr", "h1", "h2", "h3", "h4", "table"}
751 def __init__(self) -> None:
752 super().__init__(convert_charrefs=True) 2#cn N r
753 self.chunks: list[str] = [] 2#cn N r
754 self.hidden = 0 2#cn N r
756 def handle_starttag(self, tag: str, attrs: Any) -> None:
757 if tag in {"script", "style", "head"}: 2#cn N r
758 self.hidden += 1 2#cN
759 elif tag in self.BLOCKS: 2#cn N r
760 self.chunks.append("\n") 2#cn N r
762 def handle_endtag(self, tag: str) -> None:
763 if tag in {"script", "style", "head"} and self.hidden: 2#cn N r
764 self.hidden -= 1 2#cN
766 def handle_data(self, data: str) -> None:
767 if not self.hidden: 2#cn N r
768 self.chunks.append(data) 2#cn N r
771def html_to_text(html: str) -> str:
772 parser = _TextOfHTML() 2#cn N r
773 parser.feed(html) 2#cn N r
774 text = "".join(parser.chunks) 2#cn N r
775 return re.sub(r"\n\s*\n+", "\n\n", re.sub(r"[ \t]+", " ", text)).strip() 2#cn N r
778_ICS_ESCAPE = re.compile(r"\\(.)", re.DOTALL)
779_ICS_CONTROL = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]")
782def _ics_unescape(match: re.Match[str]) -> str:
783 """One escape sequence of an iCalendar TEXT value (RFC 5545 section 3.3.11)."""
784 return "\n" if match.group(1) in "nN" else match.group(1) 2Hc/ Gc
787def _ics_text(value: str) -> str:
788 """Escape untrusted text for an iCalendar TEXT value.
790 Backslash goes first so the escapes added after it are not doubled, and line
791 breaks become escaped newlines so a value can never start a new content line.
792 """
793 escaped = value.replace("\\", "\\\\").replace(";", "\\;").replace(",", "\\,") 2)d*d+d,d-d.d/ =
794 escaped = escaped.replace("\r\n", "\\n").replace("\r", "\\n") 2)d*d+d,d-d.d/ =
795 return _ICS_CONTROL.sub("", escaped.replace("\n", "\\n")) 2)d*d+d,d-d.d/ =
798def _ics_param(value: str) -> str:
799 """A property parameter value that cannot end the parameter or the line."""
800 cleaned = _ICS_CONTROL.sub("", " ".join(value.split())).replace('"', "'") 2`d{d|d}d/ =
801 return f'"{cleaned}"' if any(char in cleaned for char in ";:,") else cleaned 2`d{d|d}d/ =
804def _unfold_ics(text: str) -> list[str]:
805 lines: list[str] = [] 2Hc/ = AcGcsctcl
806 for line in text.replace("\r\n", "\n").split("\n"): 2Hc/ = AcGcsctcl
807 if line[:1] in {" ", "\t"} and lines: 2Hc/ = AcGcsctcl
808 lines[-1] += line[1:] 2Gc
809 elif line: 2Hc/ = AcGcsctcl
810 lines.append(line) 2Hc/ = AcGcsctcl
811 return lines 2Hc/ = AcGcsctcl
814def parse_calendar(text: str) -> list[dict[str, Any]]:
815 """The events in an iCalendar part: what an invitation asks of you."""
816 method = None 2Hc/ = AcGcsctcl
817 events: list[dict[str, Any]] = [] 2Hc/ = AcGcsctcl
818 current: dict[str, Any] | None = None 2Hc/ = AcGcsctcl
819 for line in _unfold_ics(text): 2Hc/ = AcGcsctcl
820 name, _, value = line.partition(":") 2Hc/ = AcGcsctcl
821 key, *params = name.split(";") 2Hc/ = AcGcsctcl
822 key = key.upper() 2Hc/ = AcGcsctcl
823 if key == "METHOD": 2Hc/ = AcGcsctcl
824 method = value.strip().upper() 2Hc/ = AcGcl
825 elif key == "BEGIN" and value.strip().upper() == "VEVENT": 2Hc/ = AcGcsctcl
826 current = {"attendees": []} 2Hc/ = AcGcsctcl
827 elif key == "END" and value.strip().upper() == "VEVENT" and current is not None: 2Hc/ = AcGcsctcl
828 events.append(current) 2Hc/ = AcGcsctcl
829 current = None 2Hc/ = AcGcsctcl
830 elif current is not None: 2Hc/ = AcGcsctcl
831 unescaped = _ICS_ESCAPE.sub(_ics_unescape, value) 2Hc/ = AcGcsctcl
832 field = { 2Hc/ = AcGcsctcl
833 "UID": "uid",
834 "SUMMARY": "summary",
835 "DTSTART": "starts_at",
836 "DTEND": "ends_at",
837 "LOCATION": "location",
838 "DESCRIPTION": "description",
839 "SEQUENCE": "sequence",
840 "STATUS": "status",
841 }.get(key)
842 if field: 2Hc/ = AcGcsctcl
843 current[field] = unescaped 2Hc/ = AcGcsctcl
844 tzid = next( 2Hc/ = AcGcsctcl
845 (
846 p.split("=", 1)[1]
847 for p in params
848 if p.upper().startswith("TZID=")
849 ),
850 None,
851 )
852 if tzid and field in {"starts_at", "ends_at"}: 2Hc/ = AcGcsctcl
853 current["timezone"] = tzid 2Gc
854 elif key == "ORGANIZER": 2Hc/ = AcGcl
855 current["organizer"] = value.removeprefix("mailto:").removeprefix( 2Hc/ = AcGcl
856 "MAILTO:"
857 )
858 elif key == "ATTENDEE": 2/ Gc
859 current["attendees"].append( 2/ Gc
860 value.removeprefix("mailto:").removeprefix("MAILTO:")
861 )
862 return [{**event, "method": method} for event in events] 2Hc/ = AcGcsctcl
865def _calendar_parts(message: email.message.Message) -> list[dict[str, Any]]:
866 invites: list[dict[str, Any]] = [] 2/ = Acd sctca n F 2 S N l r D
867 for part in message.walk(): 2/ = Acd sctca n F 2 S N l r D
868 if part.get_content_type() != "text/calendar": 2/ = Acd sctca n F 2 S N l r D
869 continue 2/ = Acd a n F 2 S N l r D
870 invites.extend(parse_calendar(_part_text(part))) 2/ = Acsctcl
871 return invites 2/ = Acd sctca n F 2 S N l r D
874# Providers whose SMTP service files the sent message itself; appending
875# another copy over IMAP would leave two in Sent.
876AUTO_SENT_HOSTS = (
877 "gmail.com",
878 "googlemail.com",
879 "office365.com",
880 "outlook.com",
881 "live.com",
882)
885def _auto_saves_sent(smtp_host: str) -> bool:
886 host = smtp_host.lower().rstrip(".") 1szAQieVjhgUC0f
887 return any( 1szAQieVjhgUC0f
888 host == domain or host.endswith("." + domain) for domain in AUTO_SENT_HOSTS
889 )
892def _summary(
893 message: email.message.Message, message_id: str, flags: bytes
894) -> dict[str, Any]:
895 return { 1danFSNlruqyoxGHID
896 "message_id": message_id,
897 "from": _decode_header(message.get("From")),
898 "to": _decode_header(message.get("To")),
899 "cc": _decode_header(message.get("Cc")),
900 "subject": _decode_header(message.get("Subject")),
901 "date": message.get("Date"),
902 "unread": b"\\Seen" not in flags,
903 }
906def _server_ips(host: str, port: int) -> list[str]:
907 host = host.strip().rstrip(".") 2xdrd/d:d;d=d?d@d6d
908 if not host or any(character in host for character in "/\\@\r\n\t "): 2xdrd/d:d;d=d?d@d6d
909 raise ServiceError("email.invalid_host", "Mail server address is invalid.", 400) 2/d:d;d=d?d@d
910 try: 2xdrd6d
911 answers = socket.getaddrinfo(host, port, type=socket.SOCK_STREAM) 2xdrd6d
912 except OSError as error: 26d
913 raise ServiceError( 26d
914 "email.connection_failed", "Mail server could not be reached.", 502
915 ) from error
916 addresses = list(dict.fromkeys(str(answer[4][0]) for answer in answers)) 2xdrd
917 if not addresses or any( 2xdrd
918 not ipaddress.ip_address(value).is_global for value in addresses
919 ):
920 raise ServiceError( 2xdrd
921 "email.invalid_host", "Mail servers must resolve to public addresses.", 400
922 )
923 return addresses 2rd
926class _PinnedIMAP(imaplib.IMAP4):
927 def __init__(self, host: str, port: int, address: str, use_ssl: bool) -> None:
928 self._pinned_address = address 28c
929 self._use_ssl = use_ssl 28c
930 self.ssl_context = ssl.create_default_context() 28c
931 super().__init__(host=host, port=port, timeout=15) 28c
933 def _create_socket(self, timeout: float | None) -> socket.socket:
934 raw = socket.create_connection((self._pinned_address, self.port), timeout) 28c
935 if self._use_ssl: 28c
936 return self.ssl_context.wrap_socket(raw, server_hostname=self.host) 28c
937 return raw 28c
940class _PinnedSMTP(smtplib.SMTP):
941 def __init__(self, host: str, port: int, address: str, use_ssl: bool) -> None:
942 self._pinned_address = address 28c
943 self._use_ssl = use_ssl 28c
944 self.context = ssl.create_default_context() 28c
945 super().__init__(host=host, port=port, timeout=15) 28c
947 def _get_socket(self, host: str, port: int, timeout: float | None) -> socket.socket:
948 raw = socket.create_connection((self._pinned_address, port), timeout) 28c
949 if self._use_ssl: 28c
950 return self.context.wrap_socket(raw, server_hostname=host) 28c
951 return raw 28c
954def _delivery_error(error: Exception) -> ServiceError:
955 """Keep actionable SMTP status without exposing server-supplied mail data."""
956 stage = "connection" 2Qc5cMcXcNc3cRct 6 '
957 responses: list[tuple[int, bytes | str]] = [] 2Qc5cMcXcNc3cRct 6 '
958 if isinstance(error, smtplib.SMTPRecipientsRefused): 2Qc5cMcXcNc3cRct 6 '
959 stage = "recipients" 2QcRc
960 responses = list(error.recipients.values()) 2QcRc
961 elif isinstance(error, smtplib.SMTPResponseException): 25cMcXcNc3ct 6 '
962 stage = ( 2McXcNct 6
963 "sender"
964 if isinstance(error, smtplib.SMTPSenderRefused)
965 else "content"
966 if isinstance(error, smtplib.SMTPDataError)
967 else "connection"
968 )
969 responses = [(error.smtp_code, error.smtp_error)] 2McXcNct 6
970 elif isinstance(error, smtplib.SMTPNotSupportedError): 25c3c'
971 stage = "content" 23c
973 rejected = isinstance( 2Qc5cMcXcNc3cRct 6 '
974 error,
975 (
976 smtplib.SMTPResponseException,
977 smtplib.SMTPRecipientsRefused,
978 smtplib.SMTPNotSupportedError,
979 ),
980 )
981 details: dict[str, Any] = { 2Qc5cMcXcNc3cRct 6 '
982 "smtp_stage": stage,
983 "delivery_status": "rejected" if rejected else "unknown",
984 }
985 codes = [] 2Qc5cMcXcNc3cRct 6 '
986 # Compare only sanitized status fields. Reply prose often differs for each
987 # recipient and must neither hide a shared code nor expose a Bcc address.
988 smtp_codes = {code for code, _ in responses} 2Qc5cMcXcNc3cRct 6 '
989 if len(smtp_codes) == 1: 2Qc5cMcXcNc3cRct 6 '
990 code = smtp_codes.pop() 2QcMcXcNcRct 6
991 details["smtp_code"] = code 2QcMcXcNcRct 6
992 codes.append(f"SMTP {code}") 2QcMcXcNcRct 6
993 enhanced_statuses = set() 2Qc5cMcXcNc3cRct 6 '
994 for _, reply in responses: 2Qc5cMcXcNc3cRct 6 '
995 reply_text = ( 2QcMcXcNcRct 6
996 reply.decode("ascii", errors="replace")
997 if isinstance(reply, bytes)
998 else reply
999 )
1000 enhanced = re.match(r"\s*([245]\.\d{1,3}\.\d{1,3})(?:\s|$)", reply_text) 2QcMcXcNcRct 6
1001 enhanced_statuses.add(enhanced.group(1) if enhanced else None) 2QcMcXcNcRct 6
1002 if len(enhanced_statuses) == 1 and (enhanced_status := enhanced_statuses.pop()): 2Qc5cMcXcNc3cRct 6 '
1003 details["enhanced_status"] = enhanced_status 2QcMcNcRct 6
1004 codes.append(enhanced_status) 2QcMcNcRct 6
1005 if rejected: 2Qc5cMcXcNc3cRct 6 '
1006 message = { 2QcMcXcNc3cRct 6
1007 "sender": "The SMTP server rejected the sender address.",
1008 "recipients": "The SMTP server rejected the recipients.",
1009 "content": "The SMTP server rejected the message content or format.",
1010 "connection": "The SMTP server rejected the connection.",
1011 }[stage]
1012 if codes: 2QcMcXcNc3cRct 6
1013 message = f"{message[:-1]} ({', '.join(codes)})." 2QcMcXcNcRct 6
1014 else:
1015 message = ( 25c'
1016 "The SMTP connection was interrupted and delivery could not be confirmed. "
1017 "Check Sent before retrying to avoid a duplicate."
1018 )
1019 logger.warning( 2Qc5cMcXcNc3cRct 6 '
1020 "SMTP delivery failed: stage=%s delivery_status=%s smtp_code=%s enhanced_status=%s",
1021 stage,
1022 details["delivery_status"],
1023 details.get("smtp_code"),
1024 details.get("enhanced_status"),
1025 )
1026 return ServiceError("email.send_failed", message, 502, details=details) 2Qc5cMcXcNc3cRct 6 '
1029class EmailAccounts:
1030 """Workspace-scoped IMAP/SMTP adapter backed by encrypted vault entries."""
1032 ACCOUNT_PROVIDER = EMAIL_ACCOUNT_CREDENTIAL_PROVIDER
1033 SCHEDULE_PROVIDER = "orcheo-email-schedule"
1034 IDEMPOTENCY_PROVIDER = "orcheo-email-idempotency"
1036 def __init__(
1037 self, vault: BaseCredentialVault, workspace_id: str, *, actor: str = "mcp"
1038 ) -> None:
1039 self.vault = vault 2gbydhbOc3 X eb~ zdAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdgdQdRdSdTdUdVdWdXdYdmbnbobv % pbqbE rbm sbB tbubvbwbxbk w L ybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUbVbWbXbYbZb0b1b2b3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcc gchcicJ jckclc0 mcncZdf
1040 self.workspace_id = str(workspace_id) 2gbydhbOc3 X eb~ zdAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdgdQdRdSdTdUdVdWdXdYdmbnbobv % pbqbE rbm sbB tbubvbwbxbk w L ybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUbVbWbXbYbZb0b1b2b3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcc gchcicJ jckclc0 mcncZdf
1041 self.actor = actor 2gbydhbOc3 X eb~ zdAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdgdQdRdSdTdUdVdWdXdYdmbnbobv % pbqbE rbm sbB tbubvbwbxbk w L ybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUbVbWbXbYbZb0b1b2b3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcc gchcicJ jckclc0 mcncZdf
1042 try: 2gbydhbOc3 X eb~ zdAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdgdQdRdSdTdUdVdWdXdYdmbnbobv % pbqbE rbm sbB tbubvbwbxbk w L ybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUbVbWbXbYbZb0b1b2b3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcc gchcicJ jckclc0 mcncZdf
1043 workspace_uuid = uuid.UUID(self.workspace_id) 2gbydhbOc3 X eb~ zdAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdgdQdRdSdTdUdVdWdXdYdmbnbobv % pbqbE rbm sbB tbubvbwbxbk w L ybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUbVbWbXbYbZb0b1b2b3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcc gchcicJ jckclc0 mcncZdf
1044 except ValueError as error: 2gd
1045 raise ServiceError( 2gd
1046 "email.workspace_unavailable", "The active workspace is invalid.", 503
1047 ) from error
1048 self.workspace_uuid = workspace_uuid 2gbydhbOc3 X eb~ zdAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdgdQdRdSdTdUdVdWdXdYdmbnbobv % pbqbE rbm sbB tbubvbwbxbk w L ybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUbVbWbXbYbZb0b1b2b3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcc gchcicJ jckclc0 mcncZdf
1049 self.context = CredentialAccessContext( 2gbydhbOc3 X eb~ zdAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdgdQdRdSdTdUdVdWdXdYdmbnbobv % pbqbE rbm sbB tbubvbwbxbk w L ybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUbVbWbXbYbZb0b1b2b3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcc gchcicJ jckclc0 mcncZdf
1050 workspace_id=workspace_uuid, roles=[EMAIL_CREDENTIAL_ROLE]
1051 )
1053 def _metadata(self, provider: str) -> list[CredentialMetadata]:
1054 return [ 2gbhbOc3 X eb~ - 8 4 + lb{ rcqc] @ ` fbkb; dbhd0d| yc} d bbcbP mb1 nbY obv % pbK qbE Z rbm sbB tbW ub: vb* wbM xbk w L # yba zbAbBbCbDbEbFbn GbF Hb2 IbS Jb) Kb7 Lb, MbN Nbl Ob[ Pb. Qbr RbSbTbUbVbWbXbYbZb0bu 1bq 2by 3bo 4bx 5bG 6b_ 7bR 8bH 9bT !bO #bI $bD %b! 'bib(bt )b^ *boc+bs ,b( -bjb.buc/bpc:bvc;bwc=bEc?bz @b? [bDc]bA ^bQ _bab`bzc{bBc|bi }be ~bxcacCcbcV ccj dch ecp fcc g gc9 hc5 icJ U jcC kc$ lc0 6 mc' ncf
1055 item
1056 for item in self.vault.list_credentials(
1057 context=self.context, workspace_id=self.workspace_id
1058 )
1059 if item.workspace_id == self.workspace_id
1060 and item.provider == provider
1061 and item.template_id is None
1062 ]
1064 def _secret(self, metadata: CredentialMetadata) -> dict[str, Any]:
1065 try: 2gbhb3 X ~ - 8 4 + lb{ rcqc] @ ` fbkb; dbhd0d| yc} d bbcbP mb1 nbY obv % pbK qbE Z rbm sbB tbW ub: vb* wbM xbk w L # yba zbAbBbCbDbEbFbn GbF Hb2 IbS Jb) Kb7 Lb, MbN Nbl Ob[ Pb. Qbr RbSbTbUbVbWbXbYbZb0bu 1bq 2by 3bo 4bx 5bG 6b_ 7bR 8bH 9bT !bO #bI $bD %b! 'bib(bt )b^ *boc+bs ,b( -bjb.buc/bpc:bvc;bwc=bEc?bz @b? [bDc]bA ^bQ _bab`bzc{bBc|bi }be ~bxcacCcbcV ccj dch ecp fcc g gc9 hc5 icJ U jcC kc$ lc0 6 mc' ncf
1066 parsed = json.loads(metadata.reveal(cipher=self.vault.cipher)) 2gbhb3 X ~ - 8 4 + lb{ rcqc] @ ` fbkb; dbhd0d| yc} d bbcbP mb1 nbY obv % pbK qbE Z rbm sbB tbW ub: vb* wbM xbk w L # yba zbAbBbCbDbEbFbn GbF Hb2 IbS Jb) Kb7 Lb, MbN Nbl Ob[ Pb. Qbr RbSbTbUbVbWbXbYbZb0bu 1bq 2by 3bo 4bx 5bG 6b_ 7bR 8bH 9bT !bO #bI $bD %b! 'bib(bt )b^ *boc+bs ,b( -bjb.buc/bpc:bvc;bwc=bEc?bz @b? [bDc]bA ^bQ _bab`bzc{bBc|bi }be ~bxcacCcbcV ccj dch ecp fcc g gc9 hc5 icJ U jcC kc$ lc0 6 mc' ncf
1067 if not isinstance(parsed, dict): 2gbhb3 X ~ - 8 4 + lb{ rcqc] @ ` fbkb; dbhd| yc} d bbcbP mb1 nbY obv % pbK qbE Z rbm sbB tbW ub: vb* wbM xbk w L # yba zbAbBbCbDbEbFbn GbF Hb2 IbS Jb) Kb7 Lb, MbN Nbl Ob[ Pb. Qbr RbSbTbUbVbWbXbYbZb0bu 1bq 2by 3bo 4bx 5bG 6b_ 7bR 8bH 9bT !bO #bI $bD %b! 'bib(bt )b^ *boc+bs ,b( -bjb.buc/bpc:bvc;bwc=bEc?bz @b? [bDc]bA ^bQ _bab`bzc{bBc|bi }be ~bxcacCcbcV ccj dch ecp fcc g gc9 hc5 icJ U jcC kc$ lc0 6 mc' ncf
1068 raise ValueError("not an object") 2hd
1069 return parsed 2gbhb3 X ~ - 8 4 + lb{ rcqc] @ ` fbkb; db| yc} d bbcbP mb1 nbY obv % pbK qbE Z rbm sbB tbW ub: vb* wbM xbk w L # yba zbAbBbCbDbEbFbn GbF Hb2 IbS Jb) Kb7 Lb, MbN Nbl Ob[ Pb. Qbr RbSbTbUbVbWbXbYbZb0bu 1bq 2by 3bo 4bx 5bG 6b_ 7bR 8bH 9bT !bO #bI $bD %b! 'bib(bt )b^ *boc+bs ,b( -bjb.buc/bpc:bvc;bwc=bEc?bz @b? [bDc]bA ^bQ _bab`bzc{bBc|bi }be ~bxcacCcbcV ccj dch ecp fcc g gc9 hc5 icJ U jcC kc$ lc0 6 mc' ncf
1070 except (CredentialNotFoundError, ValueError, TypeError) as error: 2hd0d
1071 raise ServiceError( 2hd0d
1072 "email.credential_unavailable",
1073 "Stored email settings are unavailable. Re-enter them in the vault.",
1074 503,
1075 ) from error
1077 @staticmethod
1078 def _row_from(
1079 metadata: CredentialMetadata, config: dict[str, Any]
1080 ) -> dict[str, Any]:
1081 imap = config.get("imap") or {} 2gbhb3 X ~ - 8 4 + lb{ rcqc] @ ` fbkb; db| } d bbcbP mb1 nbY obv % pbK qbE Z rbm sbB tbW ub: vb* wbM xbk w L # yba zbAbBbCbDbEbFbn GbF Hb2 IbS Jb) Kb7 Lb, MbN Nbl Ob[ Pb. Qbr RbSbTbUbVbWbXbYbZb0bu 1bq 2by 3bo 4bx 5bG 6b_ 7bR 8bH 9bT !bO #bI $bD %b! 'bib(bt )b^ *boc+bs ,b( -bjb.b/b:b;b=bEc?bz @b? [b]bA ^bQ _bab`bzc{b|bi }be ~bacbcV ccj dch ecp fcc g gc9 hc5 icJ U jcC kc$ lc0 6 mc' ncf
1082 smtp = config.get("smtp") or {} 2gbhb3 X ~ - 8 4 + lb{ rcqc] @ ` fbkb; db| } d bbcbP mb1 nbY obv % pbK qbE Z rbm sbB tbW ub: vb* wbM xbk w L # yba zbAbBbCbDbEbFbn GbF Hb2 IbS Jb) Kb7 Lb, MbN Nbl Ob[ Pb. Qbr RbSbTbUbVbWbXbYbZb0bu 1bq 2by 3bo 4bx 5bG 6b_ 7bR 8bH 9bT !bO #bI $bD %b! 'bib(bt )b^ *boc+bs ,b( -bjb.b/b:b;b=bEc?bz @b? [b]bA ^bQ _bab`bzc{b|bi }be ~bacbcV ccj dch ecp fcc g gc9 hc5 icJ U jcC kc$ lc0 6 mc' ncf
1083 return { 2gbhb3 X ~ - 8 4 + lb{ rcqc] @ ` fbkb; db| } d bbcbP mb1 nbY obv % pbK qbE Z rbm sbB tbW ub: vb* wbM xbk w L # yba zbAbBbCbDbEbFbn GbF Hb2 IbS Jb) Kb7 Lb, MbN Nbl Ob[ Pb. Qbr RbSbTbUbVbWbXbYbZb0bu 1bq 2by 3bo 4bx 5bG 6b_ 7bR 8bH 9bT !bO #bI $bD %b! 'bib(bt )b^ *boc+bs ,b( -bjb.b/b:b;b=bEc?bz @b? [b]bA ^bQ _bab`bzc{b|bi }be ~bacbcV ccj dch ecp fcc g gc9 hc5 icJ U jcC kc$ lc0 6 mc' ncf
1084 "id": str(metadata.id),
1085 "created_at": metadata.created_at.isoformat(),
1086 "display_name": config.get("display_name") or metadata.name,
1087 "email_address": config.get("email_address") or "",
1088 "labels_json": config.get("labels") or [],
1089 "is_default": bool(config.get("is_default")),
1090 "enabled": bool(config.get("enabled", True)),
1091 "imap_host": imap.get("host", ""),
1092 "imap_port": int(imap.get("port", 993)),
1093 "imap_security": imap.get("security", "ssl"),
1094 "imap_username": imap.get("username", ""),
1095 "imap_secret": imap.get("password", ""),
1096 "imap_status": config.get("imap_status", "not-tested"),
1097 "imap_tested_at": config.get("imap_tested_at"),
1098 "smtp_host": smtp.get("host", ""),
1099 "smtp_port": int(smtp.get("port", 465)),
1100 "smtp_security": smtp.get("security", "ssl"),
1101 "smtp_username": smtp.get("username", ""),
1102 "smtp_secret": smtp.get("password", ""),
1103 "smtp_status": config.get("smtp_status", "not-tested"),
1104 "smtp_tested_at": config.get("smtp_tested_at"),
1105 "signature_text": config.get("signature_text", ""),
1106 "save_sent_copy": bool(config.get("save_sent_copy", True)),
1107 "_credential": metadata,
1108 "_config": config,
1109 }
1111 def _all_rows(self) -> list[dict[str, Any]]:
1112 return [ 2gbhbOc3 X eb~ - 8 4 + lb{ rcqc] @ ` fbkb; dbhd0dmbnbobv % pbqbE rbm sbB tbubvbwbxbk w L # yba zbAbBbCbDbEbFbGbHbIbJbKb7 Lb, MbNbOb[ Pb. QbRbSbTbUbVbWbXbYbZb0bu 1bq 2by 3bo 4bx 5b6b7b8b9b!b#b$b%b! 'bib(bt )b^ *boc+bs ,b( -bjb.b/b:b;b=bEc?bz @b? [b]b^bQ _bab`bzc{b|b}b~bacbcV ccj dch ecp fcc g gc9 hc5 icJ U jckclc0 6 mc' ncf
1113 self._row_from(item, self._secret(item))
1114 for item in self._metadata(self.ACCOUNT_PROVIDER)
1115 ]
1117 def _row(self, actor_id: str, account_id: str) -> dict[str, Any]:
1118 del actor_id # The vault's workspace and credential scope are authoritative. 2gbhb3 X ~ - 8 4 + lb{ rcqc] @ ` fbkb; db| } d bbcbP mb1 nbY obv % pbK qbE Z rbm sbB tbW ub: vb* wbM xbk w L # yba zbAbBbCbDbEbFbn GbF Hb2 IbS Jb) Kb7 LbMbN Nbl ObPb. Qbr RbSbTbUbVbWbXbYbZb0b1b2b3b4b5bG 6b_ 7bR 8bH 9bT !bO #bI $bD %b! 'b(bt )b*b+bs ,b-b.b/b:b;b=b?bz @b[b]bA ^b_b`b{b|bi }be ~bacbcccj dch ecp fcc g gchcicJ jcC kc$ lc0 mcncf
1119 try: 2gbhb3 X ~ - 8 4 + lb{ rcqc] @ ` fbkb; db| } d bbcbP mb1 nbY obv % pbK qbE Z rbm sbB tbW ub: vb* wbM xbk w L # yba zbAbBbCbDbEbFbn GbF Hb2 IbS Jb) Kb7 LbMbN Nbl ObPb. Qbr RbSbTbUbVbWbXbYbZb0b1b2b3b4b5bG 6b_ 7bR 8bH 9bT !bO #bI $bD %b! 'b(bt )b*b+bs ,b-b.b/b:b;b=b?bz @b[b]bA ^b_b`b{b|bi }be ~bacbcccj dch ecp fcc g gchcicJ jcC kc$ lc0 mcncf
1120 metadata = next( 2gbhb3 X ~ - 8 4 + lb{ rcqc] @ ` fbkb; db| } d bbcbP mb1 nbY obv % pbK qbE Z rbm sbB tbW ub: vb* wbM xbk w L # yba zbAbBbCbDbEbFbn GbF Hb2 IbS Jb) Kb7 LbMbN Nbl ObPb. Qbr RbSbTbUbVbWbXbYbZb0b1b2b3b4b5bG 6b_ 7bR 8bH 9bT !bO #bI $bD %b! 'b(bt )b*b+bs ,b-b.b/b:b;b=b?bz @b[b]bA ^b_b`b{b|bi }be ~bacbcccj dch ecp fcc g gchcicJ jcC kc$ lc0 mcncf
1121 item
1122 for item in self._metadata(self.ACCOUNT_PROVIDER)
1123 if str(item.id) == account_id
1124 )
1125 except StopIteration as error: 1~-{!
1126 raise ServiceError( 1~-{!
1127 "email.account_not_found", "Email account not found.", 404
1128 ) from error
1129 return self._row_from(metadata, self._secret(metadata)) 2gbhb3 X ~ - 8 4 + lb{ rcqc] @ ` fbkb; db| } d bbcbP mb1 nbY obv % pbK qbE Z rbm sbB tbW ub: vb* wbM xbk w L # yba zbAbBbCbDbEbFbn GbF Hb2 IbS Jb) Kb7 LbMbN Nbl ObPb. Qbr RbSbTbUbVbWbXbYbZb0b1b2b3b4b5bG 6b_ 7bR 8bH 9bT !bO #bI $bD %b! 'b(bt )b*b+bs ,b-b.b/b:b;b=b?bz @b[b]bA ^b_b`b{b|bi }be ~bacbcccj dch ecp fcc g gchcicJ jcC kc$ lc0 mcncf
1131 def _write(self, row: dict[str, Any], config: dict[str, Any]) -> None:
1132 self.vault.update_credential( 2gbhb3 X ~ - 8 4 + lb{ rcqc] @ ` fbkb; dbmbnbobv % pbqbE rbm sbB tbubvbwbxbk w L ybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUbVbWbXbYbZb0b1b2b3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcc gchcicJ jckclc0 mcncf
1133 credential_id=row["_credential"].id,
1134 actor=self.actor,
1135 secret=json.dumps(config, separators=(",", ":")),
1136 context=self.context,
1137 )
1139 def _account_result(self, row: dict[str, Any]) -> dict[str, Any]:
1140 return { 2gbhb3 X ~ - 8 4 + lb{ rcqc] @ ` fbkb; dbmbnbobv % pbqbE rbm sbB tbubvbwbxbk w L ybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUbVbWbXbYbZb0b1b2b3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcc gchcicJ jckclc0 mcncf
1141 "account_id": row["id"],
1142 "display_name": row["display_name"],
1143 "email_address": row["email_address"],
1144 "labels": row["labels_json"],
1145 "is_default": bool(row["is_default"]),
1146 "enabled": bool(row["enabled"]),
1147 "signature_text": row["signature_text"],
1148 "save_sent_copy": bool(row["save_sent_copy"]),
1149 "imap": {
1150 "host": row["imap_host"],
1151 "port": row["imap_port"],
1152 "security": row["imap_security"],
1153 "username": row["imap_username"],
1154 "status": row["imap_status"],
1155 "tested_at": row["imap_tested_at"],
1156 },
1157 "smtp": {
1158 "host": row["smtp_host"],
1159 "port": row["smtp_port"],
1160 "security": row["smtp_security"],
1161 "username": row["smtp_username"],
1162 "status": row["smtp_status"],
1163 "tested_at": row["smtp_tested_at"],
1164 },
1165 }
1167 def get_account_settings(self, actor_id: str, account_id: str) -> dict[str, Any]:
1168 return self._account_result(self._row(actor_id, account_id)) 2gbhb3 X ~ - 8 4 + lb{ rcqc] @ ` fbkb; dbmbnbobv % pbqbE rbm sbB tbubvbwbxbk w L ybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUbVbWbXbYbZb0b1b2b3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcc gchcicJ jckclc0 mcncf
1170 def _ensure_default(self) -> None:
1171 rows = sorted( 2gbhb3 X ~ - 8 4 + lb{ rcqc] @ ` fbkb; dbmbnbobv % pbqbE rbm sbB tbubvbwbxbk w L ybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUbVbWbXbYbZb0b1b2b3b4b5b6b7b8b9b!b#b$b%b! 'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcc gchcicJ jckclc0 mcncf
1172 self._all_rows(),
1173 key=lambda row: (not row["enabled"], row["created_at"], row["id"]),
1174 )
1175 if not any(row["is_default"] for row in rows) and rows: 2gbhb3 X ~ - 8 4 + lb{ rcqc] @ ` fbkb; dbmbnbobv % pbqbE rbm sbB tbubvbwbxbk w L ybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUbVbWbXbYbZb0b1b2b3b4b5b6b7b8b9b!b#b$b%b! 'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcc gchcicJ jckclc0 mcncf
1176 rows[0]["_config"]["is_default"] = True 2gbhb3 X ~ - 8 4 + lb{ rcqc] @ ` fbkb; dbmbnbobv % pbqbE rbm sbB tbubvbwbxbk w L ybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUbVbWbXbYbZb0b1b2b3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcc gchcicJ jckclc0 mcncf
1177 self._write(rows[0], rows[0]["_config"]) 2gbhb3 X ~ - 8 4 + lb{ rcqc] @ ` fbkb; dbmbnbobv % pbqbE rbm sbB tbubvbwbxbk w L ybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUbVbWbXbYbZb0b1b2b3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcc gchcicJ jckclc0 mcncf
1179 def list_accounts(self, actor_id: str) -> list[dict[str, Any]]:
1180 rows = self._all_rows() 2gbhbOc3 X eb~ { qchd0d
1181 rows.sort(key=lambda row: (not row["is_default"], row["created_at"], row["id"])) 2gbhbOc3 X eb~ { qc
1182 return [self._account_result(row) for row in rows] 2gbhbOc3 X eb~ { qc
1184 def list_agent_accounts(self, actor_id: str) -> list[dict[str, Any]]:
1185 return [ 2gbhbOc3 X eb~ qc
1186 {
1187 **{
1188 key: account[key]
1189 for key in (
1190 "account_id",
1191 "display_name",
1192 "email_address",
1193 "labels",
1194 "is_default",
1195 "enabled",
1196 "save_sent_copy",
1197 )
1198 },
1199 "has_signature": bool(account["signature_text"]),
1200 "health": {
1201 protocol: {
1202 "status": account[protocol]["status"],
1203 "tested_at": account[protocol]["tested_at"],
1204 }
1205 for protocol in ("imap", "smtp")
1206 },
1207 }
1208 for account in self.list_accounts(actor_id)
1209 ]
1211 def set_default(self, actor_id: str, account_id: str) -> dict[str, Any]:
1212 with self.vault.credential_lock(f"email-accounts:{self.workspace_id}"): 1{
1213 self._set_default(actor_id, account_id) 1{
1214 return {"account_id": account_id, "is_default": True} 1{
1216 def _set_default(self, actor_id: str, account_id: str) -> None:
1217 target = self._row(actor_id, account_id) 1{
1218 if not target["enabled"]: 1{
1219 raise ServiceError( 1{
1220 "email.account_disabled", "Enable this account before using it.", 409
1221 )
1222 for row in self._all_rows(): 1{
1223 config = row["_config"] 1{
1224 wanted = row["id"] == account_id 1{
1225 if bool(config.get("is_default")) != wanted: 1{
1226 config["is_default"] = wanted 1{
1227 self._write(row, config) 1{
1229 def prepare_account(
1230 self, actor_id: str, data: dict[str, Any]
1231 ) -> tuple[dict[str, Any] | None, dict[str, Any]]:
1232 """Validate edits and return the account row plus encrypted-secret payload."""
1233 current = ( 2gbhb3 X ~ - 8 4 + lb{ rcqc] @ ` fbkb; dbmbnbobv % pbqbE rbm sbB tbubvbwbxbk w L ybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUbVbWbXbYbZb0b1b2b3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcc gchcicJ jckclc0 mcncf
1234 self._row(actor_id, data["account_id"]) if data.get("account_id") else None
1235 )
1236 for protocol in ("imap", "smtp"): 2gbhb3 X ~ - 8 4 + lb{ rcqc] @ ` fbkb; dbmbnbobv % pbqbE rbm sbB tbubvbwbxbk w L ybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUbVbWbXbYbZb0b1b2b3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcc gchcicJ jckclc0 mcncf
1237 settings = data[protocol] 2gbhb3 X ~ - 8 4 + lb{ rcqc] @ ` fbkb; dbmbnbobv % pbqbE rbm sbB tbubvbwbxbk w L ybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUbVbWbXbYbZb0b1b2b3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcc gchcicJ jckclc0 mcncf
1238 endpoint_changed = current and any( 2gbhb3 X ~ - 8 4 + lb{ rcqc] @ ` fbkb; dbmbnbobv % pbqbE rbm sbB tbubvbwbxbk w L ybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUbVbWbXbYbZb0b1b2b3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcc gchcicJ jckclc0 mcncf
1239 settings[field] != current[f"{protocol}_{field}"]
1240 for field in ("host", "port", "security", "username")
1241 )
1242 if not settings.get("password") and (not current or endpoint_changed): 2gbhb3 X ~ - 8 4 + lb{ rcqc] @ ` fbkb; dbmbnbobv % pbqbE rbm sbB tbubvbwbxbk w L ybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUbVbWbXbYbZb0b1b2b3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcc gchcicJ jckclc0 mcncf
1243 raise ServiceError( 2rc
1244 "email.password_required",
1245 f"{protocol.upper()} password is required when its server settings change.",
1246 400,
1247 )
1248 if not settings.get("password") and current: 2gbhb3 X ~ - 8 4 + lb{ rcqc] @ ` fbkb; dbmbnbobv % pbqbE rbm sbB tbubvbwbxbk w L ybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUbVbWbXbYbZb0b1b2b3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcc gchcicJ jckclc0 mcncf
1249 settings["password"] = current[f"{protocol}_secret"] 2rc
1250 config = { 2gbhb3 X ~ - 8 4 + lb{ rcqc] @ ` fbkb; dbmbnbobv % pbqbE rbm sbB tbubvbwbxbk w L ybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUbVbWbXbYbZb0b1b2b3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcc gchcicJ jckclc0 mcncf
1251 "display_name": data["display_name"],
1252 "email_address": data["email_address"],
1253 "labels": data["labels"],
1254 "is_default": bool(data.get("is_default")),
1255 "enabled": bool(data.get("enabled", True)),
1256 "imap": data["imap"],
1257 "smtp": data["smtp"],
1258 "signature_text": data.get("signature_text", ""),
1259 "save_sent_copy": bool(data.get("save_sent_copy", True)),
1260 "imap_status": "not-tested",
1261 "smtp_status": "not-tested",
1262 "imap_tested_at": None,
1263 "smtp_tested_at": None,
1264 }
1265 return current, config 2gbhb3 X ~ - 8 4 + lb{ rcqc] @ ` fbkb; dbmbnbobv % pbqbE rbm sbB tbubvbwbxbk w L ybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUbVbWbXbYbZb0b1b2b3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcc gchcicJ jckclc0 mcncf
1267 def save_account(self, actor_id: str, data: dict[str, Any]) -> dict[str, Any]:
1268 """Store mailbox settings and return the updated, non-secret settings."""
1269 with self.vault.credential_lock(f"email-accounts:{self.workspace_id}"): 2gbhb3 X ~ - 8 4 + lb{ rcqc] @ ` fbkb; dbmbnbobv % pbqbE rbm sbB tbubvbwbxbk w L ybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUbVbWbXbYbZb0b1b2b3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcc gchcicJ jckclc0 mcncf
1270 current, config = self.prepare_account(actor_id, data) 2gbhb3 X ~ - 8 4 + lb{ rcqc] @ ` fbkb; dbmbnbobv % pbqbE rbm sbB tbubvbwbxbk w L ybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUbVbWbXbYbZb0b1b2b3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcc gchcicJ jckclc0 mcncf
1271 if config["is_default"] and not config["enabled"]: 2gbhb3 X ~ - 8 4 + lb{ rcqc] @ ` fbkb; dbmbnbobv % pbqbE rbm sbB tbubvbwbxbk w L ybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUbVbWbXbYbZb0b1b2b3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcc gchcicJ jckclc0 mcncf
1272 raise ServiceError( 1{
1273 "email.account_disabled",
1274 "Enable this account before using it.",
1275 409,
1276 )
1277 name = f"mailbox-{data['email_address'].lower()}" 2gbhb3 X ~ - 8 4 + lb{ rcqc] @ ` fbkb; dbmbnbobv % pbqbE rbm sbB tbubvbwbxbk w L ybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUbVbWbXbYbZb0b1b2b3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcc gchcicJ jckclc0 mcncf
1278 secret = json.dumps(config, separators=(",", ":")) 2gbhb3 X ~ - 8 4 + lb{ rcqc] @ ` fbkb; dbmbnbobv % pbqbE rbm sbB tbubvbwbxbk w L ybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUbVbWbXbYbZb0b1b2b3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcc gchcicJ jckclc0 mcncf
1279 if current: 2gbhb3 X ~ - 8 4 + lb{ rcqc] @ ` fbkb; dbmbnbobv % pbqbE rbm sbB tbubvbwbxbk w L ybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUbVbWbXbYbZb0b1b2b3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcc gchcicJ jckclc0 mcncf
1280 metadata = self.vault.update_credential( 28 rc
1281 credential_id=current["_credential"].id,
1282 actor=self.actor,
1283 name=name,
1284 secret=secret,
1285 context=self.context,
1286 )
1287 else:
1288 metadata = self.vault.create_credential( 2gbhb3 X ~ - 8 4 + lb{ rcqc] @ ` fbkb; dbmbnbobv % pbqbE rbm sbB tbubvbwbxbk w L ybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUbVbWbXbYbZb0b1b2b3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcc gchcicJ jckclc0 mcncf
1289 name=name,
1290 provider=self.ACCOUNT_PROVIDER,
1291 scopes=["email:imap", "email:smtp"],
1292 secret=secret,
1293 actor=self.actor,
1294 scope=CredentialScope.for_roles(EMAIL_CREDENTIAL_ROLE),
1295 workspace_id=self.workspace_id,
1296 )
1297 account_id = str(metadata.id) 2gbhb3 X ~ - 8 4 + lb{ rcqc] @ ` fbkb; dbmbnbobv % pbqbE rbm sbB tbubvbwbxbk w L ybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUbVbWbXbYbZb0b1b2b3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcc gchcicJ jckclc0 mcncf
1298 if config["is_default"]: 2gbhb3 X ~ - 8 4 + lb{ rcqc] @ ` fbkb; dbmbnbobv % pbqbE rbm sbB tbubvbwbxbk w L ybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUbVbWbXbYbZb0b1b2b3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcc gchcicJ jckclc0 mcncf
1299 self._set_default(actor_id, account_id) 1{
1300 else:
1301 self._ensure_default() 2gbhb3 X ~ - 8 4 + lb{ rcqc] @ ` fbkb; dbmbnbobv % pbqbE rbm sbB tbubvbwbxbk w L ybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUbVbWbXbYbZb0b1b2b3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcc gchcicJ jckclc0 mcncf
1302 return self.get_account_settings(actor_id, account_id) 2gbhb3 X ~ - 8 4 + lb{ rcqc] @ ` fbkb; dbmbnbobv % pbqbE rbm sbB tbubvbwbxbk w L ybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUbVbWbXbYbZb0b1b2b3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcc gchcicJ jckclc0 mcncf
1304 def delete_account(self, actor_id: str, account_id: str) -> dict[str, Any]:
1305 with self.vault.credential_lock(f"email-accounts:{self.workspace_id}"): 1X~-{!
1306 row = self._row(actor_id, account_id) 1X~-{!
1307 self.vault.delete_credential(row["_credential"].id, context=self.context) 1X~-{!
1308 self._ensure_default() 1X~-{!
1309 return {"account_id": account_id, "deleted": True} 1X~-{!
1311 def _selected_account(
1312 self, actor_id: str, account_id: str | None
1313 ) -> dict[str, Any]:
1314 if account_id: 2ebkb| } d bbcbP 1 Y v % K E Z m B W : * M k w L # a n F 2 S ) 7 , N l [ . r u q y o x G _ R H T O I D ! ibt ^ ocs ( jbEcz ? A Q abzci e V j h p c g 9 5 J U C $ 6 ' f
1315 row = self._row(actor_id, account_id) 2kb| } d bbcbP 1 Y v % K E Z m B W : * M k w L # a n F 2 S ) 7 N l . r G _ R H T O I D ! t s z A i e j h p c g C $ f
1316 else:
1317 rows = [row for row in self._all_rows() if row["enabled"]] 2ebkb# a 7 , [ . u q y o x ! ibt ^ ocs ( jbEcz ? Q abzcV 9 5 J U 6 ' f
1318 rows.sort( 2ebkb# a 7 , [ . u q y o x ! ibt ^ ocs ( jbEcz ? Q abzcV 9 5 J U 6 ' f
1319 key=lambda row: (not row["is_default"], row["created_at"], row["id"])
1320 )
1321 if not rows: 2ebkb# a 7 , [ . u q y o x ! ibt ^ ocs ( jbEcz ? Q abzcV 9 5 J U 6 ' f
1322 raise ServiceError( 2ebkb
1323 "email.account_required", "Add an email account first.", 409
1324 )
1325 row = rows[0] 2kb# a 7 , [ . u q y o x ! ibt ^ ocs ( jbEcz ? Q abzcV 9 5 J U 6 ' f
1326 if not row["enabled"]: 2kb| } d bbcbP 1 Y v % K E Z m B W : * M k w L # a n F 2 S ) 7 , N l [ . r u q y o x G _ R H T O I D ! ibt ^ ocs ( jbEcz ? A Q abzci e V j h p c g 9 5 J U C $ 6 ' f
1327 raise ServiceError( 2kb
1328 "email.account_disabled", "This email account is disabled.", 409
1329 )
1330 return row 2kb| } d bbcbP 1 Y v % K E Z m B W : * M k w L # a n F 2 S ) 7 , N l [ . r u q y o x G _ R H T O I D ! ibt ^ ocs ( jbEcz ? A Q abzci e V j h p c g 9 5 J U C $ 6 ' f
1332 def _credentials(self, row: dict[str, Any], protocol: str) -> dict[str, Any]:
1333 config = row["_config"][protocol] 23 X - 8 4 + lb] @ ` fb; dbP 1 Y v K E Z m B W : * M k w L # a n F 2 S ) 7 , N l [ . r u q y o x G _ R H T O I D t s z A Q i e V j h p c g 9 5 J U C $ 0 6 ' f
1334 try: 23 X - 8 4 + lb] @ ` fb; dbP 1 Y v K E Z m B W : * M k w L # a n F 2 S ) 7 , N l [ . r u q y o x G _ R H T O I D t s z A Q i e V j h p c g 9 5 J U C $ 0 6 ' f
1335 from orcheo_backend.app.workspace import get_workspace_repository 23 X - 8 4 + lb] @ ` fb; dbP 1 Y v K E Z m B W : * M k w L # a n F 2 S ) 7 , N l [ . r u q y o x G _ R H T O I D t s z A Q i e V j h p c g 9 5 J U C $ 0 6 ' f
1337 get_workspace_repository().record_audit_event( 23 X - 8 4 + lb] @ ` fb; dbP 1 Y v K E Z m B W : * M k w L # a n F 2 S ) 7 , N l [ . r u q y o x G _ R H T O I D t s z A Q i e V j h p c g 9 5 J U C $ 0 6 ' f
1338 WorkspaceAuditEvent(
1339 workspace_id=uuid.UUID(self.workspace_id),
1340 action="vault.email_account_used",
1341 actor=self.actor,
1342 subject=self.actor,
1343 resource_type="credential",
1344 resource_id=row["id"],
1345 details={"protocol": protocol},
1346 )
1347 )
1348 except Exception: # Audit failure must not disclose secrets or break mail. 2lb
1349 logger.warning("Could not record email credential usage") 2lb
1350 return { 23 X - 8 4 + lb] @ ` fb; dbP 1 Y v K E Z m B W : * M k w L # a n F 2 S ) 7 , N l [ . r u q y o x G _ R H T O I D t s z A Q i e V j h p c g 9 5 J U C $ 0 6 ' f
1351 key: config[key]
1352 for key in ("host", "port", "security", "username", "password")
1353 }
1355 def _imap(self, row: dict[str, Any]) -> imaplib.IMAP4:
1356 config = self._credentials(row, "imap") 23 X - 8 4 + ] @ ` fbP 1 Y v K E Z m B W : * M k w L # a n F 2 S ) 7 , N l [ . r u q y o x G _ R H T O I D s z A Q i e V j h p c g 9 5 J U C $ f
1357 addresses = _server_ips(config["host"], config["port"]) 23 X - 8 4 + ] @ ` fbP 1 Y v K E Z m B W : * M k w L # a n F 2 S ) 7 , N l [ . r u q y o x G _ R H T O I D s z A Q i e V j h p c g 9 5 J U C $ f
1358 last_error: Exception | None = None 23 X - 8 4 + ] @ ` fbP 1 Y v K E Z m B W : * M k w L # a n F 2 S ) 7 , N l [ . r u q y o x G _ R H T O I D s z A Q i e V j h p c g 9 5 J U C $ f
1359 for address in addresses: 23 X - 8 4 + ] @ ` fbP 1 Y v K E Z m B W : * M k w L # a n F 2 S ) 7 , N l [ . r u q y o x G _ R H T O I D s z A Q i e V j h p c g 9 5 J U C $ f
1360 client = None 23 X - 8 4 + ] @ ` fbP 1 Y v K E Z m B W : * M k w L # a n F 2 S ) 7 , N l [ . r u q y o x G _ R H T O I D s z A Q i e V j h p c g 9 5 J U C $ f
1361 try: 23 X - 8 4 + ] @ ` fbP 1 Y v K E Z m B W : * M k w L # a n F 2 S ) 7 , N l [ . r u q y o x G _ R H T O I D s z A Q i e V j h p c g 9 5 J U C $ f
1362 client = _PinnedIMAP( 23 X - 8 4 + ] @ ` fbP 1 Y v K E Z m B W : * M k w L # a n F 2 S ) 7 , N l [ . r u q y o x G _ R H T O I D s z A Q i e V j h p c g 9 5 J U C $ f
1363 config["host"],
1364 config["port"],
1365 address,
1366 config["security"] == "ssl",
1367 )
1368 if config["security"] == "starttls": 23 X - 8 4 + ] @ ` fbP 1 Y v K E Z m B W : * M k w L # a n F 2 S ) 7 , N l [ . r u q y o x G _ R H T O I D s z A Q i e V j h p c g 9 5 J U C $ f
1369 client.starttls(ssl_context=ssl.create_default_context()) 1@`
1370 except (OSError, imaplib.IMAP4.abort) as error: 1]@`
1371 last_error = error 1]`
1372 if client is not None: 1]`
1373 try: 1`
1374 client.logout() 1`
1375 except (OSError, imaplib.IMAP4.error): 1`
1376 pass 1`
1377 continue 1]`
1378 except imaplib.IMAP4.error as error: 1@
1379 if client is not None: 1379 ↛ 1384line 1379 didn't jump to line 1384 because the condition on line 1379 was always true1@
1380 try: 1@
1381 client.logout() 1@
1382 except (OSError, imaplib.IMAP4.error): 1@
1383 pass 1@
1384 raise ServiceError( 1@
1385 "email.imap_failed",
1386 "Could not connect to the IMAP server. Check its settings and password.",
1387 502,
1388 ) from error
1389 try: 23 X - 8 4 + ] @ ` fbP 1 Y v K E Z m B W : * M k w L # a n F 2 S ) 7 , N l [ . r u q y o x G _ R H T O I D s z A Q i e V j h p c g 9 5 J U C $ f
1390 client.login(config["username"], config["password"]) 23 X - 8 4 + ] @ ` fbP 1 Y v K E Z m B W : * M k w L # a n F 2 S ) 7 , N l [ . r u q y o x G _ R H T O I D s z A Q i e V j h p c g 9 5 J U C $ f
1391 return client 23 X - 8 4 + ` fbP 1 Y v K E Z m B W : * M k w L # a n F 2 S ) 7 , N l [ . r u q y o x G _ R H T O I D s z A Q i e V j h p c g 9 5 J U C $ f
1392 except (OSError, imaplib.IMAP4.abort, ssl.SSLError) as error: 14]@AQc
1393 last_error = error 1]
1394 try: 1]
1395 client.logout() 1]
1396 except (OSError, imaplib.IMAP4.error): 1]
1397 pass 1]
1398 except imaplib.IMAP4.error as error: 14@AQc
1399 try: 14@AQc
1400 client.logout() 14@AQc
1401 except (OSError, imaplib.IMAP4.error): 1@
1402 pass 1@
1403 raise ServiceError( 14@AQc
1404 "email.imap_failed",
1405 "Could not connect to the IMAP server. Check its settings and password.",
1406 502,
1407 ) from error
1408 raise ServiceError( 1]
1409 "email.imap_failed",
1410 "Could not connect to the IMAP server. Check its settings and password.",
1411 502,
1412 ) from last_error
1414 def _smtp(self, row: dict[str, Any]) -> smtplib.SMTP:
1415 config = self._credentials(row, "smtp") 23 X 8 4 ; dbt s z A Q i e V j h c g U C 0 6 ' f
1416 addresses = _server_ips(config["host"], config["port"]) 23 X 8 4 ; dbt s z A Q i e V j h c g U C 0 6 ' f
1417 last_error: Exception | None = None 23 X 8 4 ; dbt s z A Q i e V j h c g U C 0 6 ' f
1418 for address in addresses: 23 X 8 4 ; dbt s z A Q i e V j h c g U C 0 6 ' f
1419 client = None 23 X 8 4 ; dbt s z A Q i e V j h c g U C 0 6 ' f
1420 try: 23 X 8 4 ; dbt s z A Q i e V j h c g U C 0 6 ' f
1421 client = _PinnedSMTP( 23 X 8 4 ; dbt s z A Q i e V j h c g U C 0 6 ' f
1422 config["host"],
1423 config["port"],
1424 address,
1425 config["security"] == "ssl",
1426 )
1427 if config["security"] == "starttls": 23 X 8 4 ; dbt s z A Q i e V j h c g U C 0 6 ' f
1428 client.ehlo() 2; db
1429 client.starttls(context=ssl.create_default_context()) 2; db
1430 client.ehlo() 2; db
1431 except (OSError, smtplib.SMTPException) as error: 1;
1432 if client is not None: 1;
1433 try: 1;
1434 client.quit() 1;
1435 except (OSError, smtplib.SMTPException): 1;
1436 pass 1;
1437 if isinstance(error, smtplib.SMTPException) and not isinstance( 1;
1438 error, smtplib.SMTPServerDisconnected
1439 ):
1440 raise ServiceError( 1;
1441 "email.smtp_failed",
1442 "Could not connect to the SMTP server. Check its settings and password.",
1443 502,
1444 ) from error
1445 last_error = error 1;
1446 continue 1;
1447 try: 23 X 8 4 ; dbt s z A Q i e V j h c g U C 0 6 ' f
1448 client.login(config["username"], config["password"]) 23 X 8 4 ; dbt s z A Q i e V j h c g U C 0 6 ' f
1449 return client 23 X 8 4 ; dbt s z A Q i e V j h c g U C 0 6 ' f
1450 except (OSError, smtplib.SMTPException) as error: 14;
1451 try: 14;
1452 client.quit() 14;
1453 except (OSError, smtplib.SMTPException): 1;
1454 pass 1;
1455 if isinstance(error, smtplib.SMTPException) and not isinstance( 14;
1456 error, smtplib.SMTPServerDisconnected
1457 ):
1458 raise ServiceError( 14;
1459 "email.smtp_failed",
1460 "Could not connect to the SMTP server. Check its settings and password.",
1461 502,
1462 ) from error
1463 last_error = error 1;
1464 raise ServiceError( 1;
1465 "email.smtp_failed",
1466 "Could not connect to the SMTP server. Check its settings and password.",
1467 502,
1468 ) from last_error
1470 def test_account(
1471 self, actor_id: str, account_id: str, protocol: str
1472 ) -> dict[str, Any]:
1473 row = self._row(actor_id, account_id) 13X-84+
1474 if not row["enabled"]: 13X-84+
1475 raise ServiceError( 14
1476 "email.account_disabled", "Enable this account before testing it.", 409
1477 )
1478 protocols = ("imap", "smtp") if protocol == "both" else (protocol,) 13X-84+
1479 outcomes: dict[str, Any] = {} 13X-84+
1480 tested_at: dict[str, str] = {} 13X-84+
1481 for name in protocols: 13X-84+
1482 try: 13X-84+
1483 if name == "imap": 13X-84+
1484 client = self._imap(row) 13X-84+
1485 try: 13X-84+
1486 client.logout() 13X-84+
1487 except (OSError, imaplib.IMAP4.error): 1+
1488 pass 1+
1489 else:
1490 smtp = self._smtp(row) 13X84
1491 smtp.quit() 13X84
1492 status = "connected" 13X-84+
1493 message = "Connection successful." 13X-84+
1494 except ServiceError as error: 14
1495 status = "failed" 14
1496 message = error.message 14
1497 tested_at[name] = datetime.now(UTC).isoformat() 13X-84+
1498 outcomes[name] = {"status": status, "message": message} 13X-84+
1499 # The connections can take a while. Record only the outcome, on the
1500 # settings as they are now, so a save made meanwhile is not reverted.
1501 with self.vault.credential_lock(f"email-accounts:{self.workspace_id}"): 13X-84+
1502 current = self._row(actor_id, account_id) 13X-84+
1503 config = current["_config"] 13X84+
1504 for name, outcome in outcomes.items(): 13X84+
1505 config[f"{name}_status"] = outcome["status"] 13X84+
1506 config[f"{name}_tested_at"] = tested_at[name] 13X84+
1507 self._write(current, config) 13X84+
1508 return {"account_id": account_id, "connections": outcomes} 13X84+
1510 @staticmethod
1511 def _decode_message_id(message_id: str) -> tuple[str, str, int, int]:
1512 try: 2ebd bbcbP 1 Y v % K E Z m B W : * M k w L # a n F 2 S ) N l r pd/c%c'c{c:c;cqd|cG _ R H T O I D A i e j h p c g C $
1513 parts = json.loads(_unb64(message_id)) 2ebd bbcbP 1 Y v % K E Z m B W : * M k w L # a n F 2 S ) N l r pd/c%c'c{c:c;cqd|cG _ R H T O I D A i e j h p c g C $
1514 if not isinstance(parts, list) or len(parts) != 4: 2d bbcbP 1 Y v % K E Z m B W : * M k w L # a n F 2 S ) N l r /c%c'c{c:c;c|cG _ R H T O I D A i e j h p c g C $
1515 raise ValueError 2{c|c
1516 account_id, folder, uidvalidity, uid = parts 2d bbcbP 1 Y v % K E Z m B W : * M k w L # a n F 2 S ) N l r /c%c'c:c;cG _ R H T O I D A i e j h p c g C $
1517 if not isinstance(account_id, str) or not isinstance(folder, str): 2d bbcbP 1 Y v % K E Z m B W : * M k w L # a n F 2 S ) N l r /c%c'c:c;cG _ R H T O I D A i e j h p c g C $
1518 raise ValueError 2:c;c
1519 uidvalidity, uid = int(uidvalidity), int(uid) 2d bbcbP 1 Y v % K E Z m B W : * M k w L # a n F 2 S ) N l r /c%c'cG _ R H T O I D A i e j h p c g C $
1520 if uidvalidity < 1 or uid < 1: 2d bbcbP 1 Y v % K E Z m B W : * M k w L # a n F 2 S ) N l r %c'cG _ R H T O I D A i e j h p c g C $
1521 raise ValueError 2%c'c
1522 except (ValueError, TypeError, json.JSONDecodeError) as error: 2ebpd/c%c'c{c:c;cqd|c
1523 raise ServiceError( 2ebpd/c%c'c{c:c;cqd|c
1524 "email.invalid_id", "Email identifier is invalid.", 400
1525 ) from error
1526 return account_id, folder, uidvalidity, uid 2d bbcbP 1 Y v % K E Z m B W : * M k w L # a n F 2 S ) N l r G _ R H T O I D A i e j h p c g C $
1528 def _message_location(
1529 self, actor_id: str, message_id: str
1530 ) -> tuple[dict[str, Any], str, int, int]:
1531 account_id, folder, uidvalidity, uid = self._decode_message_id(message_id) 2ebd bbcb# a n F 2 S ) N l r pd/c%c'c{c:c;cqd|cG _ R H T O I D A i e j h p c g C $
1532 return self._selected_account(actor_id, account_id), folder, uidvalidity, uid 2d bbcb# a n F 2 S ) N l r G _ R H T O I D A i e j h p c g C $
1534 def _group_messages(
1535 self, actor_id: str, message_ids: list[str]
1536 ) -> tuple[
1537 dict[tuple[str, str, int], list[tuple[int, str]]], dict[str, dict[str, Any]]
1538 ]:
1539 """Group messages by folder generation, resolving each mailbox once."""
1540 rows: dict[str, dict[str, Any]] = {} 1P1Yv%KEZmBW:*MkwLa
1541 groups: dict[tuple[str, str, int], list[tuple[int, str]]] = {} 1P1Yv%KEZmBW:*MkwLa
1542 for message_id in message_ids: 1P1Yv%KEZmBW:*MkwLa
1543 account_id, folder, validity, uid = self._decode_message_id(message_id) 1P1Yv%KEZmBW:*MkwLa
1544 if account_id not in rows: 1P1Yv%KEZmBW:*MkwLa
1545 rows[account_id] = self._selected_account(actor_id, account_id) 1P1Yv%KEZmBW:*MkwLa
1546 groups.setdefault((account_id, folder, validity), []).append( 1P1Yv%KEZmBW:*MkwLa
1547 (uid, message_id)
1548 )
1549 return groups, rows 1P1Yv%KEZmBW:*MkwLa
1551 def _fetch_raw(
1552 self, client: imaplib.IMAP4, folder: str, uidvalidity: int, uid: int
1553 ) -> tuple[bytes, bytes]:
1554 kind, _ = client.select(_imap_quote(folder), readonly=True) 1#anF2S)NlrG_RHTOIDAiejhpcgC$
1555 if kind != "OK": 1#anF2S)NlrG_RHTOIDAiejhpcgC$
1556 raise ServiceError( 1)
1557 "email.folder_not_found", "Mail folder could not be opened.", 404
1558 )
1559 if _uidvalidity(client) != uidvalidity: 1#anF2S)NlrG_RHTOIDAiejhpcgC$
1560 raise ServiceError( 1#)_
1561 "email.message_expired",
1562 "This email identifier is no longer valid. Search the folder again.",
1563 404,
1564 )
1565 kind, data = client.uid("fetch", str(uid), "(UID FLAGS RFC822.SIZE)") 1anF2S)NlrGRHTOIDAiejhpcgC$
1566 if kind != "OK": 1anF2S)NlrGRHTOIDAiejhpcgC$
1567 raise ServiceError("email.message_not_found", "Email not found.", 404) 1)
1568 # Metadata-only FETCH responses are bytes; responses with literals are
1569 # tuples. Normalize both forms and ignore trailing protocol delimiters.
1570 for entry in data or []: 1anF2S)NlrGRHTOIDAiejhpcgC$
1571 metadata = entry[0] if isinstance(entry, tuple) else entry 1anF2S)NlrGRHTOIDAiejhpcgC$
1572 if not isinstance(metadata, bytes): 1anF2S)NlrGRHTOIDAiejhpcgC$
1573 continue 1S
1574 size = re.search(rb"RFC822\.SIZE\s+(\d+)", metadata, re.I) 1anF2S)NlrGRHTOIDAiejhpcgC$
1575 if size: 1575 ↛ 1570line 1575 didn't jump to line 1570 because the condition on line 1575 was always true1anF2S)NlrGRHTOIDAiejhpcgC$
1576 break 1anF2S)NlrGRHTOIDAiejhpcgC$
1577 else:
1578 raise ServiceError("email.message_not_found", "Email not found.", 404) 1)
1579 if int(size.group(1)) > MAX_EMAIL_SIZE: 1anF2S)NlrGRHTOIDAiejhpcgC$
1580 raise ServiceError( 1)
1581 "email.message_too_large", "This email is too large to fetch.", 413
1582 )
1583 flags_match = re.search(rb"FLAGS\s+\(([^)]*)\)", metadata, re.I) 1anF2S)NlrGRHTOIDAiejhpcgC$
1584 flags = flags_match.group(1) if flags_match else b"" 1anF2S)NlrGRHTOIDAiejhpcgC$
1585 kind, data = client.uid("fetch", str(uid), "(BODY.PEEK[])") 1anF2S)NlrGRHTOIDAiejhpcgC$
1586 if kind != "OK": 1anF2S)NlrGRHTOIDAiejhpcgC$
1587 raise ServiceError("email.message_not_found", "Email not found.", 404) 1)
1588 for entry in data or []: 1anF2S)NlrGRHTOIDAiejhpcgC$
1589 if isinstance(entry, tuple) and isinstance(entry[1], bytes): 1589 ↛ 1588line 1589 didn't jump to line 1588 because the condition on line 1589 was always true1anF2SNlrGRHTOIDAiejhpcgC$
1590 return entry[1], flags 1anF2SNlrGRHTOIDAiejhpcgC$
1591 raise ServiceError("email.message_not_found", "Email not found.", 404) 1)
1593 def search(self, actor_id: str, args: dict[str, Any]) -> dict[str, Any]:
1594 row = self._selected_account(actor_id, args.get("account_id")) 1d#auqyox
1595 _clean_folder(args["folder"]) 1d#auqyox
1596 client = self._imap(row) 1d#auqyox
1597 try: 1d#auqyox
1598 folder = _resolve_folder(client, args["folder"]) 1d#auqyox
1599 kind, _ = client.select(_imap_quote(folder), readonly=True) 1d#auqyox
1600 if kind != "OK": 1d#auqyox
1601 raise ServiceError( 1q
1602 "email.folder_not_found", "Mail folder could not be opened.", 404
1603 )
1604 uidvalidity = _uidvalidity(client) 1d#auqyox
1605 if uidvalidity is None: 1d#auqyox
1606 raise ServiceError( 1#q
1607 "email.invalid_mailbox",
1608 "The IMAP server did not provide a stable mailbox identifier.",
1609 502,
1610 )
1611 criteria: list[str] = ["UNSEEN"] if args["unread_only"] else ["ALL"] 1dauqyox
1612 if args.get("after"): 1dauqyox
1613 criteria.extend( 1x
1614 ["SINCE", date.fromisoformat(args["after"]).strftime("%d-%b-%Y")]
1615 )
1616 if args.get("before"): 1dauqyox
1617 exclusive_before = date.fromisoformat(args["before"]) + timedelta( 1x
1618 days=1
1619 )
1620 criteria.extend(["BEFORE", exclusive_before.strftime("%d-%b-%Y")]) 1x
1621 for key, yes, no in ( 1dauqyox
1622 ("flagged", "FLAGGED", "UNFLAGGED"),
1623 ("answered", "ANSWERED", "UNANSWERED"),
1624 ):
1625 if args.get(key) is not None: 1dauqyox
1626 criteria.append(yes if args[key] else no) 1x
1627 if args.get("larger_than_kb"): 1dauqyox
1628 criteria.extend(["LARGER", str(int(args["larger_than_kb"]) * 1024)]) 1x
1629 for key, criterion in ( 1dauqyox
1630 ("from_address", "FROM"),
1631 ("to_address", "TO"),
1632 ("subject", "SUBJECT"),
1633 ("text", "TEXT"),
1634 ):
1635 if args.get(key): 1dauqyox
1636 value = str(args[key]).replace("\r", " ").replace("\n", " ") 1qx
1637 if not value.isascii(): 1qx
1638 raise ServiceError( 1q
1639 "email.search_charset",
1640 "Email search filters currently support ASCII text only.",
1641 400,
1642 )
1643 criteria.extend([criterion, _imap_raw_quote(value)]) 1x
1644 kind, data = client.uid("search", *criteria) 1dauqyox
1645 if kind != "OK": 1dauqyox
1646 raise ServiceError( 1q
1647 "email.search_failed",
1648 "The IMAP server could not search this folder.",
1649 502,
1650 )
1651 uids = sorted( 1dauqyox
1652 (int(item) for item in (data[0].split() if data and data[0] else [])),
1653 reverse=True,
1654 )
1655 if args.get("cursor"): 1dauqyox
1656 # A cursor names the folder generation it was made in: after
1657 # the server renumbers the folder, its UIDs mean other mail.
1658 cursor_validity, _, cursor_uid = args["cursor"].rpartition(".") 1qy
1659 try: 1qy
1660 before_uid = int(cursor_uid) 1qy
1661 expired = ( 1qy
1662 bool(cursor_validity) and int(cursor_validity) != uidvalidity
1663 )
1664 except ValueError as error: 1q
1665 raise ServiceError( 1q
1666 "email.invalid_cursor", "Email page cursor is invalid.", 400
1667 ) from error
1668 if expired: 1qy
1669 raise ServiceError( 1q
1670 "email.cursor_expired",
1671 "This folder changed since the last page. Search again.",
1672 409,
1673 )
1674 uids = [uid for uid in uids if uid < before_uid] 1qy
1675 items: list[dict[str, Any]] = [] 1dauqyox
1676 skipped: list[int] = [] 1dauqyox
1677 examined = 0 1dauqyox
1678 limit = args["limit"] 1dauqyox
1679 attachment_filter = args.get("has_attachments") 1dauqyox
1680 batch_size = limit if attachment_filter is None else 50 1dauqyox
1681 for batch in itertools.batched(uids, batch_size): 1dauqyox
1682 fetched = _fetch_search_page(client, batch) 1dauqyox
1683 for uid in batch: 1dauqyox
1684 examined += 1 1dauqyox
1685 if uid not in fetched: 1dauqyox
1686 skipped.append(uid) 1u
1687 continue 1u
1688 metadata, raw_headers = fetched[uid] 1dauqyox
1689 has_attachments = _bodystructure_has_attachment(metadata) 1dauqyox
1690 if attachment_filter is not None and has_attachments is None: 1dauqyox
1691 skipped.append(uid) 1u
1692 continue 1u
1693 if (
1694 attachment_filter is not None
1695 and has_attachments != attachment_filter
1696 ):
1697 continue 1du
1698 parsed = BytesParser(policy=email.policy.default).parsebytes( 1dauqyox
1699 raw_headers
1700 )
1701 opaque_id = _b64( 1dauqyox
1702 json.dumps(
1703 [row["id"], folder, uidvalidity, uid], separators=(",", ":")
1704 ).encode()
1705 )
1706 attributes = re.sub(_IMAP_QUOTED_STRING, b'""', metadata) 1dauqyox
1707 flags_match = re.search(rb"FLAGS\s+\(([^)]*)\)", attributes, re.I) 1dauqyox
1708 flags = flags_match.group(1) if flags_match else b"" 1dauqyox
1709 size = re.search(rb"RFC822\.SIZE\s+(\d+)", attributes, re.I) 1dauqyox
1710 items.append( 1dauqyox
1711 {
1712 **_summary(parsed, opaque_id, flags),
1713 "flagged": b"\\Flagged" in flags,
1714 "answered": b"\\Answered" in flags,
1715 "has_attachments": has_attachments,
1716 "size": int(size.group(1)) if size else None,
1717 }
1718 )
1719 if len(items) == limit: 1dauqyox
1720 break 1duy
1721 if len(items) == limit: 1dauqyox
1722 break 1duy
1723 next_cursor = ( 1dauqyox
1724 f"{uidvalidity}.{uids[examined - 1]}"
1725 if 0 < examined < len(uids)
1726 else None
1727 )
1728 result = { 1dauqyox
1729 "account_id": row["id"],
1730 "folder": folder,
1731 "items": items,
1732 "next_cursor": next_cursor,
1733 }
1734 if skipped: 1dauqyox
1735 result["skipped_uids"] = skipped 1u
1736 return result 1dauqyox
1737 finally:
1738 try: 1d#auqyox
1739 client.logout() 1d#auqyox
1740 except (OSError, imaplib.IMAP4.error): 1a
1741 pass 1a
1743 def get_email(
1744 self,
1745 actor_id: str,
1746 message_id: str,
1747 *,
1748 include_html: bool = True,
1749 max_body_chars: int | None = None,
1750 ) -> dict[str, Any]:
1751 row, folder, uidvalidity, uid = self._message_location(actor_id, message_id) 2ebd # a n F S ) N l r pd/c%c'c{c:c;cqd|cD
1752 client = self._imap(row) 1d#anFS)NlrD
1753 try: 1d#anFS)NlrD
1754 raw, flags = self._fetch_raw(client, folder, uidvalidity, uid) 1d#anFS)NlrD
1755 finally:
1756 try: 1d#anFS)NlrD
1757 client.logout() 1d#anFS)NlrD
1758 except (OSError, imaplib.IMAP4.error): 1a
1759 pass 1a
1760 parsed = BytesParser(policy=email.policy.default).parsebytes(raw) 1danFSNlrD
1761 summary = _summary(parsed, message_id, flags) 1danFSNlrD
1762 attachments = [] 1danFSNlrD
1763 for index, part in enumerate(parsed.walk()): 1danFSNlrD
1764 filename = part.get_filename() 1danFSNlrD
1765 if _is_attachment(part): 1danFSNlrD
1766 payload = _part_payload(part) 1danFlrD
1767 attachment_id = _b64( 1danFlrD
1768 json.dumps(
1769 ["attachment", message_id, index], separators=(",", ":")
1770 ).encode()
1771 )
1772 attachments.append( 1danFlrD
1773 {
1774 "attachment_id": attachment_id,
1775 "filename": _decode_header(filename) or "attachment",
1776 "content_type": part.get_content_type(),
1777 "size": len(payload),
1778 }
1779 )
1780 body_html = _email_text(parsed, html_body=True) 1danFSNlrD
1781 body_text = _email_text(parsed) 1danFSNlrD
1782 if not body_text and body_html: 1danFSNlrD
1783 # HTML-only mail still has words in it.
1784 body_text = html_to_text(body_html) 1N
1785 result = { 1danFSNlrD
1786 **summary,
1787 "reply_to": _decode_header(parsed.get("Reply-To")),
1788 "message_header_id": parsed.get("Message-ID"),
1789 "in_reply_to": parsed.get("In-Reply-To"),
1790 "references": parsed.get_all("References", []),
1791 "body_text": body_text,
1792 "attachments": attachments,
1793 }
1794 if max_body_chars and len(body_text) > max_body_chars: 1danFSNlrD
1795 result["body_text"] = body_text[:max_body_chars] 1l
1796 result["body_text_truncated"] = True 1l
1797 if include_html: 1danFSNlrD
1798 result["body_html"] = body_html 1danFSNlrD
1799 if max_body_chars and len(body_html) > max_body_chars * 3: 1danFSNlrD
1800 result["body_html"] = body_html[: max_body_chars * 3] 1l
1801 result["body_html_truncated"] = True 1l
1802 invites = _calendar_parts(parsed) 1danFSNlrD
1803 if invites: 1danFSNlrD
1804 result["calendar_invites"] = invites 1l
1805 return {"email": result} 1danFSNlrD
1807 def download_attachment(self, actor_id: str, attachment_id: str) -> dict[str, Any]:
1808 message_id, index = _parse_attachment_id(attachment_id) 2d a [c]c^c_c`cF l
1809 row, folder, uidvalidity, uid = self._message_location(actor_id, message_id) 1daFl
1810 client = self._imap(row) 1daFl
1811 try: 1daFl
1812 raw, _ = self._fetch_raw(client, folder, uidvalidity, uid) 1daFl
1813 finally:
1814 try: 1daFl
1815 client.logout() 1daFl
1816 except (OSError, imaplib.IMAP4.error): 1a
1817 pass 1a
1818 message = BytesParser(policy=email.policy.default).parsebytes(raw) 1daFl
1819 parts = list(message.walk()) 1daFl
1820 if index >= len(parts): 1daFl
1821 raise ServiceError( 1F
1822 "email.attachment_not_found", "Attachment not found.", 404
1823 )
1824 part = parts[index] 1daFl
1825 payload = _part_payload(part) 1daFl
1826 if len(payload) > MAX_ATTACHMENT_SIZE: 1daFl
1827 raise ServiceError( 1F
1828 "email.attachment_too_large",
1829 "Attachments must be 500 KB or less to download.",
1830 413,
1831 )
1832 return { 1daFl
1833 "filename": _decode_header(part.get_filename()) or "attachment",
1834 "content_type": part.get_content_type(),
1835 "content_base64": base64.b64encode(payload).decode(),
1836 }
1838 def mark_read(
1839 self, actor_id: str, message_ids: list[str], is_read: bool
1840 ) -> dict[str, Any]:
1841 # Keep the original IDs alongside UIDs for an exact, actor-scoped result.
1842 grouped_ids, rows = self._group_messages(actor_id, message_ids) 1P1%:*a
1843 if len(grouped_ids) > 5: 1P1%:*a
1844 raise ServiceError( 1%
1845 "email.too_many_mailboxes",
1846 "Mark messages from at most five account and folder combinations at a time.",
1847 400,
1848 )
1849 affected: list[str] = [] 1P1:*a
1850 failed: list[dict[str, str]] = [] 1P1:*a
1851 for (account_id, folder, validity), entries in grouped_ids.items(): 1P1:*a
1852 client = self._imap(rows[account_id]) 1P1:*a
1853 try: 1P1:*a
1854 kind, _ = client.select(_imap_quote(folder), readonly=False) 1P1:*a
1855 if kind != "OK" or _uidvalidity(client) != validity: 1P1:*a
1856 failed.extend( 11*
1857 {"message_id": message_id, "code": "email.message_expired"}
1858 for _, message_id in entries
1859 )
1860 continue 11*
1861 for uid, message_id in entries: 1P:*a
1862 operation = "+FLAGS.SILENT" if is_read else "-FLAGS.SILENT" 1P:*a
1863 kind, _ = client.uid("store", str(uid), operation, "(\\Seen)") 1P:*a
1864 if kind == "OK": 1P:*a
1865 affected.append(message_id) 1P:*a
1866 else:
1867 failed.append( 1*
1868 {"message_id": message_id, "code": "email.action_failed"}
1869 )
1870 finally:
1871 try: 1P1:*a
1872 client.logout() 1P1:*a
1873 except (OSError, imaplib.IMAP4.error): 1a
1874 pass 1a
1875 result: dict[str, Any] = { 1P1:*a
1876 "is_read": is_read,
1877 "affected_count": len(affected),
1878 "message_ids": affected,
1879 }
1880 if failed: 1P1:*a
1881 result["failed"] = failed 11*
1882 return result 1P1:*a
1884 def manage_messages(self, actor_id: str, args: dict[str, Any]) -> dict[str, Any]:
1885 grouped, rows = self._group_messages(actor_id, args["message_ids"]) 1P1Yv%KEZmBWMkwL
1886 if len(grouped) > 5: 1P1Yv%KEZmBWMkwL
1887 raise ServiceError( 1%
1888 "email.too_many_mailboxes",
1889 "Manage messages from at most five account and folder combinations at a time.",
1890 400,
1891 )
1892 affected: list[str] = [] 1P1YvKEZmBWMkwL
1893 failed: list[dict[str, str]] = [] 1P1YvKEZmBWMkwL
1894 moved: list[dict[str, str]] = [] 1P1YvKEZmBWMkwL
1895 for (account_id, folder, validity), entries in grouped.items(): 1P1YvKEZmBWMkwL
1896 row = rows[account_id] 1P1YvKEZmBWMkwL
1897 client = self._imap(row) 1P1YvKEZmBWMkwL
1898 try: 1P1YvKEZmBWMkwL
1899 kind, _ = client.select(_imap_quote(folder), readonly=False) 1P1YvKEZmBWMkwL
1900 if kind != "OK" or _uidvalidity(client) != validity: 1P1YvKEZmBWMkwL
1901 failed.extend( 11W
1902 {"message_id": message_id, "code": "email.message_expired"}
1903 for _, message_id in entries
1904 )
1905 continue 11W
1906 plan = self._action_plan(client, folder, args) 1PYvKEZmBWMkwL
1907 for uid, message_id in entries: 1PYvKZmBWMkwL
1908 kind, data = self._apply_action(client, uid, plan) 1PYvKZmBWMkwL
1909 if kind == "OK": 1PYvKZmBWMk
1910 affected.append(message_id) 1PYvKZmBWMk
1911 new_id = self._copied_id(row["id"], plan, data, uid) 1PYvKZmBWMk
1912 if new_id: 1PYvKZmBWMk
1913 moved.append( 1KmMk
1914 {"message_id": message_id, "new_message_id": new_id}
1915 )
1916 else:
1917 failed.append( 1Wk
1918 {"message_id": message_id, "code": "email.action_failed"}
1919 )
1920 finally:
1921 try: 1P1YvKEZmBWMkwL
1922 client.logout() 1P1YvKEZmBWMkwL
1923 except (OSError, imaplib.IMAP4.error): 1Y
1924 pass 1Y
1925 result: dict[str, Any] = { 1P1YvKZmBWMk
1926 "action": args["action"],
1927 "affected_count": len(affected),
1928 "message_ids": affected,
1929 }
1930 if failed: 1P1YvKZmBWMk
1931 result["failed"] = failed 11Wk
1932 if moved: 1P1YvKZmBWMk
1933 result["moved"] = moved 1KmMk
1934 if args["action"] == "delete": 1P1YvKZmBWMk
1935 result["permanent"] = bool(args.get("permanent")) 1K
1936 return result 1P1YvKZmBWMk
1938 def _action_plan(
1939 self, client: imaplib.IMAP4, folder: str, args: dict[str, Any]
1940 ) -> dict[str, Any]:
1941 """What one action means on this server, worked out once per folder."""
1942 action = args["action"] 1PYvKEZmBWMkwL
1943 gmail = "X-GM-EXT-1" in client.capabilities 1PYvKEZmBWMkwL
1944 if action in {"move", "copy"}: 1PYvKEZmBWMkwL
1945 return { 1Mkw
1946 "kind": action,
1947 "target": _resolve_folder(client, args["target_folder"]),
1948 }
1949 if action == "archive": 1PYvKEZmBWML
1950 target = _special_folder(client, "archive") 1vM
1951 if target: 1vM
1952 return {"kind": "move", "target": _decode_imap_utf7(target)} 1M
1953 if gmail and folder.upper() == "INBOX": 1v
1954 # Gmail archives by taking the Inbox label off.
1955 return {"kind": "store", "op": "-X-GM-LABELS", "value": "(\\Inbox)"} 1v
1956 raise ServiceError( 1v
1957 "email.archive_unsupported",
1958 "This mailbox has no Archive folder. Use manage_email_messages with action=move and a destination folder instead.",
1959 409,
1960 )
1961 if action == "delete" and not args.get("permanent"): 1PYKEZmBWL
1962 target = _special_folder(client, "trash") 1KE
1963 if not target: 1KE
1964 raise ServiceError( 1E
1965 "email.trash_unsupported",
1966 "This mailbox has no Trash folder. Deleting would be permanent; ask the user before retrying with permanent=true.",
1967 409,
1968 )
1969 if _decode_imap_utf7(target) == folder: 1K
1970 raise ServiceError( 1K
1971 "email.already_in_trash",
1972 "These messages are already in Trash. Deleting them again is permanent; ask the user before retrying with permanent=true.",
1973 409,
1974 )
1975 return {"kind": "move", "target": _decode_imap_utf7(target)} 1K
1976 if action == "delete": 1PYKZmBWL
1977 return {"kind": "expunge"} 1KL
1978 if action == "junk": 1PYZmBW
1979 target = _special_folder(client, "junk") 1m
1980 if not target: 1m
1981 raise ServiceError( 1m
1982 "email.junk_unsupported", "This mailbox has no Junk folder.", 409
1983 )
1984 return {"kind": "move", "target": _decode_imap_utf7(target)} 1m
1985 if action == "not_junk": 1PYZmBW
1986 return {"kind": "move", "target": "INBOX"} 1m
1987 if action in {"add_labels", "remove_labels"}: 1PYZBW
1988 sign = "+" if action == "add_labels" else "-" 1B
1989 labels = " ".join(_imap_raw_quote(label) for label in args["labels"]) 1B
1990 if gmail: 1B
1991 return { 1B
1992 "kind": "store",
1993 "op": f"{sign}X-GM-LABELS",
1994 "value": f"({labels})",
1995 }
1996 # Elsewhere a label is an IMAP keyword, which takes atoms only.
1997 atoms = " ".join( 1B
1998 re.sub(r"[^A-Za-z0-9_.-]", "_", label) for label in args["labels"]
1999 )
2000 return {"kind": "store", "op": f"{sign}FLAGS.SILENT", "value": f"({atoms})"} 1B
2001 flag = { 1PYZW
2002 "flag": ("+FLAGS.SILENT", "(\\Flagged)"),
2003 "unflag": ("-FLAGS.SILENT", "(\\Flagged)"),
2004 "mark_answered": ("+FLAGS.SILENT", "(\\Answered)"),
2005 }[action]
2006 return {"kind": "store", "op": flag[0], "value": flag[1]} 1PYZW
2008 @staticmethod
2009 def _apply_action(
2010 client: imaplib.IMAP4, uid: int, plan: dict[str, Any]
2011 ) -> tuple[str, Any]:
2012 if plan["kind"] == "store": 1PYvKZmBWMkwL
2013 return client.uid("store", str(uid), plan["op"], plan["value"]) 1PYvZBW
2014 if plan["kind"] == "expunge": 1KmMkwL
2015 if "UIDPLUS" not in client.capabilities: 1KL
2016 raise ServiceError( 1L
2017 "email.delete_unsupported",
2018 "This server cannot safely delete individual messages.",
2019 409,
2020 )
2021 kind, data = client.uid("store", str(uid), "+FLAGS.SILENT", "(\\Deleted)") 1K
2022 if kind == "OK": 2022 ↛ 2024line 2022 didn't jump to line 2024 because the condition on line 2022 was always true1K
2023 kind, data = client.uid("expunge", str(uid)) 1K
2024 return kind, data 1K
2025 target = _imap_quote(plan["target"]) 1KmMkw
2026 if plan["kind"] == "copy": 1KmMkw
2027 return client.uid("copy", str(uid), target) 1M
2028 if "MOVE" in client.capabilities: 1KmMkw
2029 return client.uid("move", str(uid), target) 1KmM
2030 if "UIDPLUS" in client.capabilities: 1kw
2031 kind, data = client.uid("copy", str(uid), target) 1k
2032 if kind == "OK": 1k
2033 copied = data 1k
2034 kind, _ = client.uid("store", str(uid), "+FLAGS.SILENT", "(\\Deleted)") 1k
2035 if kind == "OK": 1k
2036 kind, _ = client.uid("expunge", str(uid)) 1k
2037 return kind, copied 1k
2038 return kind, data 1k
2039 raise ServiceError( 1w
2040 "email.move_unsupported",
2041 "This server cannot safely move individual messages.",
2042 409,
2043 )
2045 @staticmethod
2046 def _copied_id(
2047 account_id: str, plan: dict[str, Any], data: Any, uid: int
2048 ) -> str | None:
2049 """The message's ID in its new folder, from the server's COPYUID answer."""
2050 if plan["kind"] not in {"move", "copy"}: 2P Y v ndK Z m B W M k
2051 return None 2P Y v ndK Z B W
2052 text = b" ".join( 2ndK m M k
2053 item if isinstance(item, bytes) else b""
2054 for item in (data or [])
2055 if item is not None
2056 )
2057 match = re.search(rb"COPYUID\s+(\d+)\s+([\d:,]+)\s+([\d:,]+)", text, re.I) 2ndK m M k
2058 if not match or b"," in match.group(3) or b":" in match.group(3): 2ndK m M k
2059 return None 2nd
2060 return _b64( 2ndK m M k
2061 json.dumps(
2062 [account_id, plan["target"], int(match.group(1)), int(match.group(3))],
2063 separators=(",", ":"),
2064 ).encode()
2065 )
2067 def compose(
2068 self,
2069 row: dict[str, Any],
2070 args: dict[str, Any],
2071 *,
2072 extra_attachments: Sequence[tuple[bytes, str, str, str]] = (),
2073 ) -> EmailMessage:
2074 """Build the message, signed when the account has a signature."""
2075 message = EmailMessage(policy=OUTBOUND_POLICY) 2/ = t s z Q abzci e V j h p c g 9 5 J U 0 6 ' f
2076 message["From"] = formataddr((row["display_name"], row["email_address"])) 2/ = t s z Q abzci e V j h p c g 9 5 J U 0 6 ' f
2077 message["To"] = ( 2/ = t s z Q abzci e V j h p c g 9 5 J U 0 6 ' f
2078 ", ".join(args["to"]) if args["to"] else "undisclosed-recipients:;"
2079 )
2080 if args.get("cc"): 2/ = t s z Q abzci e V j h p c g 9 5 J U 0 6 ' f
2081 message["Cc"] = ", ".join(args["cc"]) 2abj U
2082 if args.get("reply_to"): 2/ = t s z Q abzci e V j h p c g 9 5 J U 0 6 ' f
2083 message["Reply-To"] = args["reply_to"] 2ab
2084 message["Subject"] = args["subject"] 2/ = t s z Q abzci e V j h p c g 9 5 J U 0 6 ' f
2085 message["Date"] = formatdate(localtime=True) 2/ = t s z Q abzci e V j h p c g 9 5 J U 0 6 ' f
2086 message["Message-ID"] = make_msgid( 2/ = t s z Q abzci e V j h p c g 9 5 J U 0 6 ' f
2087 domain=row["email_address"].rpartition("@")[2]
2088 )
2089 if args.get("in_reply_to"): 2/ = t s z Q abzci e V j h p c g 9 5 J U 0 6 ' f
2090 message["In-Reply-To"] = args["in_reply_to"] 2abj h p c g
2091 if args.get("references"): 2/ = t s z Q abzci e V j h p c g 9 5 J U 0 6 ' f
2092 message["References"] = " ".join(args["references"]) 2abj h p c g
2093 signature = (row.get("signature_text") or "").strip() 2/ = t s z Q abzci e V j h p c g 9 5 J U 0 6 ' f
2094 body_text = args.get("body_text") 2/ = t s z Q abzci e V j h p c g 9 5 J U 0 6 ' f
2095 body_html = args.get("body_html") 2/ = t s z Q abzci e V j h p c g 9 5 J U 0 6 ' f
2096 if signature and args.get("include_signature", True): 2/ = t s z Q abzci e V j h p c g 9 5 J U 0 6 ' f
2097 if body_text: 2097 ↛ 2099line 2097 didn't jump to line 2099 because the condition on line 2097 was always true2ab
2098 body_text = f"{body_text.rstrip()}\n\n-- \n{signature}" 2ab
2099 if body_html: 2099 ↛ 2102line 2099 didn't jump to line 2102 because the condition on line 2099 was always true2ab
2100 escaped = html.escape(signature).replace("\n", "<br>") 2ab
2101 body_html = f"{body_html}<br><br>-- <br>{escaped}" 2ab
2102 if body_text: 2/ = t s z Q abzci e V j h p c g 9 5 J U 0 6 ' f
2103 message.set_content(body_text) 2/ = t s z Q abzci e V j h p c g 9 5 J U 0 6 ' f
2104 if body_html: 2/ = t s z Q abzci e V j h p c g 9 5 J U 0 6 ' f
2105 message.add_alternative(body_html, subtype="html") 2ab
2106 else:
2107 message.set_content(body_html, subtype="html") 2zc
2108 for item in args.get("attachments") or []: 2/ = t s z Q abzci e V j h p c g 9 5 J U 0 6 ' f
2109 payload = base64.b64decode(item["content_base64"], validate=True) 2ab
2110 maintype, _, subtype = item["content_type"].partition("/") 2ab
2111 if (
2112 not maintype
2113 or not subtype
2114 or not maintype.isalnum()
2115 or not subtype.replace("-", "").replace("+", "").isalnum()
2116 ):
2117 maintype, subtype = "application", "octet-stream" 2ab
2118 message.add_attachment( 2ab
2119 payload,
2120 maintype=maintype,
2121 subtype=subtype,
2122 filename=item["filename"],
2123 )
2124 for payload, maintype, subtype, filename in extra_attachments: 2/ = t s z Q abzci e V j h p c g 9 5 J U 0 6 ' f
2125 message.add_attachment( 2abi e
2126 payload, maintype=maintype, subtype=subtype, filename=filename
2127 )
2128 return message 2/ = t s z Q abzci e V j h p c g 9 5 J U 0 6 ' f
2130 def deliver(
2131 self, row: dict[str, Any], message: EmailMessage, recipients: list[str]
2132 ) -> dict[str, Any]:
2133 """Hand a message to SMTP, then keep a copy in Sent where needed."""
2134 envelope = [parseaddr(value)[1] for value in recipients] 1tszAQieVjhcgUC06'f
2135 # Drafts fetched from IMAP can still have an 8bit transfer encoding.
2136 # The generator must apply the same safe policy to those messages too.
2137 message.policy = OUTBOUND_POLICY 1tszAQieVjhcgUC06'f
2138 client = self._smtp(row) 1tszAQieVjhcgUC06'f
2139 try: 1tszAQieVjhcgUC06'f
2140 refused = client.send_message( 1tszAQieVjhcgUC06'f
2141 message, from_addr=row["email_address"], to_addrs=envelope
2142 )
2143 except (smtplib.SMTPException, OSError) as error: 1t6'
2144 raise _delivery_error(error) from error 1t6'
2145 finally:
2146 try: 1tszAQieVjhcgUC06'f
2147 client.quit() 1tszAQieVjhcgUC06'f
2148 except (OSError, smtplib.SMTPException): 16'
2149 pass 16'
2150 saved = None 1szAQieVjhcgUC0f
2151 if row.get("save_sent_copy", True) and not _auto_saves_sent(row["smtp_host"]): 1szAQieVjhcgUC0f
2152 saved = self._append(row, "sent", message, b"(\\Seen)") 1szAQieVjhgUCf
2153 return { 1szAQieVjhcgUC0f
2154 "sent": not refused,
2155 "delivery_status": "partial" if refused else "accepted",
2156 "refused_recipients": list(refused),
2157 "saved_to_sent": saved,
2158 }
2160 def _append(
2161 self, row: dict[str, Any], alias: str, message: EmailMessage, flags: bytes
2162 ) -> bool:
2163 """Store a message in a special folder.
2165 The send already happened, so a failure here is reported, never raised.
2166 """
2167 try: 1szAQieVjhgUCf
2168 client = self._imap(row) 1szAQieVjhgUCf
2169 except ServiceError: 1Q
2170 return False 1Q
2171 try: 1szAQieVjhgUCf
2172 folder = _special_folder(client, alias) 1szAQieVjhgUCf
2173 if not folder: 1szAQieVjhgUCf
2174 return False 1Q
2175 kind, _ = _append_imap_message(client, folder, message, flags.decode()) 1szAQieVjhgUCf
2176 return kind == "OK" 1szAQieVjhgUCf
2177 except (OSError, imaplib.IMAP4.error): 1Q
2178 return False 1Q
2179 finally:
2180 try: 1szAQieVjhgUCf
2181 client.logout() 1szAQieVjhgUCf
2182 except (OSError, imaplib.IMAP4.error): 1Q
2183 pass 1Q
2185 def send(
2186 self,
2187 actor_id: str,
2188 args: dict[str, Any],
2189 *,
2190 extra_bcc: Sequence[str] = (),
2191 extra_attachments: Sequence[tuple[bytes, str, str, str]] = (),
2192 ) -> dict[str, Any]:
2193 row = self._selected_account(actor_id, args.get("account_id")) 2eb! t s z Q i e V j h c g U 6 ' f
2194 message = self.compose(row, args, extra_attachments=extra_attachments) 1tszQieVjhcgU6'f
2195 outcome = self.deliver( 1tszQieVjhcgU6'f
2196 row, message, [*args["to"], *args["cc"], *args["bcc"], *extra_bcc]
2197 )
2198 return { 1szQieVjhcgUf
2199 **outcome,
2200 "account_id": row["id"],
2201 "from": row["email_address"],
2202 "to": args["to"],
2203 "cc": args["cc"],
2204 "subject": args["subject"],
2205 "message_id": message.get("Message-ID"),
2206 }
2208 def run_idempotently(
2209 self,
2210 actor_id: str,
2211 operation_name: str,
2212 args: dict[str, Any],
2213 operation: Callable[[dict[str, Any]], dict[str, Any]],
2214 ) -> dict[str, Any]:
2215 """Run a keyed email operation once and replay its result for one day."""
2216 data = {key: value for key, value in args.items() if key != "idempotency_key"} 2ebDcBcxcCc
2217 idempotency_key = args.get("idempotency_key") 2ebDcBcxcCc
2218 if not idempotency_key: 2ebDcBcxcCc
2219 return operation(data) 2ebCc
2220 scope_key = hashlib.sha256( 2DcBcxcCc
2221 f"{actor_id}\x1f{self.workspace_id}\x1f{operation_name}\x1f"
2222 f"{idempotency_key}".encode()
2223 ).hexdigest()
2224 name = f"email-op-{scope_key}" 2DcBcxcCc
2225 request_hash = hashlib.sha256( 2DcBcxcCc
2226 json.dumps(
2227 data, sort_keys=True, separators=(",", ":"), default=str
2228 ).encode()
2229 ).hexdigest()
2231 with self.vault.credential_lock(f"{self.workspace_id}:{name}"): 2DcBcxcCc
2232 existing = next( 2DcBcxcCc
2233 (
2234 item
2235 for item in self._metadata(self.IDEMPOTENCY_PROVIDER)
2236 if item.name == name
2237 ),
2238 None,
2239 )
2240 now = datetime.now(UTC) 2DcBcxcCc
2241 if existing is not None: 2DcBcxcCc
2242 record = self._secret(existing) 2DcBcxcCc
2243 if self._idempotency_expired(existing, record, now): 2DcBcxcCc
2244 self.vault.delete_credential(existing.id, context=self.context) 2xc
2245 existing = None 2xc
2246 if existing is not None: 2DcBcxcCc
2247 if record.get("request_hash") != request_hash: 2DcBcCc
2248 raise ServiceError( 2Cc
2249 "email.idempotency_conflict",
2250 "This idempotency key was already used with different arguments.",
2251 409,
2252 )
2253 if record.get("status") == "processing": 2DcBcCc
2254 raise ServiceError( 2Bc
2255 "email.idempotency_in_progress",
2256 "This request is still running or its outcome is unknown. "
2257 "Check its outcome before using a new key.",
2258 409,
2259 )
2260 if record.get("status") == "failed": 2DcBcCc
2261 details = dict(record.get("details") or {}) 2Bc
2262 details["cached_error"] = True 2Bc
2263 raise ServiceError( 2Bc
2264 str(record.get("code", "email.send_failed")),
2265 "This is a cached failure from an earlier attempt; no new "
2266 f"send was attempted. {record.get('message', 'Email send failed.')}",
2267 int(record.get("status_code", 502)),
2268 details=details,
2269 )
2270 response = record.get("response") 2DcCc
2271 if isinstance(response, dict): 2DcCc
2272 return {**response, "duplicate": True} 2Cc
2273 raise ServiceError( 2Dc
2274 "email.idempotency_in_progress",
2275 "This request is still running or its outcome is unknown. "
2276 "Check its outcome before using a new key.",
2277 409,
2278 )
2280 metadata = self.vault.create_credential( 2DcBcxcCc
2281 name=name,
2282 provider=self.IDEMPOTENCY_PROVIDER,
2283 scopes=["email:send"],
2284 secret=json.dumps(
2285 {"status": "processing", "request_hash": request_hash},
2286 separators=(",", ":"),
2287 ),
2288 actor=self.actor,
2289 scope=CredentialScope.for_roles(EMAIL_CREDENTIAL_ROLE),
2290 workspace_id=self.workspace_id,
2291 )
2292 # Commit the claim before contacting SMTP. If the worker stops, the
2293 # persisted claim prevents a retry from delivering a duplicate.
2294 try: 2DcBcxcCc
2295 response = operation(data) 2DcBcxcCc
2296 except ServiceError as error: 2Bc
2297 self._write_email_record( 2Bc
2298 metadata,
2299 {
2300 "status": "failed",
2301 "request_hash": request_hash,
2302 "code": error.code,
2303 "message": error.message,
2304 "status_code": error.status_code,
2305 "details": error.details,
2306 },
2307 )
2308 raise 2Bc
2309 self._write_email_record( 2DcxcCc
2310 metadata,
2311 {"status": "complete", "request_hash": request_hash, "response": response},
2312 )
2313 return response 2DcxcCc
2315 @staticmethod
2316 def _idempotency_expired(
2317 metadata: CredentialMetadata, record: dict[str, Any], now: datetime
2318 ) -> bool:
2319 retention = ( 2ycDcBcxcCc
2320 EMAIL_FAILURE_RETENTION
2321 if record.get("status") == "processing"
2322 else EMAIL_RESULT_RETENTION
2323 )
2324 return metadata.updated_at < now - retention 2ycDcBcxcCc
2326 # ------------------------------------------------------------------
2327 # Mail client operations beyond search, read and send
2328 # ------------------------------------------------------------------
2330 def _with_client(self, row: dict[str, Any], work: Any) -> Any:
2331 client = self._imap(row) 2bbcba n 2 7 , [ . r G _ R H T O I D A i e j h p c g 9 5 J C $
2332 try: 2bbcba n 2 7 , [ . r G _ R H T O I D A i e j h p c g 9 5 J C $
2333 return work(client) 2bbcba n 2 7 , [ . r G _ R H T O I D A i e j h p c g 9 5 J C $
2334 finally:
2335 try: 2bbcba n 2 7 , [ . r G _ R H T O I D A i e j h p c g 9 5 J C $
2336 client.logout() 2bbcba n 2 7 , [ . r G _ R H T O I D A i e j h p c g 9 5 J C $
2337 except (OSError, imaplib.IMAP4.error): 1a
2338 pass 1a
2340 def _parsed(
2341 self, actor_id: str, message_id: str
2342 ) -> tuple[dict[str, Any], str, int, int, email.message.EmailMessage]:
2343 row, folder, validity, uid = self._message_location(actor_id, message_id) 1an2rG_RHTOIDiejhpcg
2344 raw, _ = self._with_client( 1an2rG_RHTOIDiejhpcg
2345 row, lambda client: self._fetch_raw(client, folder, validity, uid)
2346 )
2347 message = BytesParser(policy=email.policy.default).parsebytes(raw) 1an2rGRHTOIDiejhpcg
2348 return row, folder, validity, uid, message 1an2rGRHTOIDiejhpcg
2350 def list_folders(self, actor_id: str, account_id: str | None) -> dict[str, Any]:
2351 row = self._selected_account(actor_id, account_id) 1a[.
2353 def read(client: imaplib.IMAP4) -> list[dict[str, Any]]: 1a[.
2354 folders = [] 1a[.
2355 for name, attributes in _list_folders(client)[:60]: 1a[.
2356 if "\\noselect" in attributes: 1a[.
2357 continue 1.
2358 special = next( 1a[.
2359 (
2360 alias
2361 for alias in (
2362 "sent",
2363 "drafts",
2364 "trash",
2365 "junk",
2366 "archive",
2367 "all",
2368 )
2369 if f"\\{alias}" in attributes
2370 ),
2371 "inbox" if name.upper() == "INBOX" else None,
2372 )
2373 if not special: 1a[.
2374 # Servers without special-use flags name them by convention.
2375 special = next( 1[.
2376 (
2377 alias
2378 for alias, (_, names) in _SPECIAL_FOLDERS.items()
2379 if name.lower() in names
2380 ),
2381 None,
2382 )
2383 entry: dict[str, Any] = {"name": name, "special_use": special} 1a[.
2384 try: 1a[.
2385 kind, data = client.status(_imap_quote(name), "(MESSAGES UNSEEN)") 1a[.
2386 except (imaplib.IMAP4.error, ServiceError): 1.
2387 kind, data = "NO", [] 1.
2388 if kind == "OK" and data and isinstance(data[0], bytes): 1a[.
2389 counts = dict( 1a.
2390 re.findall(rb"(MESSAGES|UNSEEN)\s+(\d+)", data[0], re.I)
2391 )
2392 entry["total"] = int(counts.get(b"MESSAGES", 0)) 1a.
2393 entry["unread"] = int(counts.get(b"UNSEEN", 0)) 1a.
2394 folders.append(entry) 1a[.
2395 return folders 1a[.
2397 return {"account_id": row["id"], "folders": self._with_client(row, read)} 1a[.
2399 def _own_addresses(self, actor_id: str) -> set[str]:
2400 return {str(row["email_address"]).lower() for row in self._all_rows()} 1jhpcg
2402 @staticmethod
2403 def _quoted(message: email.message.Message, text: str) -> str:
2404 sender = _decode_header(message.get("From")) 1hpcg
2405 when = message.get("Date") or "" 1hpcg
2406 quoted = "\n".join(f"> {line}" for line in text[:10_000].splitlines()) 1hpcg
2407 return f"On {when}, {sender} wrote:\n{quoted}" 1hpcg
2409 def reply(
2410 self, actor_id: str, message_id: str, args: dict[str, Any]
2411 ) -> dict[str, Any]:
2412 """Answer a message in its thread, recipients and headers worked out here."""
2413 row, folder, validity, uid, original = self._parsed(actor_id, message_id) 1jhpcg
2414 own = self._own_addresses(actor_id) 1jhpcg
2415 reply_to = getaddresses( 1jhpcg
2416 original.get_all("Reply-To", []) or original.get_all("From", [])
2417 )
2418 to = [ 1jhpcg
2419 formataddr(pair)
2420 for pair in reply_to
2421 if pair[1] and pair[1].lower() not in own
2422 ]
2423 cc: list[str] = [] 1jhpcg
2424 if args.get("reply_all"): 1jhpcg
2425 seen = {parseaddr(value)[1].lower() for value in to} 1j
2426 for pair in getaddresses( 1j
2427 original.get_all("To", []) + original.get_all("Cc", [])
2428 ):
2429 address = pair[1].lower() 1j
2430 if address and address not in own and address not in seen: 1j
2431 seen.add(address) 1j
2432 cc.append(formataddr(pair)) 1j
2433 if not to and not cc: 1jhpcg
2434 # Replying to your own message: send it to whoever it went to.
2435 to = [formataddr(pair) for pair in getaddresses(original.get_all("To", []))] 1g
2436 subject = _decode_header(original.get("Subject")) 1jhpcg
2437 if not re.match(r"(?i)re:", subject): 1jhpcg
2438 subject = f"Re: {subject}" 1hpcg
2439 references = [ 1jhpcg
2440 *" ".join(original.get_all("References", [])).split(),
2441 *([original["Message-ID"]] if original.get("Message-ID") else []),
2442 ][-20:]
2443 body = args["body_text"].rstrip() 1jhpcg
2444 if args.get("quote_original", True): 1jhpcg
2445 body = f"{body}\n\n{self._quoted(original, _email_text(original) or html_to_text(_email_text(original, html_body=True)))}" 1hpcg
2446 outgoing = { 1jhpcg
2447 "account_id": row["id"],
2448 "to": to,
2449 "cc": cc,
2450 "bcc": [],
2451 "reply_to": None,
2452 "subject": subject[:998],
2453 "body_text": body,
2454 "body_html": None,
2455 "in_reply_to": original.get("Message-ID"),
2456 "references": references,
2457 "attachments": args.get("attachments") or [],
2458 "include_signature": args.get("include_signature", True),
2459 }
2460 if args.get("save_as_draft"): 1jhpcg
2461 return self.save_draft(actor_id, outgoing) 1p
2462 result = self.send(actor_id, outgoing) 1jhcg
2464 def answered(client: imaplib.IMAP4) -> bool: 1jhcg
2465 kind, _ = client.select(_imap_quote(folder), readonly=False) 1jhcg
2466 if kind != "OK": 1jhcg
2467 return False 1c
2468 kind, _ = client.uid("store", str(uid), "+FLAGS.SILENT", "(\\Answered)") 1jhcg
2469 return kind == "OK" 1jhcg
2471 try: 1jhcg
2472 result["original_marked_answered"] = self._with_client(row, answered) 1jhcg
2473 except ServiceError: 1c
2474 # The reply went out; only the bookkeeping on the original failed.
2475 result["original_marked_answered"] = False 1c
2476 return result 1jhcg
2478 def forward(
2479 self, actor_id: str, message_id: str, args: dict[str, Any]
2480 ) -> dict[str, Any]:
2481 """Send a message and its attachments without passing them through the assistant.
2483 The message contents stay on the mail server until the final send.
2484 """
2485 row, _, _, _, original = self._parsed(actor_id, message_id) 1ie
2486 subject = _decode_header(original.get("Subject")) 1ie
2487 if not re.match(r"(?i)fwd?:", subject): 1ie
2488 subject = f"Fwd: {subject}" 1e
2489 header = "\n".join( 1ie
2490 f"{label}: {_decode_header(original.get(label))}"
2491 for label in ("From", "Date", "Subject", "To", "Cc")
2492 if original.get(label)
2493 )
2494 original_text = _email_text(original) or html_to_text( 1ie
2495 _email_text(original, html_body=True)
2496 )
2497 body = ( 1ie
2498 f"{(args.get('body_text') or '').rstrip()}\n\n"
2499 f"---------- Forwarded message ----------\n{header}\n\n{original_text[:50_000]}"
2500 ).lstrip()
2501 extra: list[tuple[bytes, str, str, str]] = [] 1ie
2502 if args.get("include_attachments", True): 1ie
2503 for part in original.walk(): 1ie
2504 filename = part.get_filename() 1ie
2505 if _is_attachment(part): 1ie
2506 maintype, _, subtype = part.get_content_type().partition("/") 1ie
2507 extra.append( 1ie
2508 (
2509 _part_payload(part),
2510 maintype or "application",
2511 subtype or "octet-stream",
2512 _decode_header(filename) or "attachment",
2513 )
2514 )
2515 outgoing = { 1ie
2516 "account_id": row["id"],
2517 "to": args["to"],
2518 "cc": args.get("cc") or [],
2519 "bcc": args.get("bcc") or [],
2520 "reply_to": None,
2521 "subject": subject[:998],
2522 "body_text": body,
2523 "body_html": None,
2524 "in_reply_to": None,
2525 "references": [],
2526 "attachments": [],
2527 "include_signature": args.get("include_signature", True),
2528 }
2529 if args.get("save_as_draft"): 1ie
2530 return self.save_draft(actor_id, outgoing, extra_attachments=extra) 1e
2531 return self.send(actor_id, outgoing, extra_attachments=extra) 1ie
2533 def save_draft(
2534 self,
2535 actor_id: str,
2536 args: dict[str, Any],
2537 *,
2538 extra_attachments: Sequence[tuple[bytes, str, str, str]] = (),
2539 ) -> dict[str, Any]:
2540 """Keep a message in Drafts, where the user can edit and send it."""
2541 row = self._selected_account(actor_id, args.get("account_id")) 1ep95J
2542 message = self.compose(row, args, extra_attachments=extra_attachments) 1ep95J
2543 if args.get("bcc"): 1ep95J
2544 # A draft keeps its Bcc so sending it later reaches everyone.
2545 message["Bcc"] = ", ".join(args["bcc"]) 15
2547 def store(client: imaplib.IMAP4) -> dict[str, Any]: 1ep95J
2548 folder = _special_folder(client, "drafts") 1ep95J
2549 if not folder: 1ep95J
2550 raise ServiceError( 19
2551 "email.drafts_unsupported",
2552 "This mailbox has no Drafts folder.",
2553 409,
2554 )
2555 kind, data = _append_imap_message( 1ep95J
2556 client, folder, message, "(\\Draft \\Seen)"
2557 )
2558 if kind != "OK": 1ep95J
2559 raise ServiceError( 19
2560 "email.draft_failed", "The draft could not be saved.", 502
2561 )
2562 text = b" ".join(item for item in data or [] if isinstance(item, bytes)) 1ep5J
2563 appended = re.search(rb"APPENDUID\s+(\d+)\s+(\d+)", text, re.I) 1ep5J
2564 draft_id = ( 1ep5J
2565 _b64(
2566 json.dumps(
2567 [
2568 row["id"],
2569 _decode_imap_utf7(folder),
2570 int(appended.group(1)),
2571 int(appended.group(2)),
2572 ],
2573 separators=(",", ":"),
2574 ).encode()
2575 )
2576 if appended
2577 else None
2578 )
2579 return { 1ep5J
2580 "saved": True,
2581 "draft_id": draft_id,
2582 "folder": _decode_imap_utf7(folder),
2583 }
2585 result = self._with_client(row, store) 1ep95J
2586 return {**result, "account_id": row["id"], "subject": args["subject"]} 1ep5J
2588 def send_draft(self, actor_id: str, message_id: str) -> dict[str, Any]:
2589 row, folder, validity, uid = self._message_location(actor_id, message_id) 2bbcbA C $
2590 raw, flags = self._with_client( 2bbcbA C $
2591 row, lambda client: self._fetch_raw(client, folder, validity, uid)
2592 )
2593 if b"\\draft" not in flags.lower().split(): 2bbcbA C $
2594 raise ServiceError("email.not_a_draft", "This message is not a draft.", 409) 1$
2595 draft = BytesParser(policy=email.policy.default).parsebytes(raw) 2bbcbA C $
2596 recipients = [ 2bbcbA C $
2597 formataddr(pair)
2598 for pair in getaddresses(
2599 draft.get_all("To", [])
2600 + draft.get_all("Cc", [])
2601 + draft.get_all("Bcc", [])
2602 )
2603 if pair[1]
2604 ]
2605 if not recipients: 2bbcbA C $
2606 raise ServiceError( 1$
2607 "email.no_recipients", "This draft has no recipients yet.", 409
2608 )
2609 del draft["Bcc"] 2bbcbA C
2610 del draft["Date"] 2bbcbA C
2611 del draft["Message-ID"] 2bbcbA C
2612 draft["Date"] = formatdate(localtime=True) 2bbcbA C
2613 draft["Message-ID"] = make_msgid(domain=row["email_address"].rpartition("@")[2]) 2bbcbA C
2614 result = self.deliver(row, draft, recipients) 2bbcbA C
2616 def discard(client: imaplib.IMAP4) -> bool: 2bbcbA C
2617 kind, _ = client.select(_imap_quote(folder), readonly=False) 2bbcbA C
2618 if kind != "OK" or "UIDPLUS" not in client.capabilities: 2bbcbA C
2619 return False 2bbcbA
2620 kind, _ = client.uid("store", str(uid), "+FLAGS.SILENT", "(\\Deleted)") 1AC
2621 if kind == "OK": 1AC
2622 kind, _ = client.uid("expunge", str(uid)) 1C
2623 return kind == "OK" 1AC
2625 try: 2bbcbA C
2626 result["draft_removed"] = self._with_client(row, discard) 2bbcbA C
2627 except ServiceError: 1A
2628 result["draft_removed"] = False 1A
2629 return { 2bbcbA C
2630 **result,
2631 "account_id": row["id"],
2632 "subject": _decode_header(draft.get("Subject")),
2633 }
2635 @staticmethod
2636 def _thread_uids(client: imaplib.IMAP4, header_ids: set[str]) -> set[int]:
2637 """UIDs of the messages naming any of these Message-IDs, in one SEARCH."""
2638 terms = [ 1aGRHOI
2639 ("HEADER", field, _imap_raw_quote(header_id.strip()))
2640 for header_id in sorted(header_ids)[:10]
2641 for field in ("MESSAGE-ID", "REFERENCES", "IN-REPLY-TO")
2642 ]
2643 if not terms: 1aGRHOI
2644 return set() 1R
2645 # IMAP's OR takes two keys, so n terms nest as: OR t1 OR t2 ... tn.
2646 criteria = [ 1aGHOI
2647 token
2648 for index, term in enumerate(terms)
2649 for token in (("OR", *term) if index < len(terms) - 1 else term)
2650 ]
2651 kind, data = client.uid("search", *criteria) 1aGHOI
2652 if kind != "OK" or not data or not data[0]: 1aGHOI
2653 return set() 1aHO
2654 return {int(item) for item in data[0].split()} 1aGHOI
2656 def thread(self, actor_id: str, message_id: str, limit: int = 30) -> dict[str, Any]:
2657 """Find the conversation across its folder and Sent, oldest first.
2659 Include at most ``limit`` messages.
2660 """
2661 row, folder, _, uid, original = self._parsed(actor_id, message_id) 1aG_RHTOI
2662 ids = { 1aGRHTOI
2663 value
2664 for value in [
2665 original.get("Message-ID"),
2666 original.get("In-Reply-To"),
2667 *" ".join(original.get_all("References", [])).split(),
2668 ]
2669 if value and re.fullmatch(r"<[^<>\s]+>", value.strip())
2670 }
2672 def gather(client: imaplib.IMAP4) -> list[dict[str, Any]]: 1aGRHTOI
2673 folders = [folder] 1aGRHTOI
2674 # Every \Sent folder: Apple Mail and webmail can each keep their own.
2675 for sent in _special_folders(client, "sent"): 1aGRHTOI
2676 if _decode_imap_utf7(sent) not in folders: 2676 ↛ 2675line 2676 didn't jump to line 2675 because the condition on line 2676 was always true1aGRHTOI
2677 folders.append(_decode_imap_utf7(sent)) 1aGRHTOI
2678 found: dict[str, dict[str, Any]] = {} 1aGRHTOI
2679 for name in folders: 1aGRHTOI
2680 kind, _ = client.select(_imap_quote(name), readonly=True) 1aGRHTOI
2681 if kind != "OK": 1aGRHTOI
2682 continue 1I
2683 validity = _uidvalidity(client) 1aGRHTOI
2684 if validity is None: 1aGRHTOI
2685 continue 1T
2686 uids = self._thread_uids(client, ids) 1aGRHOI
2687 if not uids: 1aGRHOI
2688 continue 1aRHO
2689 kind, fetched = client.uid( 1aGHOI
2690 "fetch",
2691 ",".join(map(str, sorted(uids)[-limit:])),
2692 "(UID FLAGS BODY.PEEK[HEADER.FIELDS (FROM TO CC SUBJECT DATE MESSAGE-ID)])",
2693 )
2694 if kind != "OK": 1aGHOI
2695 continue 1I
2696 for part in fetched or []: 1aGHOI
2697 if not isinstance(part, tuple): 1aGHOI
2698 continue 1aGHOI
2699 meta, raw_headers = part 1aGHOI
2700 uid_match = re.search(rb"\bUID\s+(\d+)", meta, re.I) 1aGHOI
2701 if not uid_match: 1aGHOI
2702 continue 1O
2703 found_uid = int(uid_match.group(1)) 1aGHI
2704 parsed = BytesParser(policy=email.policy.default).parsebytes( 1aGHI
2705 raw_headers
2706 )
2707 flags = re.search(rb"FLAGS\s+\(([^)]*)\)", meta, re.I) 1aGHI
2708 key = parsed.get("Message-ID") or f"{name}:{found_uid}" 1aGHI
2709 found.setdefault( 1aGHI
2710 key,
2711 {
2712 **_summary(
2713 parsed,
2714 _b64(
2715 json.dumps(
2716 [row["id"], name, validity, found_uid],
2717 separators=(",", ":"),
2718 ).encode()
2719 ),
2720 flags.group(1) if flags else b"",
2721 ),
2722 "folder": name,
2723 },
2724 )
2725 return list(found.values()) 1aGRHTOI
2727 items = self._with_client(row, gather) 1aGRHTOI
2729 def when(item: dict[str, Any]) -> float: 1aGRHTOI
2730 try: 1aGHI
2731 return email.utils.parsedate_to_datetime(item["date"]).timestamp() 1aGHI
2732 except (TypeError, ValueError, IndexError): 1G
2733 return 0.0 1G
2735 items.sort(key=when) 1aGRHTOI
2736 return {"account_id": row["id"], "messages": items[-limit:]} 1aGRHTOI
2738 def attachment_text(
2739 self, actor_id: str, attachment_id: str, max_chars: int
2740 ) -> dict[str, Any]:
2741 """The words in an attachment: plain text, HTML or PDF."""
2742 message_id, index = _parse_attachment_id(attachment_id) 2od[c]c^c_c`cn r D
2743 _, _, _, _, message = self._parsed(actor_id, message_id) 1nrD
2744 parts = list(message.walk()) 1nrD
2745 if index >= len(parts): 1nrD
2746 raise ServiceError( 1n
2747 "email.attachment_not_found", "Attachment not found.", 404
2748 )
2749 part = parts[index] 1nrD
2750 payload = _part_payload(part) 1nrD
2751 content_type = part.get_content_type() 1nrD
2752 if content_type == "application/pdf": 1nrD
2753 text = _pdf_text(payload) 1nD
2754 elif content_type == "text/html": 1nr
2755 text = html_to_text(_part_text(part)) 1nr
2756 elif content_type.startswith("text/") or content_type in { 1nr
2757 "application/json",
2758 "application/xml",
2759 }:
2760 text = _part_text(part) 1nr
2761 else:
2762 raise ServiceError( 1n
2763 "email.attachment_not_text",
2764 "Only text, HTML and PDF attachments can be read as text; download others.",
2765 415,
2766 )
2767 return { 1nr
2768 "filename": _decode_header(part.get_filename()) or "attachment",
2769 "content_type": content_type,
2770 "text": text[:max_chars],
2771 "truncated": len(text) > max_chars,
2772 }
2774 def respond_to_invite(
2775 self, actor_id: str, message_id: str, response: str, comment: str
2776 ) -> dict[str, Any]:
2777 """Answer an invitation with an iTIP REPLY the organiser's calendar can apply.
2779 The reply is sent to the invitation organiser.
2780 """
2781 row, _, _, _, message = self._parsed(actor_id, message_id) 2/ = Ac
2782 invites = [ 2/ = Ac
2783 invite
2784 for invite in _calendar_parts(message)
2785 if invite.get("method") in {"REQUEST", None} and invite.get("uid")
2786 ]
2787 if not invites: 2/ = Ac
2788 raise ServiceError( 2Ac
2789 "email.no_invitation",
2790 "This email has no calendar invitation to answer.",
2791 409,
2792 )
2793 invite = invites[0] 2/ = Ac
2794 organizer = invite.get("organizer") 2/ = Ac
2795 if not organizer or not re.fullmatch(r"[^\s@<>]+@[^\s@<>]+", organizer): 2/ = Ac
2796 raise ServiceError( 2Ac
2797 "email.no_organizer",
2798 "This invitation names no organiser to reply to.",
2799 409,
2800 )
2801 status = { 1/=
2802 "accepted": "ACCEPTED",
2803 "declined": "DECLINED",
2804 "tentative": "TENTATIVE",
2805 }[response]
2806 stamp = time.strftime("%Y%m%dT%H%M%SZ", time.gmtime()) 1/=
2807 lines = [ 1/=
2808 "BEGIN:VCALENDAR",
2809 "PRODID:-//Orcheo//MCP mail//EN",
2810 "VERSION:2.0",
2811 "METHOD:REPLY",
2812 "BEGIN:VEVENT",
2813 f"UID:{_ics_text(invite['uid'])}",
2814 f"DTSTAMP:{stamp}",
2815 f"ORGANIZER:mailto:{organizer}",
2816 f"ATTENDEE;PARTSTAT={status};CN={_ics_param(row['display_name'])}"
2817 f":mailto:{row['email_address']}",
2818 ]
2819 # The invitation is untrusted: only a plain number may be echoed back.
2820 if re.fullmatch(r"\d{1,9}", str(invite.get("sequence") or "")): 1/=
2821 lines.append(f"SEQUENCE:{invite['sequence']}") 1=
2822 summary = " ".join(str(invite.get("summary") or "").split()) 1/=
2823 if summary: 1/=
2824 lines.append(f"SUMMARY:{_ics_text(summary)}") 1/
2825 if comment: 1/=
2826 lines.append(f"COMMENT:{_ics_text(comment)}") 1/
2827 lines += ["END:VEVENT", "END:VCALENDAR"] 1/=
2828 label = { 1/=
2829 "accepted": "Accepted",
2830 "declined": "Declined",
2831 "tentative": "Tentative",
2832 }[response]
2833 outgoing = self.compose( 1/=
2834 row,
2835 {
2836 "to": [organizer],
2837 "cc": [],
2838 "subject": f"{label}: {summary or 'Invitation'}"[:998],
2839 "body_text": comment
2840 or f"{row['display_name']} has {response} this invitation.",
2841 "include_signature": False,
2842 },
2843 )
2844 outgoing.add_alternative( 1/=
2845 "\r\n".join(lines) + "\r\n", subtype="calendar", params={"method": "REPLY"}
2846 )
2847 result = self.deliver(row, outgoing, [organizer]) 1/=
2848 return { 1/=
2849 **result,
2850 "response": response,
2851 "uid": invite["uid"],
2852 "organizer": organizer,
2853 }
2855 def event_links(self, actor_id: str, message_id: str) -> dict[str, Any]:
2856 """Extract event links and calendar invitations from a message."""
2857 _, _, _, _, message = self._parsed(actor_id, message_id) 12
2858 text = " ".join([_email_text(message), _email_text(message, html_body=True)]) 12
2859 urls = list(dict.fromkeys(re.findall(r"https://[^\s\"'<>)]+", text))) 12
2860 known = ("eventbrite.", "meetup.com", "lu.ma", "luma.com", "partiful.com") 12
2861 ranked = sorted(urls, key=lambda url: not any(host in url for host in known)) 12
2862 return {"urls": ranked[:10], "calendar_invites": _calendar_parts(message)} 12
2864 def find_contacts(
2865 self, actor_id: str, account_id: str | None, query: str, limit: int
2866 ) -> dict[str, Any]:
2867 """People you have mailed with whose name or address matches."""
2868 row = self._selected_account(actor_id, account_id) 17,
2869 needle = query.replace("\r", " ").replace("\n", " ") 17,
2870 if not needle.isascii(): 17,
2871 raise ServiceError( 17
2872 "email.search_charset", "Contact search supports ASCII text only.", 400
2873 )
2875 def scan(client: imaplib.IMAP4) -> dict[str, dict[str, Any]]: 17,
2876 seen: dict[str, dict[str, Any]] = {} 17,
2877 folders = ["INBOX"] 17,
2878 folders += [ 17,
2879 _decode_imap_utf7(sent) for sent in _special_folders(client, "sent")
2880 ]
2881 for name in folders: 17,
2882 kind, _ = client.select(_imap_quote(name), readonly=True) 17,
2883 if kind != "OK": 17,
2884 continue 1,
2885 # Match locally over the latest headers: server-side address
2886 # search differs between servers and misses display names.
2887 kind, data = client.uid("search", "ALL") 17,
2888 if kind != "OK" or not data or not data[0]: 17,
2889 continue 1,
2890 recent = sorted(int(item) for item in data[0].split())[-200:] 17,
2891 kind, fetched = client.uid( 17,
2892 "fetch",
2893 ",".join(str(found_uid) for found_uid in recent),
2894 "(BODY.PEEK[HEADER.FIELDS (FROM TO CC)])",
2895 )
2896 if kind != "OK": 17,
2897 continue 1,
2898 for part in fetched or []: 17
2899 if not isinstance(part, tuple) or not isinstance(part[1], bytes): 17
2900 continue 17
2901 headers = BytesParser(policy=email.policy.default).parsebytes( 17
2902 part[1]
2903 )
2904 for display, address in getaddresses( 17
2905 headers.get_all("From", [])
2906 + headers.get_all("To", [])
2907 + headers.get_all("Cc", [])
2908 ):
2909 normalized_address = address.lower() 17
2910 if (
2911 not normalized_address
2912 or needle.lower()
2913 not in f"{display} {normalized_address}".lower()
2914 ):
2915 continue 17
2916 entry = seen.setdefault( 17
2917 normalized_address,
2918 {
2919 "email": normalized_address,
2920 "name": display,
2921 "messages": 0,
2922 },
2923 )
2924 entry["messages"] += 1 17
2925 entry["name"] = entry["name"] or display 17
2926 return seen 17,
2928 contacts = sorted( 17,
2929 self._with_client(row, scan).values(), key=lambda entry: -entry["messages"]
2930 )
2931 return {"contacts": contacts[:limit]} 17,
2933 # Scheduled sending ------------------------------------------------
2935 def schedule(
2936 self,
2937 actor_id: str,
2938 args: dict[str, Any],
2939 send_at: str,
2940 *,
2941 extra_bcc: Sequence[str] = (),
2942 extra_attachments: Sequence[tuple[bytes, str, str, str]] = (),
2943 ) -> dict[str, Any]:
2944 row = self._selected_account(actor_id, args.get("account_id")) 2| } ! ibt ^ ocs ( jbEcz ? f
2945 payload = { 2| } ! ibt ^ ocs ( jbEcz ? f
2946 "actor_id": actor_id,
2947 "account_id": row["id"],
2948 "args": {**args, "account_id": row["id"], "send_at": None},
2949 "extra_bcc": list(extra_bcc),
2950 "extra_attachments": [
2951 [base64.b64encode(content).decode(), maintype, subtype, filename]
2952 for content, maintype, subtype, filename in extra_attachments
2953 ],
2954 "subject": args["subject"][:200],
2955 "send_at": send_at,
2956 "status": "scheduled",
2957 "last_error": None,
2958 }
2959 scheduled_id = f"scheduled_email_{uuid.uuid4().hex}" 2| } ! ibt ^ ocs ( jbEcz ? f
2960 metadata = self.vault.create_credential( 2| } ! ibt ^ ocs ( jbEcz ? f
2961 name=scheduled_id,
2962 provider=self.SCHEDULE_PROVIDER,
2963 scopes=["email:schedule"],
2964 secret=json.dumps(payload, separators=(",", ":")),
2965 actor=self.actor,
2966 scope=CredentialScope.for_roles(EMAIL_CREDENTIAL_ROLE),
2967 workspace_id=self.workspace_id,
2968 )
2969 return { 2| } ! ibt ^ ocs ( jbEcz ? f
2970 "scheduled_id": str(metadata.id),
2971 "status": "scheduled",
2972 "send_at": send_at,
2973 "account_id": row["id"],
2974 }
2976 def list_scheduled(self, actor_id: str) -> list[dict[str, Any]]:
2977 del actor_id 2ebyc} ! ibt ^ ocs ( ucpcvcwcEc?
2978 results = [] 2ebyc} ! ibt ^ ocs ( ucpcvcwcEc?
2979 for metadata in self._metadata(self.SCHEDULE_PROVIDER): 2ebyc} ! ibt ^ ocs ( ucpcvcwcEc?
2980 schedule = self._secret(metadata) 2yc} ! ibt ^ s ( ucpcvcwcEc?
2981 if schedule.get("status") in {"scheduled", "sending", "failed", "partial"}: 2981 ↛ 2979line 2981 didn't jump to line 2979 because the condition on line 2981 was always true2yc} ! ibt ^ s ( ucpcvcwcEc?
2982 result = { 2yc} ! ibt ^ s ( ucpcvcwcEc?
2983 "scheduled_id": str(metadata.id),
2984 "account_id": schedule.get("account_id")
2985 or (schedule.get("args") or {}).get("account_id"),
2986 "subject": schedule.get("subject", ""),
2987 "send_at": schedule.get("send_at"),
2988 "status": schedule.get("status"),
2989 "last_error": schedule.get("last_error"),
2990 }
2991 if schedule.get("status") == "partial": 2yc} ! ibt ^ s ( ucpcvcwcEc?
2992 result.update(schedule["delivery"]) 1}(
2993 results.append(result) 2yc} ! ibt ^ s ( ucpcvcwcEc?
2994 return sorted(results, key=lambda item: item.get("send_at") or "") 2ebyc} ! ibt ^ ocs ( ucpcvcwcEc?
2996 def cleanup_idempotency(self) -> None:
2997 """Remove expired retry records, including abandoned claims."""
2998 now = datetime.now(UTC) 2ycxcf
2999 for metadata in self._metadata(self.IDEMPOTENCY_PROVIDER): 2ycxcf
3000 if metadata.updated_at >= now - EMAIL_RESULT_RETENTION: 2ycxc
3001 continue 2xc
3002 with self.vault.credential_lock(f"{self.workspace_id}:{metadata.name}"): 2ycxc
3003 current = self._email_record(metadata.id, self.IDEMPOTENCY_PROVIDER) 2ycxc
3004 if current and self._idempotency_expired( 3004 ↛ 2999line 3004 didn't jump to line 29992ycxc
3005 current, self._secret(current), now
3006 ):
3007 self.vault.delete_credential(current.id, context=self.context) 2ycxc
3009 def _email_record(
3010 self, credential_id: uuid.UUID, provider: str
3011 ) -> CredentialMetadata | None:
3012 try: 2| yc} ! ibt ^ ocs ( jbucpcvcwcz ? xcf
3013 metadata = self.vault.get_credential_metadata( 2| yc} ! ibt ^ ocs ( jbucpcvcwcz ? xcf
3014 credential_id, context=self.context
3015 )
3016 except (CredentialNotFoundError, WorkflowScopeError): 2| t ocjb
3017 return None 2| t ocjb
3018 if (
3019 metadata.provider == provider
3020 and metadata.workspace_id == self.workspace_id
3021 and metadata.template_id is None
3022 ):
3023 return metadata 2| yc} ! ibt ^ ocs ( jbucpcvcwcz ? xcf
3024 return None 2ocjb
3026 def _write_email_record(
3027 self, metadata: CredentialMetadata, record: dict[str, Any]
3028 ) -> None:
3029 self.vault.update_credential( 2| yc} ! ibt ^ s ( jbucpcvcwcz ? DcBcxcCcf
3030 credential_id=metadata.id,
3031 actor=self.actor,
3032 secret=json.dumps(record, separators=(",", ":"), default=str),
3033 context=self.context,
3034 )
3036 def cancel_scheduled(self, actor_id: str, scheduled_id: str) -> dict[str, Any]:
3037 """Stop a waiting message, or clear a failed or partly delivered one."""
3038 del actor_id 2| ibt oc(
3039 try: 2| ibt oc(
3040 credential_id = uuid.UUID(scheduled_id) 2| ibt oc(
3041 except ValueError: 2oc
3042 credential_id = None 2oc
3043 if credential_id is not None: 2| ibt oc(
3044 with self.vault.credential_lock(f"email-schedule:{credential_id}"): 2| ibt oc(
3045 metadata = self._email_record(credential_id, self.SCHEDULE_PROVIDER) 2| ibt oc(
3046 status = self._secret(metadata).get("status") if metadata else None 2| ibt oc(
3047 if metadata and status in {"scheduled", "failed", "partial"}: 2| ibt oc(
3048 self.vault.delete_credential(metadata.id, context=self.context) 2| t oc(
3049 return { 2| t oc(
3050 "scheduled_id": scheduled_id,
3051 "status": "cancelled" if status == "scheduled" else "dismissed",
3052 }
3053 raise ServiceError( 2| ibt oc
3054 "email.scheduled_not_found",
3055 "No scheduled email with that ID can be cancelled or dismissed.",
3056 404,
3057 )
3059 def _claim_schedule(self, credential_id: uuid.UUID) -> dict[str, Any] | None:
3060 with self.vault.credential_lock(f"email-schedule:{credential_id}"): 2| } ! ibt ^ s ( jbucpcvcwcz ? f
3061 metadata = self._email_record(credential_id, self.SCHEDULE_PROVIDER) 2| } ! ibt ^ s ( jbucpcvcwcz ? f
3062 if metadata is None: 2| } ! ibt ^ s ( jbucpcvcwcz ? f
3063 return None 2| jb
3064 schedule = self._secret(metadata) 2| } ! ibt ^ s ( jbucpcvcwcz ? f
3065 if schedule.get("status") != "scheduled": 2| } ! ibt ^ s ( jbucpcvcwcz ? f
3066 return None 2jb
3067 schedule["status"] = "sending" 2| } ! ibt ^ s ( jbucpcvcwcz ? f
3068 self._write_email_record(metadata, schedule) 2| } ! ibt ^ s ( jbucpcvcwcz ? f
3069 return schedule 2| } ! ibt ^ s ( jbucpcvcwcz ? f
3071 def _recover_schedule(self, credential_id: uuid.UUID, now: datetime) -> bool:
3072 with self.vault.credential_lock(f"email-schedule:{credential_id}"): 2yc^ jb
3073 metadata = self._email_record(credential_id, self.SCHEDULE_PROVIDER) 2yc^ jb
3074 if metadata is None: 2yc^ jb
3075 return False 2jb
3076 schedule = self._secret(metadata) 2yc^ jb
3077 status = schedule.get("status") 2yc^ jb
3078 age = now - metadata.updated_at 2yc^ jb
3079 if (
3080 status in {"cancelled", "sent"}
3081 or status in {"partial", "failed"}
3082 and age >= EMAIL_FAILURE_RETENTION
3083 ):
3084 self.vault.delete_credential(metadata.id, context=self.context) 2yc
3085 elif status == "sending" and age >= SCHEDULE_INTERRUPTED_AFTER: 2yc^ jb
3086 schedule.update( 2yc^
3087 status="failed",
3088 last_error="Interrupted while sending; check Sent before retrying.",
3089 )
3090 self._write_email_record(metadata, schedule) 2yc^
3091 return True 2yc^
3092 return False 2ycjb
3094 def _finish_schedule(
3095 self,
3096 credential_id: uuid.UUID,
3097 outcome: dict[str, Any] | None,
3098 error: str | None,
3099 ) -> None:
3100 with self.vault.credential_lock(f"email-schedule:{credential_id}"): 2| } ! t s ( jbucpcvcwcz ? f
3101 metadata = self._email_record(credential_id, self.SCHEDULE_PROVIDER) 2| } ! t s ( jbucpcvcwcz ? f
3102 if metadata is None: 2| } ! t s ( jbucpcvcwcz ? f
3103 return 2jb
3104 if outcome is not None and outcome["sent"]: 2| } ! t s ( ucpcvcwcz ? f
3105 self.vault.delete_credential(metadata.id, context=self.context) 1|szf
3106 return 1|szf
3107 schedule = self._secret(metadata) 2} ! t ( ucpcvcwc?
3108 schedule["account_id"] = (schedule.get("args") or {}).get("account_id") 2} ! t ( ucpcvcwc?
3109 if outcome is not None: 2} ! t ( ucpcvcwc?
3110 schedule.update( 1}(
3111 status="partial",
3112 last_error="SMTP refused some recipients. Check the delivery details.",
3113 delivery={
3114 field: outcome[field]
3115 for field in (
3116 "delivery_status",
3117 "refused_recipients",
3118 "message_id",
3119 "saved_to_sent",
3120 )
3121 },
3122 args=None,
3123 extra_bcc=[],
3124 extra_attachments=[],
3125 )
3126 else:
3127 schedule.update(status="failed", last_error=error) 2! t ucpcvcwc?
3128 self._write_email_record(metadata, schedule) 2} ! t ( ucpcvcwc?
3130 def process_scheduled(self, limit: int = 20) -> dict[str, int]:
3131 """Send due workspace emails from their encrypted vault records.
3133 ``recovered`` counts interrupted sends this pass marked as failed; those
3134 are housekeeping, not deliveries attempted now.
3135 """
3136 counts = {"sent": 0, "failed": 0, "recovered": 0} 2| yc} ! t ^ s ( ucpcvcwcz ? f
3137 now = datetime.now(UTC) 2| yc} ! t ^ s ( ucpcvcwcz ? f
3138 due: list[tuple[datetime, uuid.UUID]] = [] 2| yc} ! t ^ s ( ucpcvcwcz ? f
3139 for metadata in self._metadata(self.SCHEDULE_PROVIDER): 2| yc} ! t ^ s ( ucpcvcwcz ? f
3140 schedule = self._secret(metadata) 2| yc} ! t ^ s ( ucpcvcwcz ? f
3141 status = schedule.get("status") 2| yc} ! t ^ s ( ucpcvcwcz ? f
3142 if status != "scheduled": 2| yc} ! t ^ s ( ucpcvcwcz ? f
3143 age = now - metadata.updated_at 2yc} t ^ ucpcvcwc
3144 if (
3145 status in {"cancelled", "sent"}
3146 or status == "sending"
3147 and age >= SCHEDULE_INTERRUPTED_AFTER
3148 or status in {"partial", "failed"}
3149 and age >= EMAIL_FAILURE_RETENTION
3150 ) and self._recover_schedule(metadata.id, now):
3151 counts["recovered"] += 1 2yc^
3152 continue 2yc} t ^ ucpcvcwc
3153 try: 2| } ! t s ( ucpcvcwcz ? f
3154 send_at = datetime.fromisoformat(schedule["send_at"]) 2| } ! t s ( ucpcvcwcz ? f
3155 if send_at.utcoffset() is None: 2| } ! t s ( pcz ? f
3156 raise ValueError("A timezone is required") 2pc
3157 except (KeyError, TypeError, ValueError): 2ucpcvcwc
3158 if self._claim_schedule(metadata.id) is not None: 3158 ↛ 3163line 3158 didn't jump to line 3163 because the condition on line 3158 was always true2ucpcvcwc
3159 self._finish_schedule( 2ucpcvcwc
3160 metadata.id, None, "Scheduled time is invalid."
3161 )
3162 counts["failed"] += 1 2ucpcvcwc
3163 continue 2ucpcvcwc
3164 if send_at <= now: 1|}!ts(z?f
3165 due.append((send_at, metadata.id)) 1|}!ts(z?f
3166 for _, credential_id in sorted(due)[:limit]: 2| yc} ! t ^ s ( ucpcvcwcz ? f
3167 claimed = self._claim_schedule(credential_id) 1|}!ts(z?f
3168 if claimed is None: 1|}!ts(z?f
3169 continue 1|
3170 try: 1|}!ts(z?f
3171 outcome = self.send( 1|}!ts(z?f
3172 claimed["actor_id"],
3173 claimed["args"],
3174 extra_bcc=claimed.get("extra_bcc") or [],
3175 extra_attachments=[
3176 (base64.b64decode(content), maintype, subtype, filename)
3177 for content, maintype, subtype, filename in claimed.get(
3178 "extra_attachments"
3179 )
3180 or []
3181 ],
3182 )
3183 except Exception as error: 1!t?
3184 message = ( 1!t?
3185 error.message
3186 if isinstance(error, ServiceError)
3187 else f"Scheduled email failed ({type(error).__name__})."
3188 )
3189 self._finish_schedule(credential_id, None, message) 1!t?
3190 counts["failed"] += 1 1!t?
3191 else:
3192 self._finish_schedule(credential_id, outcome, None) 1|}s(zf
3193 counts["sent" if outcome["sent"] else "failed"] += 1 1|}s(zf
3194 return counts 2| yc} ! t ^ s ( ucpcvcwcz ? f
3197def _pdf_text(payload: bytes) -> str:
3198 from pypdf import PdfReader 21dn D
3199 from pypdf.errors import PdfReadError 21dn D
3201 try: 21dn D
3202 reader = PdfReader(io.BytesIO(payload)) 21dn D
3203 return "\n\n".join((page.extract_text() or "") for page in reader.pages[:50]) 21dn
3204 except (PdfReadError, ValueError, KeyError) as error: 21dD
3205 raise ServiceError( 21dD
3206 "email.attachment_unreadable", "This PDF could not be read.", 422
3207 ) from error