Source code for mailsuite.mailbox.imap

"""IMAP mailbox backend"""

from __future__ import annotations

import logging
from collections.abc import Callable
from time import sleep
from typing import Any, cast

from imapclient.exceptions import IMAPClientError

from mailsuite.imap import IMAPClient
from mailsuite.mailbox.base import MailboxConnection

logger = logging.getLogger(__name__)


[docs] class IMAPConnection(MailboxConnection): """ A :class:`MailboxConnection` backed by IMAP Wraps :class:`mailsuite.imap.IMAPClient` and adds the :class:`MailboxConnection` semantics (folder/label management, polling via IDLE, etc.). IMAP is a mail-access protocol with no send capability — :meth:`send_message` raises :class:`NotImplementedError`. Use :func:`mailsuite.smtp.send_email` for sending. """ def __init__( self, host: str, user: str, password: str | None = None, port: int = 993, ssl: bool = True, verify: bool = True, timeout: int = 30, max_retries: int = 4, oauth2_token: str | None = None, oauth2_token_provider: Callable[[], str] | None = None, oauth2_mechanism: str = "XOAUTH2", oauth2_vendor: str | None = None, starttls: bool | None = None, ): """ Args: host: IMAP server hostname user: Username (or OAuth2 identity / email address) password: Password (omit when using OAuth2) port: Server port ssl: Use SSL/TLS verify: Verify the server's TLS certificate timeout: Per-operation timeout in seconds max_retries: Retries after a timeout oauth2_token: Static OAuth2 access token oauth2_token_provider: Zero-arg callable returning a current token. Re-invoked on reconnect, so the callable is responsible for refreshing the token. Prefer this over ``oauth2_token`` for long-running watch loops. oauth2_mechanism: ``"XOAUTH2"`` (default) or ``"OAUTHBEARER"`` oauth2_vendor: Optional vendor string for Yahoo's XOAUTH2 starttls: Whether to upgrade a plain-text (``ssl=False``) connection with STARTTLS. ``None`` (default) upgrades when the server advertises STARTTLS, and raises :class:`imapclient.exceptions.IMAPClientError` before authenticating when it does not, so credentials are never sent in plain text. ``False`` never upgrades, so the connection stays plain text even when STARTTLS is advertised and credentials are sent unencrypted (a warning is logged). ``True`` requires the upgrade and raises :class:`imapclient.exceptions.IMAPClientError` if the server does not advertise STARTTLS. Ignored when ``ssl=True``, because the connection is already TLS. """ self._username = user self._password = password self._verify = verify self._oauth2_token = oauth2_token self._oauth2_token_provider = oauth2_token_provider self._oauth2_mechanism = oauth2_mechanism self._oauth2_vendor = oauth2_vendor self._starttls = starttls self._client = IMAPClient( host, user, password, port=port, ssl=ssl, verify=verify, timeout=timeout, max_retries=max_retries, oauth2_token=oauth2_token, oauth2_token_provider=oauth2_token_provider, oauth2_mechanism=oauth2_mechanism, oauth2_vendor=oauth2_vendor, starttls=starttls, )
[docs] def create_folder(self, folder_name: str) -> None: self._client.create_folder(folder_name)
[docs] def rename_folder(self, old_name: str, new_name: str) -> None: self._ensure_no_folder_conflict(new_name) self._client.rename_folder(old_name, new_name)
[docs] def delete_folder(self, folder_name: str) -> None: self._client.delete_folder(folder_name)
[docs] def folder_exists(self, folder_name: str) -> bool: return bool(self._client.folder_exists(folder_name))
def _do_move_folder( self, source: str, target_parent: str, target_path: str ) -> None: # IMAP RENAME relocates within the hierarchy in one step, so a move is # just a rename to the full target path. _normalise_folder maps "/" to # the server's delimiter. (target_parent is unused; the path carries it.) del target_parent self._client.rename_folder(source, target_path)
[docs] def fetch_messages(self, reports_folder: str, **kwargs: Any) -> list: self._client.select_folder(reports_folder) since = kwargs.get("since") if since is not None: return self._client.search(f"SINCE {since}") return self._client.search()
[docs] def fetch_message(self, message_id: Any, **kwargs: Any) -> str: return cast(str, self._client.fetch_message(message_id, parse=False))
[docs] def delete_message(self, message_id: Any) -> None: try: self._client.delete_messages([message_id]) except IMAPClientError as error: logger.warning( "IMAP delete fallback for message %s due to server error: %s", message_id, error, ) self._client.add_flags([message_id], [r"\Deleted"], silent=True) self._client.expunge()
[docs] def move_message(self, message_id: Any, folder_name: str) -> None: try: self._client.move_messages([message_id], folder_name) except IMAPClientError as error: logger.warning( "IMAP move fallback for message %s due to server error: %s", message_id, error, ) self._client.copy([message_id], folder_name) self.delete_message(message_id)
[docs] def keepalive(self) -> None: self._client.noop()
[docs] def watch( self, check_callback: Callable[[MailboxConnection], None], check_timeout: int, config_reloading: Callable[[], bool] | None = None, ) -> None: """ Watch for new messages over an IDLE connection and dispatch each batch to ``check_callback`` """ def idle_callback_wrapper(client: IMAPClient) -> None: self._client = client check_callback(self) while True: if config_reloading and config_reloading(): return try: IMAPClient( host=self._client.host, username=self._username, password=self._password, port=self._client.port, ssl=self._client.ssl, verify=self._verify, idle_callback=idle_callback_wrapper, idle_timeout=check_timeout, oauth2_token=self._oauth2_token, oauth2_token_provider=self._oauth2_token_provider, oauth2_mechanism=self._oauth2_mechanism, oauth2_vendor=self._oauth2_vendor, config_reloading=config_reloading, starttls=self._starttls, ) except Exception as e: # noqa: BLE001 logger.warning(f"IMAP connection error: {e!r}. Reconnecting...") sleep(check_timeout) if config_reloading and config_reloading(): return
[docs] def send_message(self, *args: Any, **kwargs: Any) -> str | None: raise NotImplementedError( "IMAP cannot send mail; use mailsuite.smtp.send_email" )