Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

console.py 1.4KB

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