Commit c6da621d authored by Konrad Świat's avatar Konrad Świat Committed by Tim Graham
Browse files

Fixed #24623 -- Fixed EmailMessage.attach_file() with text files on Python 3.

Thanks tkrapp for the report and Tim Graham for the review.
parent 44dc201c
Loading
Loading
Loading
Loading
+29 −3
Original line number Diff line number Diff line
@@ -308,10 +308,36 @@ class EmailMessage(object):
            self.attachments.append((filename, content, mimetype))

    def attach_file(self, path, mimetype=None):
        """Attaches a file from the filesystem."""
        """
        Attaches a file from the filesystem.

        The mimetype will be set to the DEFAULT_ATTACHMENT_MIME_TYPE if it is
        not specified and cannot be guessed or (PY3 only) if it suggests
        text/* for a binary file.
        """
        filename = os.path.basename(path)
        if not mimetype:
            mimetype, _ = mimetypes.guess_type(filename)
            if not mimetype:
                mimetype = DEFAULT_ATTACHMENT_MIME_TYPE
        basetype, subtype = mimetype.split('/', 1)
        read_mode = 'r' if basetype == 'text' else 'rb'
        content = None

        with open(path, read_mode) as f:
            try:
                content = f.read()
            except UnicodeDecodeError:
                # If mimetype suggests the file is text but it's actually
                # binary, read() will raise a UnicodeDecodeError on Python 3.
                pass

        # If the previous read in text mode failed, try binary mode.
        if content is None:
            with open(path, 'rb') as f:
                content = f.read()
                mimetype = DEFAULT_ATTACHMENT_MIME_TYPE

        self.attach(filename, content, mimetype)

    def _create_message(self, msg):
+144 B
Loading image diff...
+1 −0
Original line number Diff line number Diff line
django/django
 No newline at end of file
+144 B

File added.

No diff preview for this file type.

+144 B

File added.

No diff preview for this file type.

Loading