forktex-mail 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- forktex_mail/__init__.py +87 -0
- forktex_mail/errors.py +239 -0
- forktex_mail/imap.py +673 -0
- forktex_mail/mailbox.py +254 -0
- forktex_mail/message.py +410 -0
- forktex_mail/py.typed +0 -0
- forktex_mail/ratelimit.py +125 -0
- forktex_mail/smtp.py +409 -0
- forktex_mail/testing.py +94 -0
- forktex_mail-1.0.0.dist-info/METADATA +133 -0
- forktex_mail-1.0.0.dist-info/RECORD +14 -0
- forktex_mail-1.0.0.dist-info/WHEEL +4 -0
- forktex_mail-1.0.0.dist-info/licenses/LICENSE +45 -0
- forktex_mail-1.0.0.dist-info/licenses/NOTICE +18 -0
forktex_mail/__init__.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
# Copyright (C) 2026 FORKTEX S.R.L.
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: AGPL-3.0-or-later OR LicenseRef-ForkTex-Commercial
|
|
4
|
+
#
|
|
5
|
+
# This file is part of ForkTex Mail.
|
|
6
|
+
#
|
|
7
|
+
# For commercial licensing -- including use in proprietary products, SaaS
|
|
8
|
+
# deployments, or any context where AGPL obligations cannot be met -- you
|
|
9
|
+
# MUST obtain a commercial license from FORKTEX S.R.L. (info@forktex.com).
|
|
10
|
+
#
|
|
11
|
+
# This program is free software: you can redistribute it and/or modify
|
|
12
|
+
# it under the terms of the GNU Affero General Public License as published by
|
|
13
|
+
# the Free Software Foundation, either version 3 of the License, or
|
|
14
|
+
# (at your option) any later version.
|
|
15
|
+
#
|
|
16
|
+
# This program is distributed in the hope that it will be useful,
|
|
17
|
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
18
|
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
19
|
+
# GNU Affero General Public License for more details.
|
|
20
|
+
#
|
|
21
|
+
# You should have received a copy of the GNU Affero General Public License
|
|
22
|
+
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import logging
|
|
27
|
+
from importlib.metadata import version
|
|
28
|
+
|
|
29
|
+
from forktex_mail.errors import Kind, MailError
|
|
30
|
+
from forktex_mail.imap import (
|
|
31
|
+
Fetched,
|
|
32
|
+
Folder,
|
|
33
|
+
MailFolder,
|
|
34
|
+
Messages,
|
|
35
|
+
archive,
|
|
36
|
+
delete,
|
|
37
|
+
fetch,
|
|
38
|
+
folders,
|
|
39
|
+
mark,
|
|
40
|
+
messages,
|
|
41
|
+
move,
|
|
42
|
+
)
|
|
43
|
+
from forktex_mail.mailbox import ImapSecurity, Mailbox, Security
|
|
44
|
+
from forktex_mail.message import Address, Attachment, Bounce, BouncedRecipient, Received, compose, parse
|
|
45
|
+
from forktex_mail.ratelimit import RateLimit, acquire
|
|
46
|
+
from forktex_mail.smtp import Probe, Refusal, Sent, Smtp, Transport, probe, send
|
|
47
|
+
from forktex_mail.testing import Capture
|
|
48
|
+
|
|
49
|
+
__version__ = version("forktex-mail")
|
|
50
|
+
|
|
51
|
+
logging.getLogger(__name__).addHandler(logging.NullHandler())
|
|
52
|
+
|
|
53
|
+
__all__ = [
|
|
54
|
+
"Address",
|
|
55
|
+
"Attachment",
|
|
56
|
+
"Bounce",
|
|
57
|
+
"BouncedRecipient",
|
|
58
|
+
"Capture",
|
|
59
|
+
"Fetched",
|
|
60
|
+
"Folder",
|
|
61
|
+
"ImapSecurity",
|
|
62
|
+
"Kind",
|
|
63
|
+
"MailError",
|
|
64
|
+
"MailFolder",
|
|
65
|
+
"Mailbox",
|
|
66
|
+
"Messages",
|
|
67
|
+
"Probe",
|
|
68
|
+
"RateLimit",
|
|
69
|
+
"Received",
|
|
70
|
+
"Refusal",
|
|
71
|
+
"Security",
|
|
72
|
+
"Sent",
|
|
73
|
+
"Smtp",
|
|
74
|
+
"Transport",
|
|
75
|
+
"acquire",
|
|
76
|
+
"archive",
|
|
77
|
+
"compose",
|
|
78
|
+
"delete",
|
|
79
|
+
"fetch",
|
|
80
|
+
"folders",
|
|
81
|
+
"mark",
|
|
82
|
+
"messages",
|
|
83
|
+
"move",
|
|
84
|
+
"parse",
|
|
85
|
+
"probe",
|
|
86
|
+
"send",
|
|
87
|
+
]
|
forktex_mail/errors.py
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
# Copyright (C) 2026 FORKTEX S.R.L.
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: AGPL-3.0-or-later OR LicenseRef-ForkTex-Commercial
|
|
4
|
+
#
|
|
5
|
+
# This file is part of ForkTex Mail.
|
|
6
|
+
#
|
|
7
|
+
# For commercial licensing -- including use in proprietary products, SaaS
|
|
8
|
+
# deployments, or any context where AGPL obligations cannot be met -- you
|
|
9
|
+
# MUST obtain a commercial license from FORKTEX S.R.L. (info@forktex.com).
|
|
10
|
+
#
|
|
11
|
+
# This program is free software: you can redistribute it and/or modify
|
|
12
|
+
# it under the terms of the GNU Affero General Public License as published by
|
|
13
|
+
# the Free Software Foundation, either version 3 of the License, or
|
|
14
|
+
# (at your option) any later version.
|
|
15
|
+
#
|
|
16
|
+
# This program is distributed in the hope that it will be useful,
|
|
17
|
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
18
|
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
19
|
+
# GNU Affero General Public License for more details.
|
|
20
|
+
#
|
|
21
|
+
# You should have received a copy of the GNU Affero General Public License
|
|
22
|
+
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import imaplib
|
|
27
|
+
import re
|
|
28
|
+
import ssl
|
|
29
|
+
from collections.abc import Sequence
|
|
30
|
+
from typing import Literal
|
|
31
|
+
|
|
32
|
+
from aiosmtplib import (
|
|
33
|
+
SMTPAuthenticationError,
|
|
34
|
+
SMTPRecipientsRefused,
|
|
35
|
+
SMTPResponseException,
|
|
36
|
+
SMTPSenderRefused,
|
|
37
|
+
)
|
|
38
|
+
from forktex.error import AppError, AppErrorCode
|
|
39
|
+
from forktex.log import get_logger
|
|
40
|
+
|
|
41
|
+
Kind = Literal["invalid", "config", "auth", "tls", "unreachable", "deferred", "rejected", "unknown"]
|
|
42
|
+
|
|
43
|
+
_CODES: dict[Kind, AppErrorCode] = {
|
|
44
|
+
"invalid": AppErrorCode.VALIDATION,
|
|
45
|
+
"config": AppErrorCode.INTERNAL,
|
|
46
|
+
"auth": AppErrorCode.INTERNAL,
|
|
47
|
+
"tls": AppErrorCode.INTERNAL,
|
|
48
|
+
"unreachable": AppErrorCode.UNAVAILABLE,
|
|
49
|
+
"deferred": AppErrorCode.RATE_LIMITED,
|
|
50
|
+
"rejected": AppErrorCode.FAILED,
|
|
51
|
+
"unknown": AppErrorCode.FAILED,
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
_EXCEEDED_STORAGE = 552
|
|
55
|
+
_ENHANCED = re.compile(r"^\s*([245])\.(\d{1,3})\.(\d{1,3})\b")
|
|
56
|
+
_IMAP_CODE = re.compile(r"^\s*\[([A-Z-]+)")
|
|
57
|
+
_REFUSED: dict[Kind, str] = {
|
|
58
|
+
"deferred": "refused by the server for now",
|
|
59
|
+
"rejected": "refused by the server",
|
|
60
|
+
"unreachable": "an answer outside the protocol",
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
log = get_logger(__name__)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class ReplyTooLong(Exception):
|
|
67
|
+
pass
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class MailError(AppError):
|
|
71
|
+
def __init__(self, message: str, *, kind: Kind, reply: int | None = None, enhanced: str | None = None) -> None:
|
|
72
|
+
super().__init__(message, details={"kind": kind, "reply": reply, "enhanced": enhanced})
|
|
73
|
+
self.code = _CODES[kind]
|
|
74
|
+
self.kind: Kind = kind
|
|
75
|
+
self.reply = reply
|
|
76
|
+
self.enhanced = enhanced
|
|
77
|
+
|
|
78
|
+
def __reduce__(self) -> tuple[object, ...]:
|
|
79
|
+
return (_rebuild, (self.args[0] if self.args else "", self.kind, self.reply, self.enhanced))
|
|
80
|
+
|
|
81
|
+
@property
|
|
82
|
+
def transient(self) -> bool:
|
|
83
|
+
return self.kind in ("unreachable", "deferred")
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _rebuild(message: str, kind: Kind, reply: int | None, enhanced: str | None) -> MailError:
|
|
87
|
+
return MailError(message, kind=kind, reply=reply, enhanced=enhanced)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def enhanced_status(text: str) -> str | None:
|
|
91
|
+
match = _ENHANCED.match(text)
|
|
92
|
+
return ".".join(match.groups()) if match else None
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def reply_kind(reply: int, text: str) -> Kind:
|
|
96
|
+
status = enhanced_status(text)
|
|
97
|
+
status_class = reply // 100
|
|
98
|
+
if status and status_class not in (4, 5):
|
|
99
|
+
status_class = int(status[0])
|
|
100
|
+
if status_class == 4:
|
|
101
|
+
return "deferred"
|
|
102
|
+
if status_class == 5:
|
|
103
|
+
return "rejected"
|
|
104
|
+
return "unreachable"
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def refused_for_size(reply: int, status: str | None) -> bool:
|
|
108
|
+
if status is not None:
|
|
109
|
+
return status.endswith(".3.4")
|
|
110
|
+
return reply == _EXCEEDED_STORAGE
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def recipient_refusal_is_transient(reply: int, text: str) -> bool:
|
|
114
|
+
return reply == _EXCEEDED_STORAGE or reply_kind(reply, text) == "deferred"
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _tls_failure(exc: BaseException) -> bool:
|
|
118
|
+
seen: set[int] = set()
|
|
119
|
+
current: BaseException | None = exc
|
|
120
|
+
while current is not None and id(current) not in seen:
|
|
121
|
+
if isinstance(current, ssl.SSLError):
|
|
122
|
+
return True
|
|
123
|
+
seen.add(id(current))
|
|
124
|
+
current = current.__cause__ or current.__context__
|
|
125
|
+
return False
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _classified(
|
|
129
|
+
message: str, said: object, *, kind: Kind, reply: int | None = None, enhanced: str | None = None
|
|
130
|
+
) -> MailError:
|
|
131
|
+
log.warning("%s (%s): %s", message, kind, said)
|
|
132
|
+
return MailError(message, kind=kind, reply=reply, enhanced=enhanced)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def outcome_unknown(said: object, prefix: str, *, what: str = "the connection was lost") -> MailError:
|
|
136
|
+
return _classified(f"{prefix}: {what} after the message was sent; the server may have it", said, kind="unknown")
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def every_recipient_refused(prefix: str, refusals: Sequence[tuple[int, str | None, bool]]) -> MailError:
|
|
140
|
+
reply, enhanced, _ = refusals[0] if refusals else (None, None, False)
|
|
141
|
+
transient = bool(refusals) and all(temporary for _, _, temporary in refusals)
|
|
142
|
+
return MailError(
|
|
143
|
+
f"{prefix}: every recipient refused",
|
|
144
|
+
kind="deferred" if transient else "rejected",
|
|
145
|
+
reply=reply,
|
|
146
|
+
enhanced=enhanced,
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def smtp_error(exc: BaseException, prefix: str, *, connecting: bool = False) -> MailError:
|
|
151
|
+
if isinstance(exc, SMTPRecipientsRefused):
|
|
152
|
+
log.warning("%s: every recipient refused: %s", prefix, " | ".join(r.message for r in exc.recipients))
|
|
153
|
+
return every_recipient_refused(
|
|
154
|
+
prefix,
|
|
155
|
+
[
|
|
156
|
+
(r.code, enhanced_status(r.message), recipient_refusal_is_transient(r.code, r.message))
|
|
157
|
+
for r in exc.recipients
|
|
158
|
+
],
|
|
159
|
+
)
|
|
160
|
+
if isinstance(exc, SMTPAuthenticationError):
|
|
161
|
+
return _classified(
|
|
162
|
+
f"{prefix}: login refused",
|
|
163
|
+
exc.message,
|
|
164
|
+
kind="deferred" if reply_kind(exc.code, exc.message) == "deferred" else "auth",
|
|
165
|
+
reply=exc.code,
|
|
166
|
+
enhanced=enhanced_status(exc.message),
|
|
167
|
+
)
|
|
168
|
+
if connecting and _tls_failure(exc):
|
|
169
|
+
return _classified(f"{prefix}: TLS failed while connecting", exc, kind="tls")
|
|
170
|
+
if (
|
|
171
|
+
isinstance(exc, SMTPResponseException)
|
|
172
|
+
and reply_kind(exc.code, exc.message) == "rejected"
|
|
173
|
+
and refused_for_size(exc.code, enhanced_status(exc.message))
|
|
174
|
+
):
|
|
175
|
+
return _classified(
|
|
176
|
+
f"{prefix}: the message is larger than the server accepts",
|
|
177
|
+
exc.message,
|
|
178
|
+
kind="invalid",
|
|
179
|
+
reply=exc.code,
|
|
180
|
+
enhanced=enhanced_status(exc.message),
|
|
181
|
+
)
|
|
182
|
+
if isinstance(exc, SMTPSenderRefused) and reply_kind(exc.code, exc.message) == "rejected":
|
|
183
|
+
status = enhanced_status(exc.message)
|
|
184
|
+
return _classified(
|
|
185
|
+
f"{prefix}: the server will not send as {exc.sender!r}",
|
|
186
|
+
exc.message,
|
|
187
|
+
kind="config",
|
|
188
|
+
reply=exc.code,
|
|
189
|
+
enhanced=status,
|
|
190
|
+
)
|
|
191
|
+
if isinstance(exc, SMTPResponseException):
|
|
192
|
+
kind = reply_kind(exc.code, exc.message)
|
|
193
|
+
return _classified(
|
|
194
|
+
f"{prefix}: {_REFUSED[kind]}", exc.message, kind=kind, reply=exc.code, enhanced=enhanced_status(exc.message)
|
|
195
|
+
)
|
|
196
|
+
if isinstance(exc, OSError):
|
|
197
|
+
return _classified(f"{prefix}: the connection failed", exc, kind="unreachable")
|
|
198
|
+
return _classified(f"{prefix}: unexpected {type(exc).__name__}", exc, kind="rejected")
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def imap_refusal(text: str, prefix: str, *, otherwise: Kind, folder: str | None = None) -> MailError:
|
|
202
|
+
code = _IMAP_CODE.search(text)
|
|
203
|
+
kinds: dict[str, Kind] = {
|
|
204
|
+
"LIMIT": "deferred",
|
|
205
|
+
"OVERQUOTA": "deferred",
|
|
206
|
+
"UNAVAILABLE": "unreachable",
|
|
207
|
+
"SERVERBUG": "unreachable",
|
|
208
|
+
"INUSE": "unreachable",
|
|
209
|
+
"NONEXISTENT": "config",
|
|
210
|
+
"TRYCREATE": "config",
|
|
211
|
+
"CANNOT": "invalid",
|
|
212
|
+
"AUTHENTICATIONFAILED": "auth",
|
|
213
|
+
"AUTHORIZATIONFAILED": "auth",
|
|
214
|
+
"EXPIRED": "auth",
|
|
215
|
+
"PRIVACYREQUIRED": "tls",
|
|
216
|
+
}
|
|
217
|
+
error = _classified(
|
|
218
|
+
f"{prefix}: refused by the server",
|
|
219
|
+
text if folder is None else f"{text} (folder {folder!r})",
|
|
220
|
+
kind=kinds.get(code[1], otherwise) if code else otherwise,
|
|
221
|
+
)
|
|
222
|
+
error.__cause__ = imaplib.IMAP4.error(text)
|
|
223
|
+
return error
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def imap_error(exc: BaseException, prefix: str, *, connecting: bool = False, during_login: bool = False) -> MailError:
|
|
227
|
+
if connecting and _tls_failure(exc):
|
|
228
|
+
return _classified(f"{prefix}: TLS failed while connecting", exc, kind="tls")
|
|
229
|
+
if isinstance(exc, ReplyTooLong):
|
|
230
|
+
return _classified(f"{prefix}: a reply longer than this library reads", exc, kind="rejected")
|
|
231
|
+
if isinstance(exc, imaplib.IMAP4.readonly):
|
|
232
|
+
return _classified(f"{prefix}: the folder is read-only for this account", exc, kind="config")
|
|
233
|
+
if isinstance(exc, imaplib.IMAP4.abort | OSError):
|
|
234
|
+
return _classified(f"{prefix}: the connection failed", exc, kind="unreachable")
|
|
235
|
+
if not isinstance(exc, imaplib.IMAP4.error):
|
|
236
|
+
return _classified(f"{prefix}: unexpected {type(exc).__name__}", exc, kind="rejected")
|
|
237
|
+
said = exc.args[0] if exc.args else ""
|
|
238
|
+
text = said.decode(errors="replace") if isinstance(said, bytes) else str(said)
|
|
239
|
+
return imap_refusal(text, prefix, otherwise="auth" if during_login else "rejected")
|