2009-11-03 20:53:26 +08:00
|
|
|
"""
|
|
|
|
Email backend that writes messages to console instead of sending them.
|
|
|
|
"""
|
|
|
|
import sys
|
|
|
|
import threading
|
|
|
|
|
|
|
|
from django.core.mail.backends.base import BaseEmailBackend
|
2013-12-31 06:45:43 +08:00
|
|
|
from django.utils import six
|
2009-11-03 20:53:26 +08:00
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2009-11-03 20:53:26 +08:00
|
|
|
class EmailBackend(BaseEmailBackend):
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
self.stream = kwargs.pop('stream', sys.stdout)
|
|
|
|
self._lock = threading.RLock()
|
|
|
|
super(EmailBackend, self).__init__(*args, **kwargs)
|
|
|
|
|
2013-12-31 06:45:43 +08:00
|
|
|
def write_message(self, message):
|
|
|
|
msg = message.message().as_bytes()
|
|
|
|
if six.PY3:
|
|
|
|
msg = msg.decode()
|
|
|
|
self.stream.write('%s\n' % msg)
|
|
|
|
self.stream.write('-' * 79)
|
|
|
|
self.stream.write('\n')
|
|
|
|
|
2009-11-03 20:53:26 +08:00
|
|
|
def send_messages(self, email_messages):
|
|
|
|
"""Write all messages to the stream in a thread-safe way."""
|
|
|
|
if not email_messages:
|
|
|
|
return
|
2013-04-04 10:42:31 +08:00
|
|
|
msg_count = 0
|
2012-06-23 23:11:15 +08:00
|
|
|
with self._lock:
|
|
|
|
try:
|
|
|
|
stream_created = self.open()
|
|
|
|
for message in email_messages:
|
2013-12-31 06:45:43 +08:00
|
|
|
self.write_message(message)
|
2012-06-23 23:11:15 +08:00
|
|
|
self.stream.flush() # flush after each message
|
2013-04-04 10:42:31 +08:00
|
|
|
msg_count += 1
|
2012-06-23 23:11:15 +08:00
|
|
|
if stream_created:
|
|
|
|
self.close()
|
2013-09-30 23:55:14 +08:00
|
|
|
except Exception:
|
2012-06-23 23:11:15 +08:00
|
|
|
if not self.fail_silently:
|
|
|
|
raise
|
2013-04-04 10:42:31 +08:00
|
|
|
return msg_count
|