summaryrefslogtreecommitdiff
path: root/django/core/mail/backends/filebased.py
blob: 67257738ac79ccda11f7d5d1232f345a1da80572 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
"""Email backend that writes messages to a file."""

import datetime
import os

from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.core.mail import InvalidMailer
from django.core.mail.backends.console import EmailBackend as ConsoleEmailBackend


class EmailBackend(ConsoleEmailBackend):
    def __init__(self, fail_silently=False, file_path=None, **kwargs):
        self._fname = None
        # Since we're using the console-based backend as a base, force the
        # stream to be None, so we don't default to stdout.
        kwargs["stream"] = None
        super().__init__(fail_silently=fail_silently, **kwargs)

        # RemovedInDjango70Warning.
        if self.alias is None:
            # Use deprecated settings when MAILERS not enabled.
            if file_path is not None:
                self.file_path = file_path
            else:
                self.file_path = getattr(settings, "EMAIL_FILE_PATH", None)
            if self.file_path is None:
                raise ImproperlyConfigured(
                    "The EMAIL_FILE_PATH setting must be set to use the file "
                    "EmailBackend."
                )
            self.file_path = os.path.abspath(self.file_path)
            try:
                os.makedirs(self.file_path, exist_ok=True)
            except FileExistsError:
                raise ImproperlyConfigured(
                    "Path for saving email messages exists, but is not a directory: %s"
                    % self.file_path
                )
            except OSError as err:
                raise ImproperlyConfigured(
                    "Could not create directory for saving email messages: %s (%s)"
                    % (self.file_path, err)
                )
            # Make sure that self.file_path is writable.
            if not os.access(self.file_path, os.W_OK):
                raise ImproperlyConfigured(
                    "Could not write to directory: %s" % self.file_path
                )
            return

        if file_path is None:
            raise InvalidMailer("OPTIONS must define 'file_path'.", alias=self.alias)
        self.file_path = os.path.abspath(file_path)
        try:
            os.makedirs(self.file_path, exist_ok=True)
        except FileExistsError:
            raise InvalidMailer(
                f"'file_path' is not a directory: {self.file_path}",
                alias=self.alias,
            )
        except OSError as err:
            raise InvalidMailer(
                f"Could not create 'file_path': {self.file_path} ({err})",
                alias=self.alias,
            )
        if not os.access(self.file_path, os.W_OK):
            raise InvalidMailer(
                f"'file_path' is not writable: {self.file_path}",
                alias=self.alias,
            )

    def write_message(self, message):
        self.stream.write(message.message().as_bytes() + b"\n")
        self.stream.write(b"-" * 79)
        self.stream.write(b"\n")

    def _get_filename(self):
        """Return a unique file name."""
        if self._fname is None:
            timestamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
            fname = "%s-%s.log" % (timestamp, abs(id(self)))
            self._fname = os.path.join(self.file_path, fname)
        return self._fname

    def open(self):
        if self.stream is None:
            self.stream = open(self._get_filename(), "ab")
            return True
        return False

    def close(self):
        try:
            if self.stream is not None:
                self.stream.close()
        finally:
            self.stream = None