Debian Codegraph @

django/core/mail/backends/filebased.py

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