1"""
 2Email backend that writes messages to console instead of sending them.
 3"""
 4
 5from __future__ import annotations
 6
 7import sys
 8import threading
 9from typing import TYPE_CHECKING, Any
10
11from .base import BaseEmailBackend
12
13if TYPE_CHECKING:
14    from ..message import EmailMessage
15
16
17class EmailBackend(BaseEmailBackend):
18    def __init__(self, *, stream: Any = None) -> None:
19        self.stream = stream or sys.stdout
20        self._lock = threading.RLock()
21
22    def write_message(self, message: EmailMessage) -> None:
23        msg = message.message()
24        msg_data = msg.as_bytes()
25        msg_charset = msg.get_charset()
26        if msg_charset is None:
27            charset = "utf-8"
28        elif isinstance(msg_charset, str):
29            charset = msg_charset
30        else:
31            charset = msg_charset.get_output_charset() or "utf-8"
32        msg_data = msg_data.decode(charset)
33        self.stream.write(f"{msg_data}\n")
34        self.stream.write("-" * 79)
35        self.stream.write("\n")
36
37    def send_messages(self, email_messages: list[EmailMessage]) -> int:
38        """Write all messages to the stream in a thread-safe way."""
39        if not email_messages:
40            return 0
41        msg_count = 0
42        with self._lock:
43            stream_created = self.open()
44            for message in email_messages:
45                self.write_message(message)
46                self.stream.flush()  # flush after each message
47                msg_count += 1
48            if stream_created:
49                self.close()
50        return msg_count