1""" 2Email backend that writes messages to console instead of sending them. 3""" 4 5importsys 6importthreading 7 8from.baseimportBaseEmailBackend 91011classEmailBackend(BaseEmailBackend):12def__init__(self,*args,**kwargs):13self.stream=kwargs.pop("stream",sys.stdout)14self._lock=threading.RLock()15super().__init__(*args,**kwargs)1617defwrite_message(self,message):18msg=message.message()19msg_data=msg.as_bytes()20charset=(21msg.get_charset().get_output_charset()ifmsg.get_charset()else"utf-8"22)23msg_data=msg_data.decode(charset)24self.stream.write(f"{msg_data}\n")25self.stream.write("-"*79)26self.stream.write("\n")2728defsend_messages(self,email_messages):29"""Write all messages to the stream in a thread-safe way."""30ifnotemail_messages:31return32msg_count=033withself._lock:34try:35stream_created=self.open()36formessageinemail_messages:37self.write_message(message)38self.stream.flush()# flush after each message39msg_count+=140ifstream_created:41self.close()42exceptException:43ifnotself.fail_silently:44raise45returnmsg_count