From a34130b73b14990457512dabd4eac0250ce016b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alice=20Bevan=E2=80=93McGregor?= Date: Mon, 25 Aug 2014 15:26:44 -0400 Subject: [PATCH] Base64-encode attachments and wrap to 76 characters. --- marrow/mailer/message.py | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/marrow/mailer/message.py b/marrow/mailer/message.py index 02e57e2..3cee97e 100644 --- a/marrow/mailer/message.py +++ b/marrow/mailer/message.py @@ -8,6 +8,7 @@ import base64 from datetime import datetime +from textwrap import TextWrapper from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.nonmultipart import MIMENonMultipart @@ -19,8 +20,11 @@ from marrow.mailer.address import Address, AddressList, AutoConverter from marrow.util.compat import basestring, unicode + __all__ = ['Message'] +WRAP = TextWrapper(width=76, expand_tabs=False) + class Message(object): """Represents an e-mail message.""" @@ -280,18 +284,21 @@ def attach(self, name, data=None, maintype=None, subtype=None, if data is None: with open(name, 'rb') as fp: - part.set_payload(base64.b64encode(fp.read())) + value = base64.b64encode(fp.read()) name = os.path.basename(name) elif isinstance(data, bytes): - part.set_payload(base64.b64encode(data)) + value = base64.b64encode(data) elif hasattr(data, 'read'): - part.set_payload(base64.b64encode(data.read())) + value = base64.b64encode(data.read()) else: raise TypeError("Unable to read attachment contents") - + + part.set_payload(WRAP.fill(value)) + if inline: part.add_header('Content-Disposition', 'inline', filename=name) part.add_header('Content-ID', '<%s>' % name) + part.add_header('Content-Transfer-Encoding','base64') self.embedded.append(part) else: if filename: