1"""Email backend that writes messages to a file."""
2
3import datetime
4import os
5
6from plain.exceptions import ImproperlyConfigured
7from plain.runtime import settings
8
9from .console import EmailBackend as ConsoleEmailBackend
10
11
12class EmailBackend(ConsoleEmailBackend):
13 def __init__(self, *args, file_path=None, **kwargs):
14 self._fname = None
15 if file_path is not None:
16 self.file_path = file_path
17 else:
18 self.file_path = getattr(settings, "EMAIL_FILE_PATH", None)
19 self.file_path = os.path.abspath(self.file_path)
20 try:
21 os.makedirs(self.file_path, exist_ok=True)
22 except FileExistsError:
23 raise ImproperlyConfigured(
24 "Path for saving email messages exists, but is not a directory: %s"
25 % self.file_path
26 )
27 except OSError as err:
28 raise ImproperlyConfigured(
29 "Could not create directory for saving email messages: {} ({})".format(
30 self.file_path, err
31 )
32 )
33 # Make sure that self.file_path is writable.
34 if not os.access(self.file_path, os.W_OK):
35 raise ImproperlyConfigured(
36 "Could not write to directory: %s" % self.file_path
37 )
38 # Finally, call super().
39 # Since we're using the console-based backend as a base,
40 # force the stream to be None, so we don't default to stdout
41 kwargs["stream"] = None
42 super().__init__(*args, **kwargs)
43
44 def write_message(self, message):
45 self.stream.write(message.message().as_bytes() + b"\n")
46 self.stream.write(b"-" * 79)
47 self.stream.write(b"\n")
48
49 def _get_filename(self):
50 """Return a unique file name."""
51 if self._fname is None:
52 timestamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
53 fname = f"{timestamp}-{abs(id(self))}.log"
54 self._fname = os.path.join(self.file_path, fname)
55 return self._fname
56
57 def open(self):
58 if self.stream is None:
59 self.stream = open(self._get_filename(), "ab")
60 return True
61 return False
62
63 def close(self):
64 try:
65 if self.stream is not None:
66 self.stream.close()
67 finally:
68 self.stream = None