Problem emailing CSV file that was read as a binary file

95 views
Skip to first unread message

Joshua Fialkoff

unread,
Nov 13, 2014, 10:05:03 AM11/13/14
to django...@googlegroups.com
Hi all,

I have this function that helps send emails with attachments:

def send_email(…):
    …
    msg = EmailMessage(
            subject, body, send_from,
            recipients_list, cc=cc, bcc=bcc,
            headers={'Reply-To': reply_to})
    msg.attach_alternative(html_body, "text/html")
    for f in files:
        try:
            email_fn, path = f
        except (ValueError, TypeError):
            path = f
            _, email_fn = os.path.split(path)
        with open(path, 'rb') as f:
            contents = f.read()
            msg.attach(email_fn, contents)

    msg.send()


In the case where path points to a file with a text mimetype (e.g., 'text/csv'), this fails with this error:

AttributeError: 'bytes' object has no attribute 'encode'

Here's an excerpt from django.core.mail.message. The error occurs on the line 4.

        basetype, subtype = mimetype.split('/', 1)
        if basetype == 'text':
            encoding = self.encoding or settings.DEFAULT_CHARSET
            attachment = SafeMIMEText(content, subtype, encoding)
        elif basetype == 'message' and subtype == 'rfc822':
            # Bug #18967: per RFC2046 s5.2.1, message/rfc822 attachments
            # must not be base64 encoded.
            if isinstance(content, EmailMessage):
                # convert content into an email.Message first
                content = content.message()
            elif not isinstance(content, Message):
                # For compatibility with existing code, parse the message
                # into an email.Message object if it is not one already.
                content = message_from_string(content)

            attachment = SafeMIMEMessage(content, subtype)
        else:
            # Encode non-text attachments with base64.
            attachment = MIMEBase(basetype, subtype)
            attachment.set_payload(content)
            Encoders.encode_base64(attachment)
        return attachment

My question is, why not use base64 encoding if the attachment content is specified as bytes?

Shu Latif

unread,
Jun 25, 2018, 5:55:35 PM6/25/18
to Django users
 Did you ever get this working? I am having the same issue with django 1.8. I see there was some sort of bug reported but I think the fix was in a later release. Not sure what I can do since I cannot upgrade.

Jason

unread,
Jun 25, 2018, 7:47:37 PM6/25/18
to Django users
Why not upload the file to S3 or some storage and include the download link in the email?  
Reply all
Reply to author
Forward
0 new messages