mailadapter 0.1.0.dev1__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.
- mailadapter/__init__.py +43 -0
- mailadapter/exceptions.py +46 -0
- mailadapter/imap/__init__.py +0 -0
- mailadapter/imap/_base.py +92 -0
- mailadapter/imap/async_client.py +45 -0
- mailadapter/imap/client.py +46 -0
- mailadapter/imap/connection.py +129 -0
- mailadapter/imap/search.py +48 -0
- mailadapter/py.typed +0 -0
- mailadapter/servers.py +69 -0
- mailadapter/smtp/__init__.py +0 -0
- mailadapter/utils/__init__.py +0 -0
- mailadapter/utils/normalization.py +34 -0
- mailadapter-0.1.0.dev1.dist-info/METADATA +266 -0
- mailadapter-0.1.0.dev1.dist-info/RECORD +17 -0
- mailadapter-0.1.0.dev1.dist-info/WHEEL +4 -0
- mailadapter-0.1.0.dev1.dist-info/licenses/LICENSE +21 -0
mailadapter/__init__.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
from .imap.client import IMAPClient
|
|
2
|
+
from .imap.async_client import AsyncIMAPClient
|
|
3
|
+
from .imap.search import SearchCriteria
|
|
4
|
+
from .servers import ServerConfig, SMTPServers, IMAPServers, TLSMode
|
|
5
|
+
|
|
6
|
+
from .exceptions import (
|
|
7
|
+
MailAdapterError,
|
|
8
|
+
IMAPError,
|
|
9
|
+
SMTPError,
|
|
10
|
+
|
|
11
|
+
EmailClientError,
|
|
12
|
+
FetchError,
|
|
13
|
+
EmailConnectionError,
|
|
14
|
+
AuthenticationError,
|
|
15
|
+
SendError,
|
|
16
|
+
SearchError,
|
|
17
|
+
MailboxError,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
__all__ = [
|
|
23
|
+
'AsyncIMAPClient',
|
|
24
|
+
'IMAPClient',
|
|
25
|
+
'IMAPError',
|
|
26
|
+
'SMTPError',
|
|
27
|
+
|
|
28
|
+
'SearchCriteria',
|
|
29
|
+
|
|
30
|
+
'MailAdapterError',
|
|
31
|
+
'EmailClientError',
|
|
32
|
+
'FetchError',
|
|
33
|
+
'EmailConnectionError',
|
|
34
|
+
'AuthenticationError',
|
|
35
|
+
'SendError',
|
|
36
|
+
'SearchError',
|
|
37
|
+
'MailboxError',
|
|
38
|
+
|
|
39
|
+
'ServerConfig',
|
|
40
|
+
'SMTPServers',
|
|
41
|
+
'IMAPServers',
|
|
42
|
+
'TLSMode'
|
|
43
|
+
]
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
class MailAdapterError(Exception):
|
|
2
|
+
"""Base exception for all mailadapter errors."""
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
# ----- Client
|
|
7
|
+
class EmailClientError(MailAdapterError):
|
|
8
|
+
'''Base exception for email client operations.'''
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class EmailConnectionError(EmailClientError):
|
|
12
|
+
'''Failed to establish or maintain a connection.'''
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class AuthenticationError(EmailClientError):
|
|
16
|
+
'''Authentication with the email server failed.'''
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
# ----- IMAP
|
|
22
|
+
class IMAPError(EmailClientError):
|
|
23
|
+
'''Base exception for IMAP operations.'''
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class MailboxError(IMAPError):
|
|
27
|
+
'''Mailbox selection or management failed.'''
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class SearchError(IMAPError):
|
|
31
|
+
'''Email search failed.'''
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class FetchError(IMAPError):
|
|
35
|
+
'''Email retrieval failed.'''
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
# ----- SMTP
|
|
41
|
+
class SMTPError(EmailClientError):
|
|
42
|
+
'''Base exception for SMTP operations.'''
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class SendError(SMTPError):
|
|
46
|
+
'''Email transmission failed.'''
|
|
File without changes
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import imaplib
|
|
2
|
+
|
|
3
|
+
from email import message_from_bytes
|
|
4
|
+
from email.message import EmailMessage
|
|
5
|
+
from email.policy import default
|
|
6
|
+
|
|
7
|
+
from .connection import IMAPConnection
|
|
8
|
+
from ..servers import ServerConfig
|
|
9
|
+
|
|
10
|
+
from ..exceptions import (
|
|
11
|
+
SearchError,
|
|
12
|
+
FetchError,
|
|
13
|
+
EmailConnectionError,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class _BaseIMAPClient:
|
|
21
|
+
def __init__(self, server: str | ServerConfig, username: str, password: str, *, mailbox: str='INBOX', timeout: float=30.0):
|
|
22
|
+
self.server = (
|
|
23
|
+
ServerConfig(server, 993)
|
|
24
|
+
if isinstance(server, str)
|
|
25
|
+
else server
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
self.username = username
|
|
29
|
+
self.password = password
|
|
30
|
+
self.mailbox = mailbox
|
|
31
|
+
self.timeout = timeout
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _imap(self) -> IMAPConnection:
|
|
35
|
+
return IMAPConnection(
|
|
36
|
+
server=self.server.host,
|
|
37
|
+
port=self.server.port,
|
|
38
|
+
username=self.username,
|
|
39
|
+
password=self.password,
|
|
40
|
+
tls=self.server.tls,
|
|
41
|
+
mailbox=self.mailbox,
|
|
42
|
+
timeout=self.timeout
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _imap_fetch(self, *criteria: str) -> list[EmailMessage]:
|
|
47
|
+
emails: list[EmailMessage] = list()
|
|
48
|
+
|
|
49
|
+
with self._imap() as imap:
|
|
50
|
+
try:
|
|
51
|
+
status, data = imap.uid('SEARCH', None, *criteria)
|
|
52
|
+
|
|
53
|
+
except (OSError, imaplib.IMAP4.abort) as exc:
|
|
54
|
+
raise EmailConnectionError(
|
|
55
|
+
"Connection lost during IMAP search"
|
|
56
|
+
) from exc
|
|
57
|
+
|
|
58
|
+
except imaplib.IMAP4.error as exc:
|
|
59
|
+
raise SearchError("IMAP search failed") from exc
|
|
60
|
+
|
|
61
|
+
if status != "OK":
|
|
62
|
+
raise SearchError("IMAP search failed")
|
|
63
|
+
|
|
64
|
+
for email_id in data[0].split():
|
|
65
|
+
try:
|
|
66
|
+
status, response = imap.uid('FETCH', email_id, '(BODY.PEEK[])')
|
|
67
|
+
|
|
68
|
+
except (OSError, imaplib.IMAP4.abort) as exc:
|
|
69
|
+
raise EmailConnectionError(
|
|
70
|
+
'Connection lost during IMAP fetch'
|
|
71
|
+
) from exc
|
|
72
|
+
|
|
73
|
+
except imaplib.IMAP4.error as exc:
|
|
74
|
+
raise FetchError(
|
|
75
|
+
f'Failed to fetch email: {email_id!r}'
|
|
76
|
+
) from exc
|
|
77
|
+
|
|
78
|
+
if status != 'OK':
|
|
79
|
+
raise FetchError(
|
|
80
|
+
f'Failed to fetch email: {email_id!r}'
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
for item in response:
|
|
84
|
+
if isinstance(item, tuple):
|
|
85
|
+
emails.append(
|
|
86
|
+
message_from_bytes(
|
|
87
|
+
item[1],
|
|
88
|
+
policy=default
|
|
89
|
+
)
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
return emails
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
|
|
3
|
+
from datetime import date, datetime
|
|
4
|
+
from email.message import EmailMessage
|
|
5
|
+
|
|
6
|
+
from ._base import _BaseIMAPClient
|
|
7
|
+
from .search import SearchCriteria
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class AsyncIMAPClient(_BaseIMAPClient):
|
|
15
|
+
async def fetch(self, criteria: SearchCriteria) -> list[EmailMessage]:
|
|
16
|
+
return await asyncio.to_thread(self._imap_fetch, *criteria.build())
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
async def fetch_all_emails(self) -> list[EmailMessage]:
|
|
20
|
+
return await self.fetch(SearchCriteria())
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
async def fetch_emails_by_date(self, since: str | date | datetime) -> list[EmailMessage]:
|
|
24
|
+
return await self.fetch(
|
|
25
|
+
SearchCriteria(since=since)
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
async def fetch_emails_by_date_range(self, start: str | date | datetime, end: str | date | datetime) -> list[EmailMessage]:
|
|
30
|
+
return await self.fetch(
|
|
31
|
+
SearchCriteria(
|
|
32
|
+
since=start,
|
|
33
|
+
before=end
|
|
34
|
+
)
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
async def fetch_emails_by_sender(self, sender: str) -> list[EmailMessage]:
|
|
39
|
+
return await self.fetch(
|
|
40
|
+
SearchCriteria(sender=sender)
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
async def fetch_unread(self) -> list[EmailMessage]:
|
|
45
|
+
return await self.fetch(SearchCriteria(unread=True))
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
from datetime import date, datetime
|
|
2
|
+
from email.message import EmailMessage
|
|
3
|
+
|
|
4
|
+
from ._base import _BaseIMAPClient
|
|
5
|
+
from .search import SearchCriteria
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class IMAPClient(_BaseIMAPClient):
|
|
13
|
+
def fetch(self, criteria: SearchCriteria) -> list[EmailMessage]:
|
|
14
|
+
return self._imap_fetch(*criteria.build())
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def fetch_all_emails(self) -> list[EmailMessage]:
|
|
18
|
+
return self.fetch(SearchCriteria())
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def fetch_emails_by_date(self, since: str | date | datetime) -> list[EmailMessage]:
|
|
22
|
+
return self.fetch(
|
|
23
|
+
SearchCriteria(since=since)
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def fetch_emails_by_date_range(self, start: str | date | datetime, end: str | date | datetime) -> list[EmailMessage]:
|
|
28
|
+
return self.fetch(
|
|
29
|
+
SearchCriteria(
|
|
30
|
+
since=start,
|
|
31
|
+
before=end
|
|
32
|
+
)
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def fetch_emails_by_sender(self, sender: str) -> list[EmailMessage]:
|
|
37
|
+
return self.fetch(
|
|
38
|
+
SearchCriteria(sender=sender)
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def fetch_unread(self) -> list[EmailMessage]:
|
|
43
|
+
return self.fetch(SearchCriteria(unread=True))
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import imaplib
|
|
2
|
+
import ssl
|
|
3
|
+
|
|
4
|
+
from types import TracebackType
|
|
5
|
+
|
|
6
|
+
from ..exceptions import AuthenticationError, EmailConnectionError, MailboxError
|
|
7
|
+
from ..servers import TLSMode
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class IMAPConnection:
|
|
13
|
+
def __init__(self, *, server: str, port: int, username: str, password: str, tls: TLSMode=TLSMode.IMPLICIT, mailbox: str='INBOX', timeout: float=30.0):
|
|
14
|
+
self.server = server
|
|
15
|
+
self.port = port
|
|
16
|
+
self.username = username
|
|
17
|
+
self.password = password
|
|
18
|
+
self.mailbox = mailbox
|
|
19
|
+
self.tls = tls
|
|
20
|
+
self.timeout = timeout
|
|
21
|
+
|
|
22
|
+
self._connection: imaplib.IMAP4 | None = None
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def __enter__(self) -> imaplib.IMAP4:
|
|
26
|
+
try:
|
|
27
|
+
self._connect()
|
|
28
|
+
self._authenticate()
|
|
29
|
+
self._select_mailbox()
|
|
30
|
+
|
|
31
|
+
except BaseException:
|
|
32
|
+
self._disconnect()
|
|
33
|
+
raise
|
|
34
|
+
|
|
35
|
+
assert self._connection is not None
|
|
36
|
+
|
|
37
|
+
return self._connection
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def __exit__(self, exc_type: type[BaseException] | None, exc: BaseException | None, traceback: TracebackType | None) -> None:
|
|
41
|
+
self._disconnect()
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _connect(self) -> None:
|
|
45
|
+
ssl_context = ssl.create_default_context()
|
|
46
|
+
|
|
47
|
+
try:
|
|
48
|
+
match self.tls:
|
|
49
|
+
case TLSMode.IMPLICIT:
|
|
50
|
+
self._connection = imaplib.IMAP4_SSL(
|
|
51
|
+
host=self.server,
|
|
52
|
+
port=self.port,
|
|
53
|
+
ssl_context=ssl_context,
|
|
54
|
+
timeout=self.timeout
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
case TLSMode.STARTTLS:
|
|
58
|
+
self._connection = imaplib.IMAP4(
|
|
59
|
+
host=self.server,
|
|
60
|
+
port=self.port,
|
|
61
|
+
timeout=self.timeout
|
|
62
|
+
)
|
|
63
|
+
self._connection.starttls(ssl_context=ssl_context)
|
|
64
|
+
|
|
65
|
+
case _:
|
|
66
|
+
raise EmailConnectionError(f'Unsupported TLS Mode {self.tls!r}')
|
|
67
|
+
|
|
68
|
+
except (OSError, imaplib.IMAP4.error) as exc:
|
|
69
|
+
raise EmailConnectionError(
|
|
70
|
+
f'Failed to connect to {self.server}'
|
|
71
|
+
) from exc
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _authenticate(self) -> None:
|
|
75
|
+
assert self._connection is not None
|
|
76
|
+
|
|
77
|
+
try:
|
|
78
|
+
self._connection.login(self.username, self.password)
|
|
79
|
+
|
|
80
|
+
except (OSError, imaplib.IMAP4.abort) as exc:
|
|
81
|
+
raise EmailConnectionError(
|
|
82
|
+
'Connection lost during authentication'
|
|
83
|
+
) from exc
|
|
84
|
+
|
|
85
|
+
except imaplib.IMAP4.error as exc:
|
|
86
|
+
raise AuthenticationError(
|
|
87
|
+
'IMAP Authentication failed'
|
|
88
|
+
) from exc
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _select_mailbox(self) -> None:
|
|
92
|
+
assert self._connection is not None
|
|
93
|
+
|
|
94
|
+
try:
|
|
95
|
+
status, _ = self._connection.select(self.mailbox, readonly=True)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
except (imaplib.IMAP4.abort, OSError) as exc:
|
|
99
|
+
raise EmailConnectionError(
|
|
100
|
+
'Connection lost during mailbox selection'
|
|
101
|
+
) from exc
|
|
102
|
+
|
|
103
|
+
except imaplib.IMAP4.error as exc:
|
|
104
|
+
raise MailboxError(
|
|
105
|
+
f'Failed to select mailbox: {self.mailbox}'
|
|
106
|
+
) from exc
|
|
107
|
+
|
|
108
|
+
if status != 'OK':
|
|
109
|
+
raise MailboxError(
|
|
110
|
+
f'Failed to select mailbox: {self.mailbox}'
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _disconnect(self) -> None:
|
|
115
|
+
if self._connection is None:
|
|
116
|
+
return
|
|
117
|
+
|
|
118
|
+
try:
|
|
119
|
+
self._connection.logout()
|
|
120
|
+
|
|
121
|
+
except (imaplib.IMAP4.error, OSError):
|
|
122
|
+
try:
|
|
123
|
+
self._connection.shutdown()
|
|
124
|
+
|
|
125
|
+
except OSError:
|
|
126
|
+
pass
|
|
127
|
+
|
|
128
|
+
finally:
|
|
129
|
+
self._connection = None
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
from datetime import date, datetime
|
|
2
|
+
from dataclasses import dataclass
|
|
3
|
+
|
|
4
|
+
from ..utils.normalization import normalize_date
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass
|
|
10
|
+
class SearchCriteria:
|
|
11
|
+
sender: str | None = None
|
|
12
|
+
recipient: str | None = None
|
|
13
|
+
subject: str | None = None
|
|
14
|
+
since: str | date | datetime | None = None
|
|
15
|
+
before: str | date | datetime | None = None
|
|
16
|
+
unread: bool | None = None
|
|
17
|
+
|
|
18
|
+
def build(self) -> tuple[str, ...]:
|
|
19
|
+
criteria: list[str] = []
|
|
20
|
+
|
|
21
|
+
if self.sender:
|
|
22
|
+
criteria.extend(('FROM', self._quote(self.sender)))
|
|
23
|
+
|
|
24
|
+
if self.recipient:
|
|
25
|
+
criteria.extend(('TO', self._quote(self.recipient)))
|
|
26
|
+
|
|
27
|
+
if self.subject:
|
|
28
|
+
criteria.extend(('SUBJECT', self._quote(self.subject)))
|
|
29
|
+
|
|
30
|
+
if self.since:
|
|
31
|
+
criteria.extend(('SINCE', normalize_date(self.since)))
|
|
32
|
+
|
|
33
|
+
if self.before:
|
|
34
|
+
criteria.extend(('BEFORE', normalize_date(self.before)))
|
|
35
|
+
|
|
36
|
+
if self.unread is not None:
|
|
37
|
+
criteria.append('UNSEEN' if self.unread else 'SEEN')
|
|
38
|
+
|
|
39
|
+
return tuple(criteria) if criteria else ('ALL',)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@staticmethod
|
|
43
|
+
def _quote(value: str) -> str:
|
|
44
|
+
if any(char in value for char in ('\r', '\n', '\x00')):
|
|
45
|
+
raise ValueError('Invalid search value')
|
|
46
|
+
|
|
47
|
+
escaped = value.replace('\\', '\\\\').replace('"', '\\"')
|
|
48
|
+
return f'"{escaped}"'
|
mailadapter/py.typed
ADDED
|
File without changes
|
mailadapter/servers.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
2
|
+
from enum import StrEnum
|
|
3
|
+
from typing import Final
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class TLSMode(StrEnum):
|
|
7
|
+
IMPLICIT = 'implicit'
|
|
8
|
+
STARTTLS = 'starttls'
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass(frozen=True, slots=True)
|
|
12
|
+
class ServerConfig:
|
|
13
|
+
host: str
|
|
14
|
+
port: int
|
|
15
|
+
tls: TLSMode = TLSMode.IMPLICIT
|
|
16
|
+
|
|
17
|
+
def __post_init__(self) -> None:
|
|
18
|
+
if not self.host.strip():
|
|
19
|
+
raise ValueError('Server hostname cannot be empty')
|
|
20
|
+
|
|
21
|
+
if not 1 <= self.port <= 65535:
|
|
22
|
+
raise ValueError(f'Invalid port: {self.port}')
|
|
23
|
+
|
|
24
|
+
if not isinstance(self.tls, TLSMode):
|
|
25
|
+
raise ValueError(f'Invalid TLS mode: {self.tls!r}')
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class IMAPServers:
|
|
29
|
+
GMAIL: Final = ServerConfig('imap.gmail.com', 993)
|
|
30
|
+
OUTLOOK: Final = ServerConfig('outlook.office365.com', 993)
|
|
31
|
+
MICROSOFT365: Final = ServerConfig('outlook.office365.com', 993)
|
|
32
|
+
YAHOO: Final = ServerConfig('imap.mail.yahoo.com', 993)
|
|
33
|
+
ICLOUD: Final = ServerConfig('imap.mail.me.com', 993)
|
|
34
|
+
AOL: Final = ServerConfig('imap.aol.com', 993)
|
|
35
|
+
|
|
36
|
+
GMX: Final = ServerConfig('imap.gmx.net', 993)
|
|
37
|
+
GMX_INT: Final = ServerConfig('imap.gmx.com', 993)
|
|
38
|
+
WEBDE: Final = ServerConfig('imap.web.de', 993)
|
|
39
|
+
T_ONLINE: Final = ServerConfig('secureimap.t-online.de', 993)
|
|
40
|
+
|
|
41
|
+
ZOHO: Final = ServerConfig('imap.zoho.com', 993)
|
|
42
|
+
FASTMAIL: Final = ServerConfig('imap.fastmail.com', 993)
|
|
43
|
+
MAILCOM: Final = ServerConfig('imap.mail.com', 993)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class SMTPServers:
|
|
47
|
+
GMAIL: Final = ServerConfig("smtp.gmail.com", 465)
|
|
48
|
+
OUTLOOK: Final = ServerConfig(
|
|
49
|
+
'smtp-mail.outlook.com', 587, TLSMode.STARTTLS
|
|
50
|
+
)
|
|
51
|
+
MICROSOFT365: Final = ServerConfig(
|
|
52
|
+
'smtp.office365.com', 587, TLSMode.STARTTLS
|
|
53
|
+
)
|
|
54
|
+
YAHOO: Final = ServerConfig('smtp.mail.yahoo.com', 465)
|
|
55
|
+
ICLOUD: Final = ServerConfig(
|
|
56
|
+
'smtp.mail.me.com', 587, TLSMode.STARTTLS
|
|
57
|
+
)
|
|
58
|
+
AOL: Final = ServerConfig('smtp.aol.com', 465)
|
|
59
|
+
|
|
60
|
+
GMX: Final = ServerConfig('mail.gmx.net', 465)
|
|
61
|
+
GMX_INT: Final = ServerConfig('mail.gmx.com', 465)
|
|
62
|
+
WEBDE: Final = ServerConfig('smtp.web.de', 465)
|
|
63
|
+
T_ONLINE: Final = ServerConfig('securesmtp.t-online.de', 465)
|
|
64
|
+
|
|
65
|
+
ZOHO: Final = ServerConfig('smtp.zoho.com', 465)
|
|
66
|
+
FASTMAIL: Final = ServerConfig('smtp.fastmail.com', 465)
|
|
67
|
+
MAILCOM: Final = ServerConfig(
|
|
68
|
+
'smtp.mail.com', 587, TLSMode.STARTTLS
|
|
69
|
+
)
|
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
from datetime import datetime, date
|
|
2
|
+
from dateutil.parser import parse, ParserError
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
_MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def normalize_date(value: str | date | datetime) -> str:
|
|
12
|
+
if isinstance(value, str):
|
|
13
|
+
try:
|
|
14
|
+
value = datetime.fromisoformat(value)
|
|
15
|
+
|
|
16
|
+
except ValueError:
|
|
17
|
+
try:
|
|
18
|
+
value = parse(
|
|
19
|
+
value,
|
|
20
|
+
dayfirst=True,
|
|
21
|
+
fuzzy=False,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
except (ParserError, OverflowError) as exc:
|
|
25
|
+
raise ValueError(
|
|
26
|
+
f'Invalid date format: {value!r}'
|
|
27
|
+
) from exc
|
|
28
|
+
|
|
29
|
+
if not isinstance(value, date):
|
|
30
|
+
raise TypeError(
|
|
31
|
+
f'Unsupported date type: {type(value).__name__}'
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
return f'{value.day:02d}-{_MONTHS[value.month - 1]}-{value.year:04d}'
|
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: mailadapter
|
|
3
|
+
Version: 0.1.0.dev1
|
|
4
|
+
Summary: A lightweight, typed Python email client.
|
|
5
|
+
Project-URL: Homepage, https://karstcoding.com/open-source/mailadapter
|
|
6
|
+
Project-URL: Repository, https://github.com/KarstCoding/mailadapter
|
|
7
|
+
Project-URL: Issues, https://github.com/KarstCoding/mailadapter/issues
|
|
8
|
+
Author: KarstCoding
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Classifier: Development Status :: 2 - Pre-Alpha
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Typing :: Typed
|
|
15
|
+
Requires-Python: >=3.11
|
|
16
|
+
Requires-Dist: python-dateutil
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
|
|
19
|
+
# MailAdapter
|
|
20
|
+
|
|
21
|
+
A lightweight, typed Python library for integrating email functionality into synchronous and asynchronous applications.
|
|
22
|
+
|
|
23
|
+
MailAdapter abstracts email protocol operations and connection management while maintaining explicit configuration and predictable execution behavior.
|
|
24
|
+
|
|
25
|
+
## Features
|
|
26
|
+
|
|
27
|
+
- Synchronous and asynchronous IMAP clients.
|
|
28
|
+
- Email retrieval and composable search criteria.
|
|
29
|
+
- Automatic date normalization.
|
|
30
|
+
- Predefined and custom server configurations.
|
|
31
|
+
- Implicit TLS and STARTTLS support.
|
|
32
|
+
- Automatic connection lifecycle management.
|
|
33
|
+
- Structured exception handling.
|
|
34
|
+
- Strict, fail-fast connection establishment.
|
|
35
|
+
|
|
36
|
+
## Installation
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
pip install mailadapter
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
For development releases:
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
pip install --pre mailadapter
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Requires Python 3.11 or later.
|
|
49
|
+
|
|
50
|
+
## Quick Start
|
|
51
|
+
|
|
52
|
+
### Synchronous Client
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
import os
|
|
56
|
+
|
|
57
|
+
from mailadapter import IMAPClient, IMAPServers
|
|
58
|
+
|
|
59
|
+
client = IMAPClient(
|
|
60
|
+
server=IMAPServers.GMAIL,
|
|
61
|
+
username=os.environ["EMAIL_USERNAME"],
|
|
62
|
+
password=os.environ["EMAIL_PASSWORD"],
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
emails = client.fetch_all_emails()
|
|
66
|
+
|
|
67
|
+
for email in emails:
|
|
68
|
+
print(email["Subject"])
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
### Asynchronous Client
|
|
72
|
+
|
|
73
|
+
```python
|
|
74
|
+
import asyncio
|
|
75
|
+
import os
|
|
76
|
+
|
|
77
|
+
from mailadapter import AsyncIMAPClient, IMAPServers
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
async def main():
|
|
81
|
+
client = AsyncIMAPClient(
|
|
82
|
+
server=IMAPServers.GMAIL,
|
|
83
|
+
username=os.environ["EMAIL_USERNAME"],
|
|
84
|
+
password=os.environ["EMAIL_PASSWORD"],
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
emails = await client.fetch_all_emails()
|
|
88
|
+
|
|
89
|
+
for email in emails:
|
|
90
|
+
print(email["Subject"])
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
asyncio.run(main())
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
Asynchronous operations are thread-backed using `asyncio.to_thread()`. Cancellation does not terminate an already-running blocking operation.
|
|
97
|
+
|
|
98
|
+
## Email Retrieval
|
|
99
|
+
|
|
100
|
+
```python
|
|
101
|
+
client.fetch_all_emails()
|
|
102
|
+
client.fetch_unread()
|
|
103
|
+
client.fetch_emails_by_sender("sender@example.com")
|
|
104
|
+
client.fetch_emails_by_date("2026-12-01")
|
|
105
|
+
|
|
106
|
+
client.fetch_emails_by_date_range(
|
|
107
|
+
start="2026-12-01",
|
|
108
|
+
end="2027-01-01",
|
|
109
|
+
)
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
Multiple search criteria can be combined:
|
|
113
|
+
|
|
114
|
+
```python
|
|
115
|
+
from mailadapter import SearchCriteria
|
|
116
|
+
|
|
117
|
+
emails = client.fetch(
|
|
118
|
+
SearchCriteria(
|
|
119
|
+
sender="sender@example.com",
|
|
120
|
+
subject="Invoice",
|
|
121
|
+
since="2026-12-01",
|
|
122
|
+
unread=True,
|
|
123
|
+
)
|
|
124
|
+
)
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
Fetched messages are returned as standard-library `EmailMessage` objects. Retrieval does not mark messages as read.
|
|
128
|
+
|
|
129
|
+
Date filters accept strings, `date` and `datetime` objects. Date ranges are start-inclusive and end-exclusive. ISO 8601 date strings are recommended.
|
|
130
|
+
|
|
131
|
+
## Server Configuration
|
|
132
|
+
|
|
133
|
+
MailAdapter includes presets for common email providers, including Gmail, Outlook, Microsoft 365, Yahoo, iCloud, GMX and others.
|
|
134
|
+
|
|
135
|
+
Custom servers can be configured explicitly:
|
|
136
|
+
|
|
137
|
+
```python
|
|
138
|
+
from mailadapter import ServerConfig, TLSMode
|
|
139
|
+
|
|
140
|
+
server = ServerConfig(
|
|
141
|
+
host="mail.example.com",
|
|
142
|
+
port=993,
|
|
143
|
+
tls=TLSMode.IMPLICIT,
|
|
144
|
+
)
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
Supported encryption modes:
|
|
148
|
+
|
|
149
|
+
| Mode | Description |
|
|
150
|
+
|---|---|
|
|
151
|
+
| `TLSMode.IMPLICIT` | TLS encryption from connection establishment. |
|
|
152
|
+
| `TLSMode.STARTTLS` | Explicit TLS upgrade before authentication. |
|
|
153
|
+
|
|
154
|
+
Some providers require application-specific passwords or OAuth2. The current implementation supports username-and-password authentication.
|
|
155
|
+
|
|
156
|
+
## Connection Policy
|
|
157
|
+
|
|
158
|
+
MailAdapter follows a strict, fail-fast connection policy.
|
|
159
|
+
|
|
160
|
+
Connections are established exclusively according to the supplied configuration. The library does not perform:
|
|
161
|
+
|
|
162
|
+
- Automatic server or port discovery.
|
|
163
|
+
- Fallback to alternative connection settings.
|
|
164
|
+
- Fallback between TLS modes.
|
|
165
|
+
- Fallback to unencrypted connections.
|
|
166
|
+
- Automatic authentication strategy switching.
|
|
167
|
+
- Automatic connection retries.
|
|
168
|
+
|
|
169
|
+
Failed operations raise exceptions rather than silently attempting alternative configurations.
|
|
170
|
+
|
|
171
|
+
TLS negotiation must succeed before authentication is attempted.
|
|
172
|
+
|
|
173
|
+
Each retrieval operation manages its own connection lifecycle internally. Configuration, retry strategies and recovery mechanisms remain the responsibility of the consuming application.
|
|
174
|
+
|
|
175
|
+
**MailAdapter abstracts protocol mechanics, not configuration decisions.**
|
|
176
|
+
|
|
177
|
+
## Exception Handling
|
|
178
|
+
|
|
179
|
+
MailAdapter provides a common exception hierarchy rooted in `MailAdapterError`.
|
|
180
|
+
|
|
181
|
+
```python
|
|
182
|
+
from mailadapter import (
|
|
183
|
+
MailAdapterError,
|
|
184
|
+
AuthenticationError,
|
|
185
|
+
EmailConnectionError,
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
try:
|
|
189
|
+
emails = client.fetch_all_emails()
|
|
190
|
+
|
|
191
|
+
except AuthenticationError:
|
|
192
|
+
print("Authentication failed")
|
|
193
|
+
|
|
194
|
+
except EmailConnectionError:
|
|
195
|
+
print("Connection failed")
|
|
196
|
+
|
|
197
|
+
except MailAdapterError as exc:
|
|
198
|
+
print(f"Email operation failed: {exc}")
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
Underlying protocol exceptions are preserved through exception chaining where applicable.
|
|
202
|
+
|
|
203
|
+
## Project Status
|
|
204
|
+
|
|
205
|
+
MailAdapter is currently under active development. The initial release focuses on IMAP retrieval. SMTP and additional authentication mechanisms are planned for subsequent releases.
|
|
206
|
+
|
|
207
|
+
## Roadmap
|
|
208
|
+
|
|
209
|
+
### v0.1.0 — IMAP Foundation
|
|
210
|
+
|
|
211
|
+
- Synchronous and asynchronous IMAP clients.
|
|
212
|
+
- Search criteria and email filtering.
|
|
213
|
+
- Date normalization.
|
|
214
|
+
- Provider presets.
|
|
215
|
+
- TLS configuration.
|
|
216
|
+
- Structured exception handling.
|
|
217
|
+
|
|
218
|
+
### v0.2.0 — Email Operations
|
|
219
|
+
|
|
220
|
+
- Synchronous and asynchronous SMTP clients.
|
|
221
|
+
- Attachment management.
|
|
222
|
+
- Extended mailbox operations.
|
|
223
|
+
|
|
224
|
+
### v0.3.0 — Extended Functionality
|
|
225
|
+
|
|
226
|
+
- OAuth2 authentication.
|
|
227
|
+
- Optional connection reuse.
|
|
228
|
+
- Advanced search expressions.
|
|
229
|
+
- Expanded provider support.
|
|
230
|
+
|
|
231
|
+
### v1.0.0 — Stable Release
|
|
232
|
+
|
|
233
|
+
- Stable public API.
|
|
234
|
+
- Comprehensive documentation.
|
|
235
|
+
- Expanded integration testing.
|
|
236
|
+
- Defined compatibility guarantees.
|
|
237
|
+
|
|
238
|
+
## Development
|
|
239
|
+
|
|
240
|
+
```bash
|
|
241
|
+
git clone https://github.com/KarstCoding/mailadapter.git
|
|
242
|
+
cd mailadapter
|
|
243
|
+
|
|
244
|
+
python -m venv .venv
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
Activate the virtual environment and install the package in editable mode:
|
|
248
|
+
|
|
249
|
+
```bash
|
|
250
|
+
python -m pip install -e .
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
## Contributing
|
|
254
|
+
|
|
255
|
+
Contributions, bug reports and feature requests are welcome.
|
|
256
|
+
|
|
257
|
+
MailAdapter prioritizes explicit interfaces, readability, maintainability and predictable behavior over unnecessary abstraction.
|
|
258
|
+
|
|
259
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md) and the [Architecture Decision Records](docs/adr/) for further information.
|
|
260
|
+
|
|
261
|
+
## License
|
|
262
|
+
|
|
263
|
+
MailAdapter is distributed under the [MIT License](LICENSE).
|
|
264
|
+
|
|
265
|
+
Developed and maintained by [KarstCoding](https://karstcoding.com).
|
|
266
|
+
Docs: (https://karstcoding.com/open-source/mailadapter)
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
mailadapter/__init__.py,sha256=psHhzvruENWhAhcDGhXaKaz4A1BbBREKFK7tBZi-hug,822
|
|
2
|
+
mailadapter/exceptions.py,sha256=bq7fuk2Pv_QZSwsbtCXwVUU-5kIQ5f5LcBjgMOilW9w,926
|
|
3
|
+
mailadapter/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
4
|
+
mailadapter/servers.py,sha256=oDI9kTQQmBBCBJzOCMUFfLVbGngIDb6nC6g5gB2Xi88,2371
|
|
5
|
+
mailadapter/imap/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
mailadapter/imap/_base.py,sha256=UFR0ZDQ1KoRXkYpAVyEsiQdYKy5WDjVM-2C34Ytb2eg,2781
|
|
7
|
+
mailadapter/imap/async_client.py,sha256=5iN5zeQkzNeI0c-vu0yzdPDS9WpwGjDXaNc9qkcuvag,1257
|
|
8
|
+
mailadapter/imap/client.py,sha256=E1qay37dpr_X7i3LzSHgMgrKa6TFrzjSx2U8N5zUwJ4,1151
|
|
9
|
+
mailadapter/imap/connection.py,sha256=bGXmoUEDn2HIIxCl3iGAhlGC9uSiCLEvFs9F5HCCWvQ,3728
|
|
10
|
+
mailadapter/imap/search.py,sha256=FIaZ_zybu8hFoQUAIuOhREN_TLRwnnUURSW99mlj9TI,1387
|
|
11
|
+
mailadapter/smtp/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
12
|
+
mailadapter/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
13
|
+
mailadapter/utils/normalization.py,sha256=EyGbwMuuUnJmOcksYz7ecrnMipzjSAF505C7gEHO8TE,937
|
|
14
|
+
mailadapter-0.1.0.dev1.dist-info/METADATA,sha256=P-OHDwUUfeYV3Bovg_xoQ0n2HRi-1DQkH9l29wlu7v0,6886
|
|
15
|
+
mailadapter-0.1.0.dev1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
16
|
+
mailadapter-0.1.0.dev1.dist-info/licenses/LICENSE,sha256=nm_CbMC_kY_2gnh85qa3H_5MjwIYVBWpSp2wXPqgRrQ,1113
|
|
17
|
+
mailadapter-0.1.0.dev1.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 KarstCoding (https://karstcoding.com)
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|