#27007 closed Cleanup/optimization (fixed)
Handle non-UTF-8 bytes objects for text/* attachments
| Reported by: | Michael Schwarz | Owned by: | nobody |
|---|---|---|---|
| Component: | Core (Mail) | Version: | dev |
| Severity: | Normal | Keywords: | |
| Cc: | Triage Stage: | Ready for checkin | |
| Has patch: | yes | Needs documentation: | no |
| Needs tests: | no | Patch needs improvement: | no |
| Easy pickings: | no | UI/UX: | no |
Description
I've noticed that that attach() from django.core.mail.EmailMessage allows a bytes object to be passed as content even when the MIME type is set to text/plain. SafeMIMEText will then try to decode the text in the bytes object as UTF-8, which is necessary because the MIME specifications require text/* parts to be decodable with the encoding specified in the Content-Type header. But decoding the bytes object will fail if the bytes object does not contain valid UTF-8 encoded text.
OTOH, attach_file() will in that case first try to decode the file's content but fall back on treating the attachment as binary, setting the Content-Type to application/octet-stream.
I think the fallback provided by attach_file() is useful and I would like to extend attach() to that same behavior.
Change History (10)
comment:1 by , 9 years ago
comment:2 by , 9 years ago
| Summary: | Allow bytes objects as text/* attachments → Handle non-UTF-8 bytes objects for text/* attachments |
|---|
comment:3 by , 9 years ago
Might be a duplicate of #26802 which was committed just a couple weeks ago.
comment:5 by , 9 years ago
Replying to timgraham:
Sorry for not mentioning #26802. That change did improve the situation, allowing bytes objects. But it tries to unconditionally decode it as UTF-8 (compared to the logic in attach_file(), which falls back to treating it as a binary file). This means that if a bytes object is passed which does not contain valid UTF-8, a UnicodeDecodeError will be thrown.
With the changes in the pull request, the behavior is the same as when attaching a non-UTF-8 file.
comment:6 by , 9 years ago
| Has patch: | set |
|---|---|
| Patch needs improvement: | set |
| Triage Stage: | Unreviewed → Accepted |
comment:8 by , 9 years ago
| Patch needs improvement: | unset |
|---|---|
| Triage Stage: | Accepted → Ready for checkin |
Pending some small documentation edits.
I will shortly create a pull request with my proposed changes.