Debian Codegraph @

django/core/mail/backends/console.py

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