Skip to content

Commit 9b8d3df

Browse files
authored
mime: have MIMEImage respect policy.max_line_length
This patch updates Lib/email/mime/image.py so that MIMEImage honors the max_line_length setting from the provided EmailPolicy when Base64-encoding image payloads. - Adds imports for base64 and textwrap.wrap - Replaces the old `set_payload(_imagedata)` + `_encoder(self)` calls with an explicit Base64 encode, wrap to `policy.max_line_length` (default 76), and then calls `set_payload` with the wrapped text. - Ensures CRLF line endings and proper headers are still applied by set_payload. Fixes issue python#133311: MIMEImage’s policy argument not taking effect.
1 parent 49ea8a0 commit 9b8d3df

File tree

1 file changed

+15
-3
lines changed

1 file changed

+15
-3
lines changed

Lib/email/mime/image.py

+15-3
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88

99
from email import encoders
1010
from email.mime.nonmultipart import MIMENonMultipart
11+
import base64
12+
from textwrap import wrap
1113

1214

1315
class MIMEImage(MIMENonMultipart):
@@ -39,9 +41,19 @@ def __init__(self, _imagedata, _subtype=None,
3941
raise TypeError('Could not guess image MIME subtype')
4042
MIMENonMultipart.__init__(self, 'image', _subtype, policy=policy,
4143
**_params)
42-
self.set_payload(_imagedata)
43-
_encoder(self)
44-
44+
#self.set_payload(_imagedata)
45+
#_encoder(self)
46+
# 1) Turn your image bytes into one long Base64 string
47+
b64str = base64.b64encode(_imagedata).decode('ascii')
48+
49+
# 2) Ask the policy “how long should each line be?”
50+
maxlen = getattr(self.policy, 'max_line_length', 76)
51+
52+
# 3) Break that long string into chunks of that length
53+
wrapped = "\r\n".join(wrap(b64str, maxlen))
54+
55+
# 4) Give the email library those nice, wrapped lines
56+
self.set_payload(wrapped, 'base64', policy=self.policy)
4557

4658
_rules = []
4759

0 commit comments

Comments
 (0)