Skip to content

Commit

Permalink
Merge pull request #37 from gisce/fix_parse_attachments_and_body
Browse files Browse the repository at this point in the history
Better parse of attachments/body
  • Loading branch information
ecarreras authored Apr 3, 2019
2 parents 4fe6772 + c310a60 commit 9653ad0
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 27 deletions.
36 changes: 12 additions & 24 deletions qreu/email.py
Original file line number Diff line number Diff line change
Expand Up @@ -417,29 +417,22 @@ def body_parts(self):
"""
Get all body parts of the email (text, html and attachments)
"""
return_vals = {}
return_vals = {'files': []}

for part in self.email.walk():
maintype, subtype = part.get_content_type().split('/')
# Multipart/* are containers, so we skip it
if maintype == 'multipart':
continue
# Get Text and HTML
filename = part.get_filename()
if filename:
return_vals['files'].append(filename)
elif maintype == 'text':
if subtype in ['plain', 'html']:
encoder = part.get_content_charset() or 'utf-8'
return_vals.update(
{subtype:part.get_payload(decode=True).decode(encoder)})
# Get Attachments
else:
files = return_vals.get('files', [])
new_attach = part.get('Content-Disposition', [])
if 'filename' in new_attach:
filename = [
f for f in new_attach.split(';') if 'filename=' in f
][0].split('filename=')[-1][1:-1]
if filename:
files.append(filename)
return_vals['files'] = files
return return_vals

@property
Expand All @@ -451,18 +444,13 @@ def attachments(self):
:return: Returns a Tuple generator as (AttachName, AttachContent)
"""
for part in self.email.walk():
if not part.get_content_maintype() in ['multipart', 'text']:
new_attach = part.get('Content-Disposition', [])
if 'filename' in new_attach:
if 'filename' in new_attach:
filename = [
f for f in new_attach.split(';') if 'filename=' in f
][0].split('filename=')[-1][1:-1]
yield {
'type': part.get_content_type(),
'name': filename,
'content': part.get_payload()
}
filename = part.get_filename()
if filename:
yield {
'type': part.get_content_type(),
'name': filename,
'content': part.get_payload()
}

@property
def mime_string(self):
Expand Down
6 changes: 3 additions & 3 deletions spec/qreu_spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,9 +104,9 @@

with it('must get all attachments and avoid wrong body parts'):
c = Email.parse(self.raw_messages[4])
attch = [p for p in c.attachments]
expect(attch).to(be_empty)
expect(c.body_parts['files']).to(be_empty)
attch = [p['name'] for p in c.attachments]
expect(attch).to(contain_exactly('image.png'))
expect(c.body_parts['files']).to(contain_exactly('image.png'))

with description("Creating an Email"):
with context("empty"):
Expand Down

0 comments on commit 9653ad0

Please sign in to comment.