Community Articles

Find and share helpful community-sourced technical articles.
Labels (1)
Super Guru

Some people say I must have a bot to read and reply to email at all crazy hours of the day. An awesome email assistant, well I decided to prototype it.

This is the first piece. After this I will add some Spark machine learning to intelligently reply to emails from a list of pretrained responses. With supervised learning it will learn what emails to send to who, based on Subject, From, Body Content, attachments, time of day, sender domain and many other variables.

For now, it just reads some emails and checks for a hard coded subject.

I could use this to trigger other processes, such as running a batch Spark job.

Since most people send and use HTML email (that's what Outlook,, Gmail do), I will send and receive HTML emails as to make it look more legit.

I could also run my fortune script and return that as my email content. Making me sound wise, or pull in a random selection of tweets about Hadoop or even recent news. Making the email very current and fresh.

Snippet Example of a Mixed Content Email Message (Attachments Removed to Save Space)

Return-Path: <>
Received: from
    by (Dovecot) with LMTP id +5RhOfCcB1jpZQAAf6S19A
    for <>; Wed, 19 Oct 2016 12:19:13 -0400
Return-path: <>
Delivery-date: Wed, 19 Oct 2016 12:19:13 -0400
Received: from [x.x.x.x] (
    by with esmtp (Exim)
    id 1bwtaC-0006dd-VQ
    for; Wed, 19 Oct 2016 12:19:12 -0400
Received: from ([x.x.x.x])
    by x with bizsmtp
    id xUKB1t0063zlEh401UKCnK; Wed, 19 Oct 2016 12:19:12 -0400
X-EN-IMPSID: xUKB1t0063zlEh401UKCnK
Received: from (localhost [])
    (using TLSv1 with cipher AES256-SHA (256/256 bits))
    (No client certificate requested)
    by emg-ca-1-1.localdomain (Postfix) with ESMTPS id BEE9453F81
    for <>; Wed, 19 Oct 2016 09:19:10 -0700 (PDT)
Subject: test
MIME-Version: 1.0
x-echoworx-msg-id: e50ca00a-edc5-4030-a127-f5474adf4802
x-echoworx-emg-received: Wed, 19 Oct 2016 09:19:10.713 -0700
x-echoworx-message-code-hashed: 5841d9083d16bded28a3c4d33bc505206b431f7f383f0eb3dbf1bd1917f763e8
x-echoworx-action: delivered
Received: from ([])
          by emg-ca-1-1 (JAMES SMTP Server 2.3.2) with SMTP ID 503
          for <>;
          Wed, 19 Oct 2016 09:19:10 -0700 (PDT)
Received: from (unknown [x.x.x.x])
    (using TLSv1 with cipher AES256-SHA (256/256 bits))
    (No client certificate requested)
    by emg-ca-1-1.localdomain (Postfix) with ESMTPS id 6693053F86
    for <>; Wed, 19 Oct 2016 09:19:10 -0700 (PDT)
Received: from (x.x.x.x) by (x.x.x.x) with Microsoft SMTP
 Server (TLS) id 15.0.1178.4; Wed, 19 Oct 2016 09:19:09 -0700
Received: from ([x.x.x.x]) by ([x.x.x.x]) with mapi id
 15.00.1178.000; Wed, 19 Oct 2016 09:19:09 -0700
From: x x<>
To: "" <>
Thread-Topic: test
Thread-Index: AQHSKiSFTVqN9ugyLEirSGxkMiBNFg==
Date: Wed, 19 Oct 2016 16:19:09 +0000
Message-ID: <>
Accept-Language: en-US
Content-Language: en-US
X-MS-Has-Attach: yes
x-ms-exchange-messagesentrepresentingtype: 1
x-ms-exchange-transport-fromentityheader: Hosted
x-originating-ip: []
x-source-routing-agent: Processed
Content-Type: multipart/related;

Content-Type: multipart/alternative;

Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: base64

Python Script to Parse Email Messages

#!/usr/bin/env python

"""Unpack a MIME message into a directory of files."""
import json
import os
import sys
import email
import errno
import mimetypes
from optparse import OptionParser
from email.parser import Parser

def main():
    parser = OptionParser(usage="""Unpack a MIME message into a directory of files.
Usage: %prog [options] msgfile
    parser.add_option('-d', '--directory',
                      type='string', action='store',
                      help="""Unpack the MIME message into the named
                      directory, which will be created if it doesn't already
    opts, args = parser.parse_args()
    if not
    except OSError as e:
        # Ignore directory exists error
        if e.errno != errno.EEXIST:
    msgstring = ''.join(str(x) for x in sys.stdin.readlines())

    msg = email.message_from_string(msgstring)

    headers = Parser().parsestr(msgstring)
    response  = {'To': headers['to'], 'From': headers['from'], 'Subject': headers['subject'], 'Received': headers['Received']}
    print json.dumps(response)
    counter = 1
    for part in msg.walk():
        # multipart/* are just containers
        if part.get_content_maintype() == 'multipart':
        # Applications should really sanitize the given filename so that an
        # email message can't be used to overwrite important files
        filename = part.get_filename()
        if not filename:
            ext = mimetypes.guess_extension(part.get_content_type())
            if not ext:
                # Use a generic bag-of-bits extension
                ext = '.bin'
            filename = 'part-%03d%s' % (counter, ext)
        counter += 1
        fp = open(os.path.join(, filename), 'wb')

if __name__ == '__main__':

python -d /opt/demo/email/"$@"

Python needs the email component for parsing the message, you can install via PIP.

pip install email

I am using Python 2.7, you could use a newer Python 3.x

Here is the flow:





For the final part of the flow, I read the files created by the parsing, load them to HDFS and delete from the file system using the standard GetFile.







Take a Tour of the Community
Don't have an account?
Your experience may be limited. Sign in to explore more.
Version history
Last update:
‎03-11-2020 04:28 PM
Updated by:
Top Kudoed Authors