﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
32806	Send email with a content_type=text/* attachment	Christos Georgiou	nobody	"Python 3.8.5, Django 3.2.3
{{{
from django.core.mail import EmailMessage

e = EmailMessage('subject', 'the body', 'sender@domain.org', ['recipient@domain.org'])
e.attach('attachment.csv', 'flda,fldb\nvala,valb\n', 'text/csv')
e.send()
}}}
This fails as expected:
{{{
…
  File ""…/lib/python3.8/site-packages/sgbackend/mail.py"", line 149, in _build_sg_mail
    base64_attachment = base64.b64encode(attachment[1])
  File ""…/lib/python3.8/base64.py"", line 58, in b64encode
    encoded = binascii.b2a_base64(s, newline=False)
}}}

But this also fails:
{{{
e.attach('attachment.csv', b'flda,fldb\nvala,valb\n', 'text/csv')
e.send()
}}}

because `…/lib/python3.8/site-packages/django/core/mail/message.py` on `attach` does:

{{{
            if basetype == 'text':
                if isinstance(content, bytes):
                    try:
                        content = content.decode()
                    except UnicodeDecodeError:
                        # If mimetype suggests the file is text but it's
                        # actually binary, read() raises a UnicodeDecodeError.
                        mimetype = DEFAULT_ATTACHMENT_MIME_TYPE

            self.attachments.append((filename, content, mimetype))
}}}

Why decode it if a Py3 string can't be b64encoded?  I think that actually it should be *encoded* as bytes if already str using the DEFAULT_CHARSET before appending the tuple to self.attachments.

If I `.attach(name, bytes_object, 'application/csv')` then the send operation works fine.

(I'm open to the possibility that I miss something and this is not a bug :) )

I can provide a patch if we decide upon the correct behaviour, but please let me know the target branch."	Bug	closed	Core (Mail)	3.2	Normal	invalid	sendgrid-django		Unreviewed	0	0	0	0	0	0
