ushka.mail.imap
ImapClient: read the inbox of a mailbox (support, leads, receipts) from an app.
It is the standard library's imaplib (blocking) called outside the event
loop with asyncio.to_thread, and email to parse, so it adds no dependency.
The e-mail is written by strangers, so everything in it is hostile input:
- every text taken from a message (subject, sender, body, attachment names) is
Untrustedand the guard refuses it in HTML, redirects, paths and SQL; - values you put into an IMAP command (search terms, folder names) are quoted and escaped, and CR, LF and NUL are refused, so a search term cannot append a command;
- the connection is TLS with the certificate and host name verified; plain text
needs
allow_insecure = true; - a message over
max_message_kbis refused from its size, before its body is downloaded, and the number and depth of MIME parts are capped; - the password and the message bodies are never logged and never in a
repr.
Import it explicitly (from ushka.mail import ImapClient): import ushka
does not load it.
In this module
class ImapError | The server or the connection failed. The message never contains the password or a message body. |
class ImapSecurityError | Refused because it would be unsafe: an injected command, an unverified or plain-text connection. |
class MessageRefused | A message over the size, part or depth limit. It is not downloaded or not parsed. |
class MessageNotFound | No message with that UID in the selected folder. |
def encode_folder() | A folder name in IMAP's modified UTF-7 ("Caixa de Entrada/Faturas ção" -> ASCII). |
def decode_folder() | The inverse of encode_folder. Malformed runs are left as they are. |
def build_search() | The tokens of a UID SEARCH, built only from validated parts. |
class Attachment | A file attached to a message. Everything the sender wrote about it is Untrusted. |
class Message | One e-mail. Every text field is Untrusted (source "mail:<field>"). |
def parse_message() | Parses RFC 822 bytes into a Message. Raises MessageRefused over the part or depth limits. |
def host_for() | The IMAP host of a well-known provider from an e-mail address, or "" (no guess for other domains). |
class ImapClient | An asynchronous IMAP client with one connection, used as async with. |
class ImapError (Exception)
The server or the connection failed. The message never contains the password or a message body.
class ImapSecurityError (ImapError, ValueError)
Refused because it would be unsafe: an injected command, an unverified or plain-text connection.
class MessageRefused (ImapError)
A message over the size, part or depth limit. It is not downloaded or not parsed.
class MessageNotFound (ImapError, LookupError)
No message with that UID in the selected folder.
def encode_folder
def encode_folder(name: str) -> strA folder name in IMAP's modified UTF-7 ("Caixa de Entrada/Faturas ção" -> ASCII).
def decode_folder
def decode_folder(name: str) -> strThe inverse of encode_folder. Malformed runs are left as they are.
def build_search
def build_search(**criteria: Any) -> list[bytes]The tokens of a UID SEARCH, built only from validated parts.
Keywords: flags (unseen=True, seen, flagged, answered,
deleted, draft and their negations), text (from_, to,
cc, bcc, subject, body, text), dates (since,
before, on, sent_since, sent_before, sent_on), sizes
(larger, smaller, in bytes), header=("X-Name", "value"),
keyword= / unkeyword= and uid= (an int, a list of ints or a set
such as "5:9"). No criteria means ALL.
Text values are quoted and escaped; one with a CR, LF or NUL raises
ImapSecurityError. Non-ASCII text is sent as UTF-8 quoted text (the
client then adds CHARSET UTF-8).
class Attachment
A file attached to a message. Everything the sender wrote about it is Untrusted.
filename and content_type are the sender's claims; use safe_filename
for a name on disk and let save do the writing.
read
def read() -> bytesThe decoded content.
save
def save(
directory: str | os.PathLike[str],
name: str | None = None,
*,
extensions: Iterable[str] | None = None,
overwrite: bool = False,
) -> AnyWrites it into directory exactly like UploadFile.save.
Without name a random name with the cleaned extension is used; pass
name=att.safe_filename to keep the sender's. Never overwrites unless
asked, never follows a symlink, and extensions limits what is accepted.
class Message
One e-mail. Every text field is Untrusted (source "mail:<field>").
html is the raw HTML of the sender: render it only after safe.html or
a sanitiser, never with |safe. date is timezone-aware, or None
when the header is missing or invalid; message_id is None when absent.
def parse_message
def parse_message(
raw: bytes,
uid: int = 0,
*,
max_parts: int = 100,
max_depth: int = MAX_DEPTH,
taint: bool = True,
) -> MessageParses RFC 822 bytes into a Message. Raises MessageRefused over the part or depth limits.
It never raises for a malformed header, a broken charset or a bad date:
those become replacement characters, None or the raw text.
def host_for
def host_for(address: str) -> strThe IMAP host of a well-known provider from an e-mail address, or "" (no guess for other domains).
class ImapClient
An asynchronous IMAP client with one connection, used as async with.
async with ImapClient() as mail: # doctest: +SKIP ... async for msg in mail.unseen(): ... ... ... await mail.mark_seen(msg.uid)
Commands are serialised by a lock (imaplib is not thread-safe), run in a
worker thread, and use UIDs, never sequence numbers. After a dropped
connection the next command reconnects and selects the same folder again.
Whatever you do not pass comes from [imap] (and USHKA_IMAP_PASSWORD), so
ImapClient() is the client of ushka.toml. A misspelt option raises TypeError.
With no host, it is taken from the user's address when that is at a well-known provider
(you@gmail.com is imap.gmail.com), and host="gmail" names a provider too
(see PROVIDER_HOSTS). Any other server needs its host: Ushka does not guess where to
send a password.
Parameters
| Name | Type | Description |
|---|---|---|
host | str | The password is kept out of |
user | str | The password is kept out of |
password | str | The password is kept out of |
**options | Any | The other keys of |
Methods
from_config | ImapClient(config=config, **overrides): a client from [imap]; keywords override single settings. |
close | Logs out and closes the connection. Safe to call twice. |
folders | The names of all folders, decoded from modified UTF-7. |
select | Selects folder; returns how many messages it has. |
search | UIDs of the messages matching criteria (see build_search), oldest first. |
fetch | Downloads and parses one message, without marking it seen. |
unseen | The unread messages of the selected folder, oldest first. They stay unread: call mark_seen. |
mark_seen | |
mark_unseen | |
delete | Flags the message \Deleted and expunges only that message (UID EXPUNGE). |
move | Copies the message to folder, then deletes it here. A failed copy deletes nothing. |
from_config
@classmethod
def from_config(config: Any = None, **overrides: Any) -> ImapClientImapClient(config=config, **overrides): a client from [imap]; keywords override single settings.
close
async def close() -> NoneLogs out and closes the connection. Safe to call twice.
folders
async def folders() -> list[str]The names of all folders, decoded from modified UTF-7.
select
async def select(folder: str, *, readonly: bool = False) -> intSelects folder; returns how many messages it has.
search
async def search(
*,
limit: int | None = None,
oldest: bool = False,
**criteria: Any,
) -> list[int]UIDs of the messages matching criteria (see build_search), oldest first.
With limit, only the newest limit UIDs, or the oldest ones with oldest=True
(what a queue wants: the next ones to process).
fetch
async def fetch(uid: int) -> MessageDownloads and parses one message, without marking it seen.
Raises MessageRefused when it is over max_message_kb (decided from
RFC822.SIZE before the body is downloaded) or has too many or too deeply
nested parts, and MessageNotFound when the UID does not exist.
unseen
async def unseen(
*,
limit: int | None = None,
on_error: Callable[[int, ImapError], Any] | None = None,
mark_refused: bool = False,
) -> AsyncIterator[Message]The unread messages of the selected folder, oldest first. They stay unread: call mark_seen.
With limit, the oldest limit unread messages: the next ones to process, so a queue
drains from the front.
A refused message (too big, too many parts) raises MessageRefused, or, when
on_error(uid, error) is given, is passed to it and skipped. It stays unread and comes
back on the next call, where it would take a place in limit again; with
mark_refused=True it is marked read first, so it is reported once.
mark_seen
async def mark_seen(uid: int) -> Nonemark_unseen
async def mark_unseen(uid: int) -> Nonedelete
async def delete(uid: int) -> NoneFlags the message \Deleted and expunges only that message (UID EXPUNGE).
move
async def move(uid: int, folder: str) -> NoneCopies the message to folder, then deletes it here. A failed copy deletes nothing.