Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allowed adding attachments from strings and streams #26

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion envelopes/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
Mailing for human beings.
"""

__version__ = '0.4'
__version__ = '0.5'


from .conn import *
Expand Down
27 changes: 20 additions & 7 deletions envelopes/envelope.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
This module contains the Envelope class.
"""

import io
import sys

if sys.version_info[0] == 2:
Expand Down Expand Up @@ -273,7 +274,7 @@ def _encoded(self, _str):
def to_mime_message(self):
"""Returns the envelope as
:py:class:`email.mime.multipart.MIMEMultipart`."""
msg = MIMEMultipart('alternative')
msg = MIMEMultipart('mixed')
msg['Subject'] = self._header(self._subject or '')

msg['From'] = self._encoded(self._addrs_to_header([self._from]))
Expand All @@ -295,20 +296,22 @@ def to_mime_message(self):

return msg

def add_attachment(self, file_path, mimetype=None):
"""Attaches a file located at *file_path* to the envelope. If
*mimetype* is not specified an attempt to guess it is made. If nothing
is guessed then `application/octet-stream` is used."""
def add_attachment(self, file_path, data=None, mimetype=None):
"""Attaches a file to the envelope. If *data* is not specified, the
file is loaded from *file_path*. Otherwise *file_path* is used only for
name and mimetype guessing.
*data* might be a stream or a bytestring.
If *mimetype* is not specified an attempt to guess it is made.
If nothing is guessed then `application/octet-stream` is used."""
if not mimetype:
mimetype, _ = mimetypes.guess_type(file_path)

if mimetype is None:
mimetype = 'application/octet-stream'

type_maj, type_min = mimetype.split('/')
with open(file_path, 'rb') as fh:
part_data = fh.read()

def attach_data(part_data):
part = MIMEBase(type_maj, type_min)
part.set_payload(part_data)
email_encoders.encode_base64(part)
Expand All @@ -318,6 +321,16 @@ def add_attachment(self, file_path, mimetype=None):
% part_filename)

self._parts.append((mimetype, part))
if not data:
with open(file_path, 'rb') as fh:
part_data = fh.read()
attach_data(part_data)
elif isinstance(data, io.IOBase):
part_data = data.read()
attach_data(part_data)
else:
attach_data(data)


def send(self, *args, **kwargs):
"""Sends the envelope using a freshly created SMTP connection. *args*
Expand Down
28 changes: 27 additions & 1 deletion tests/test_envelope.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,9 @@
This module contains test suite for the *Envelope* class.
"""

import base64
from email.header import Header
import io
import os
import sys

Expand All @@ -36,6 +38,8 @@
from lib.testing import BaseTestCase


LOREM = 'Lorem ipsum'.encode('utf-8')

class Test_Envelope(BaseTestCase):
def setUp(self):
self._patch_smtplib()
Expand Down Expand Up @@ -362,7 +366,14 @@ def test_add_attachment(self):
_octet = self._tempfile(suffix='.txt')
envelope.add_attachment(_octet, mimetype='application/octet-stream')

assert len(envelope._parts) == 7
# Attach from string
envelope.add_attachment('file1.txt', data=LOREM, mimetype='text/plain')

# Attach from stream
sio = io.BytesIO(LOREM)
envelope.add_attachment('file2.txt', data=sio, mimetype='text/plain')

assert len(envelope._parts) == 9

assert envelope._parts[0][0] == 'text/plain'
assert envelope._parts[1][0] == 'text/html'
Expand All @@ -388,6 +399,21 @@ def test_add_attachment(self):
assert envelope._parts[6][1]['Content-Disposition'] ==\
'attachment; filename="%s"' % os.path.basename(_octet)

assert envelope._parts[6][0] == 'application/octet-stream'
assert envelope._parts[6][1]['Content-Disposition'] ==\
'attachment; filename="%s"' % os.path.basename(_octet)

assert envelope._parts[7][0] == 'text/plain'
assert envelope._parts[7][1]['Content-Disposition'] ==\
'attachment; filename="%s"' % os.path.basename('file1.txt')
assert envelope._parts[7][1].get_payload(decode=True) == LOREM

assert envelope._parts[8][0] == 'text/plain'
assert envelope._parts[8][1]['Content-Disposition'] ==\
'attachment; filename="%s"' % os.path.basename('file2.txt')
assert envelope._parts[8][1].get_payload(decode=True) == LOREM


def test_repr(self):
msg = self._dummy_message()
envelope = Envelope(**msg)
Expand Down