diff --git a/Lib/email/mime/image.py b/Lib/email/mime/image.py index dab9685848172b..6603fb68c52866 100644 --- a/Lib/email/mime/image.py +++ b/Lib/email/mime/image.py @@ -8,6 +8,8 @@ from email import encoders from email.mime.nonmultipart import MIMENonMultipart +import base64 +from textwrap import wrap class MIMEImage(MIMENonMultipart): @@ -39,9 +41,19 @@ def __init__(self, _imagedata, _subtype=None, raise TypeError('Could not guess image MIME subtype') MIMENonMultipart.__init__(self, 'image', _subtype, policy=policy, **_params) - self.set_payload(_imagedata) - _encoder(self) - + #self.set_payload(_imagedata) + #_encoder(self) + # 1) Turn your image bytes into one long Base64 string + b64str = base64.b64encode(_imagedata).decode('ascii') + + # 2) Ask the policy “how long should each line be?” + maxlen = getattr(self.policy, 'max_line_length', 76) + + # 3) Break that long string into chunks of that length + wrapped = "\r\n".join(wrap(b64str, maxlen)) + + # 4) Give the email library those nice, wrapped lines + self.set_payload(wrapped, 'base64', policy=self.policy) _rules = [] diff --git a/Misc/NEWS.d/next/133311.rst b/Misc/NEWS.d/next/133311.rst new file mode 100644 index 00000000000000..99fd0d67dae19e --- /dev/null +++ b/Misc/NEWS.d/next/133311.rst @@ -0,0 +1 @@ +Fix email.mime.image.MIMEImage to respect policy.max_line_length (bpo-133311). diff --git a/Misc/NEWS.d/next/Library/2025-05-02-23-35-26.gh-issue-133311.c36IjF.rst b/Misc/NEWS.d/next/Library/2025-05-02-23-35-26.gh-issue-133311.c36IjF.rst new file mode 100644 index 00000000000000..fab58aa4754e6f --- /dev/null +++ b/Misc/NEWS.d/next/Library/2025-05-02-23-35-26.gh-issue-133311.c36IjF.rst @@ -0,0 +1 @@ +Fix email.mime.image.MIMEImage to respect policy.max_line_length when Base64-encoding image payloads.