|
29
|
1 |
""" |
|
|
2 |
Email backend that writes messages to console instead of sending them. |
|
|
3 |
""" |
|
|
4 |
import sys |
|
|
5 |
import threading |
|
|
6 |
|
|
|
7 |
from django.core.mail.backends.base import BaseEmailBackend |
|
|
8 |
|
|
|
9 |
class EmailBackend(BaseEmailBackend): |
|
|
10 |
def __init__(self, *args, **kwargs): |
|
|
11 |
self.stream = kwargs.pop('stream', sys.stdout) |
|
|
12 |
self._lock = threading.RLock() |
|
|
13 |
super(EmailBackend, self).__init__(*args, **kwargs) |
|
|
14 |
|
|
|
15 |
def send_messages(self, email_messages): |
|
|
16 |
"""Write all messages to the stream in a thread-safe way.""" |
|
|
17 |
if not email_messages: |
|
|
18 |
return |
|
|
19 |
self._lock.acquire() |
|
|
20 |
try: |
|
|
21 |
# The try-except is nested to allow for |
|
|
22 |
# Python 2.4 support (Refs #12147) |
|
|
23 |
try: |
|
|
24 |
stream_created = self.open() |
|
|
25 |
for message in email_messages: |
|
|
26 |
self.stream.write('%s\n' % message.message().as_string()) |
|
|
27 |
self.stream.write('-'*79) |
|
|
28 |
self.stream.write('\n') |
|
|
29 |
self.stream.flush() # flush after each message |
|
|
30 |
if stream_created: |
|
|
31 |
self.close() |
|
|
32 |
except: |
|
|
33 |
if not self.fail_silently: |
|
|
34 |
raise |
|
|
35 |
finally: |
|
|
36 |
self._lock.release() |
|
|
37 |
return len(email_messages) |