Plain is headed towards 1.0! Subscribe for development updates →

 1"""Base email backend class."""
 2
 3from __future__ import annotations
 4
 5from typing import TYPE_CHECKING, Any
 6
 7if TYPE_CHECKING:
 8    from types import TracebackType
 9
10    from ..message import EmailMessage
11
12
13class BaseEmailBackend:
14    """
15    Base class for email backend implementations.
16
17    Subclasses must at least overwrite send_messages().
18
19    open() and close() can be called indirectly by using a backend object as a
20    context manager:
21
22       with backend as connection:
23           # do something with connection
24           pass
25    """
26
27    def __init__(self, fail_silently: bool = False, **kwargs: Any) -> None:
28        self.fail_silently = fail_silently
29
30    def open(self) -> None:
31        """
32        Open a network connection.
33
34        This method can be overwritten by backend implementations to
35        open a network connection.
36
37        It's up to the backend implementation to track the status of
38        a network connection if it's needed by the backend.
39
40        This method can be called by applications to force a single
41        network connection to be used when sending mails. See the
42        send_messages() method of the SMTP backend for a reference
43        implementation.
44
45        The default implementation does nothing.
46        """
47        pass
48
49    def close(self) -> None:
50        """Close a network connection."""
51        pass
52
53    def __enter__(self) -> BaseEmailBackend:
54        try:
55            self.open()
56        except Exception:
57            self.close()
58            raise
59        return self
60
61    def __exit__(
62        self,
63        exc_type: type[BaseException] | None,
64        exc_value: BaseException | None,
65        traceback: TracebackType | None,
66    ) -> None:
67        self.close()
68
69    def send_messages(self, email_messages: list[EmailMessage]) -> int:
70        """
71        Send one or more EmailMessage objects and return the number of email
72        messages sent.
73        """
74        raise NotImplementedError(
75            "subclasses of BaseEmailBackend must override send_messages() method"
76        )