1"""
2Email backend that writes messages to console instead of sending them.
3"""
4import sys
5import threading
6
7from .base import BaseEmailBackend
8
9
10class EmailBackend(BaseEmailBackend):
11 def __init__(self, *args, **kwargs):
12 self.stream = kwargs.pop("stream", sys.stdout)
13 self._lock = threading.RLock()
14 super().__init__(*args, **kwargs)
15
16 def write_message(self, message):
17 msg = message.message()
18 msg_data = msg.as_bytes()
19 charset = (
20 msg.get_charset().get_output_charset() if msg.get_charset() else "utf-8"
21 )
22 msg_data = msg_data.decode(charset)
23 self.stream.write("%s\n" % msg_data)
24 self.stream.write("-" * 79)
25 self.stream.write("\n")
26
27 def send_messages(self, email_messages):
28 """Write all messages to the stream in a thread-safe way."""
29 if not email_messages:
30 return
31 msg_count = 0
32 with self._lock:
33 try:
34 stream_created = self.open()
35 for message in email_messages:
36 self.write_message(message)
37 self.stream.flush() # flush after each message
38 msg_count += 1
39 if stream_created:
40 self.close()
41 except Exception:
42 if not self.fail_silently:
43 raise
44 return msg_count