Issue 25948: Invalid MIME encoding generated by email.mime (line too long) (original) (raw)
The email.mime package creates invalid MIME encoding (line too long) on certain inputs. That is, by proper usage of the email.mime API it is possible to create invalid emails that will be rejected by most mail servers.
Steps to reproduce
- Create a string that has the following properties:
1.1. The string contains only US-ASCII characters 1.2. The string contains a line that is longer than ~1000 characters
(For example, this could be an english-language HTML document that contains embedded images as "data:" URIs.)
- Create MIMEText instance with that text, don't specify a charset
(This will default to 'us-ascii'. Alternatively, specify the 'us-ascii' charset explicitly.)
Create Message out of that MIMEText instance
Serialize the message
Expected result
A MIME encoded email message that conforms to RFC 5322, section 2.1.1.: "Each line of characters MUST be no more than 998 characters, and SHOULD be no more than 78 characters, excluding the CRLF."
Actual result
A MIME encoded email message that contains a line with more than 998 characters. Hence, the email is rightfully rejected by most mail servers.
Workaround
Specify the UTF-8 charset explicitly. This forces MIMEText to switch to Base64 encoding, which will generate lines no longer than 78 characters.
For example, replace the following constructions:
MIMEText('Text with very long line', 'plain') MIMEText('HTML with very long line', 'html')
with:
MIMEText('Text with very long line', 'plain', 'utf-8') MIMEText('HTML with very long line', 'html', 'utf-8')
References
RFC 5322, 2.1.1. Line Length Limits https://tools.ietf.org/html/rfc5322#section-2.1.1
RFC 2822, 2.1.1. Line Length Limits https://tools.ietf.org/html/rfc2822#section-2.1.1
Related issues
Django #22561: EmailMessage should respect RFC2822 on max line length https://code.djangoproject.com/ticket/22561
Python #9298: binary email attachment issue with base64 encoding https://bugs.python.org/issue9298