Skip to content

Commit

Permalink
Base64-encode attachments and wrap to 76 characters.
Browse files Browse the repository at this point in the history
  • Loading branch information
amcgregor committed Aug 25, 2014
1 parent dbebf24 commit a34130b
Showing 1 changed file with 11 additions and 4 deletions.
15 changes: 11 additions & 4 deletions marrow/mailer/message.py
Expand Up @@ -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
Expand All @@ -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."""
Expand Down Expand Up @@ -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:
Expand Down

0 comments on commit a34130b

Please sign in to comment.