DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • NiFi In-Memory Processing
  • Streamlining Data Lake ETL With Apache NiFi: A Practical Tutorial
  • Real-Time Analytics: All Data, Any Data, Any Scale, at Any Time
  • What Is a Modern Developer? In Today’s World, It’s a Citizen Engineer

Trending

  • Memory-Optimized Tables: Implementation Strategies for SQL Server
  • Intro to RAG: Foundations of Retrieval Augmented Generation, Part 1
  • Designing for Sustainability: The Rise of Green Software
  • Designing AI Multi-Agent Systems in Java
  1. DZone
  2. Data Engineering
  3. Data
  4. Creating an Email Bot in Apache NiFi

Creating an Email Bot in Apache NiFi

Some people say that I must have a bot to read and reply to emails at all crazy hours of the day — some type of awesome email assistant. Well, I decided to prototype it.

By 
Tim Spann user avatar
Tim Spann
DZone Core CORE ·
Jun. 10, 17 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
8.2K Views

Join the DZone community and get the full member experience.

Join For Free

This is the first piece. After this, I will add some Spark Machine Learning to intelligently reply to emails from a list of pre-trained responses. With supervised learning, it will learn what emails to send to whom based on subject, who an email is 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, I will send and receive HTML emails 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: < tspann@ hortonworks.com >
    Delivered - To: nifi@ dataflowdeveloper.com
Received: from walmailscan15.int.bizland.net by walmailscan15.int.bizland.net(
    Dovecot) with LMTP id + 5 RhOfCcB1jpZQAAf6S19A
for < nifi@ dataflowdeveloper.com > ;
Wed, 19 Oct 2016 12: 19: 13 - 0400
Return - path: < tspann@ hortonworks.com >
    Envelope - to: nifi@ dataflowdeveloper.com
Delivery - date: Wed, 19 Oct 2016 12: 19: 13 - 0400
Received: from[10.114.3.11](helo = smtp.maileig.com)
by walmailscan15.yourhostingaccount.com with esmtp(Exim)
id 1 bwtaC - 0006 dd - VQ
for nifi@ dataflowdeveloper.com;
Wed, 19 Oct 2016 12: 19: 12 - 0400
Received: from relayvx11c.securemail.intermedia.net([64.78.52.185]) by walimpinc11 with bizsmtp id xUKB1t0063zlEh401UKCnK;
Wed, 19 Oct 2016 12: 19: 12 - 0400 X - EN - OrigIP: 64.78.52.185 X - EN - IMPSID: xUKB1t0063zlEh401UKCnK Received: from emg - ca - 1 - 1. securemail.intermedia.net(localhost[127.0.0.1])(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 < nifi@ dataflowdeveloper.com > ;
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: 5841 d9083d16bded28a3c4d33bc505206b431f7f383f0eb3dbf1bd1917f763e8 x - echoworx - action: delivered Received: from 10.254.155.15([10.254.155.15]) by emg - ca - 1 - 1(JAMES SMTP Server 2.3.2) with SMTP ID 503
for < nifi@ dataflowdeveloper.com > ;
Wed, 19 Oct 2016 09: 19: 10 - 0700(PDT) Received: from MBX080 - W5 - CO - 2.e xch080.serverpod.net(unknown[10.224.117.104])(using TLSv1 with cipher AES256 - SHA(256 / 256 bits))(No client certificate requested) by emg - ca - 1 - 1. localdomain(Postfix) with ESMTPS id 6693053 F86
for < nifi@ dataflowdeveloper.com > ;
Wed, 19 Oct 2016 09: 19: 10 - 0700(PDT) Received: from MBX080 - W5 - CO - 2.e xch080.serverpod.net(10.224.117.104) by MBX080 - W5 - CO - 2.e xch080.serverpod.net(10.224.117.104) with Microsoft SMTP Server(TLS) id 15.0.1178.4;
Wed, 19 Oct 2016 09: 19: 09 - 0700 Received: from MBX080 - W5 - CO - 2.e xch080.serverpod.net([10.224.117.104]) by MBX080 - W5 - CO - 2.e xch080.serverpod.net([10.224.117.104]) with mapi id 15.00.1178.000;
Wed, 19 Oct 2016 09: 19: 09 - 0700 From: Timothy Spann < tspann@ hortonworks.com > To: "nifi@dataflowdeveloper.com" < nifi@ dataflowdeveloper.com > Thread - Topic: test Thread - Index: AQHSKiSFTVqN9ugyLEirSGxkMiBNFg == Date: Wed, 19 Oct 2016 16: 19: 09 + 0000 Message - ID: < D49AD137 - 3765 - 4 F9A - BF98 - C4E36D11FFD8@ hortonworks.com > Accept - Language: en - US Content - Language: en - US X - MS - Has - Attach: yes X - MS - TNEF - Correlator: x - ms - exchange - messagesentrepresentingtype: 1 x - ms - exchange - transport - fromentityheader: Hosted x - originating - ip: [71.168.178.39] x - source - routing - agent: Processed Content - Type: multipart / related;
boundary = "_004_D49AD13737654F9ABF98C4E36D11FFD8hortonworkscom_";
type = "multipart/alternative"--_004_D49AD13737654F9ABF98C4E36D11FFD8hortonworkscom_ Content - Type: multipart / alternative;
boundary = "_000_D49AD13737654F9ABF98C4E36D11FFD8hortonworkscom_"--_000_D49AD13737654F9ABF98C4E36D11FFD8hortonworkscom_ 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 exist."
    "") opts, args = parser.parse_args() if not opts.directory: os.makedirs(opts.directory)
try: os.mkdir(opts.directory)
except OSError as e: #Ignore directory exists error
if e.errno != errno.EEXIST: raise 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': continue # 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(opts.directory, filename), 'wb') fp.write(part.get_payload(decode=True)) fp.close() if __name__ == '__main__': main() */

mailnifi.sh:

python mailnifi.py -d /opt/demo/email/"$@"

Python needs the email component for parsing the message. You can install this via PIP.

pip install email

I am using Python 2.7. You could use a newer Python 3.x. I recommend Python 3. See this documentation for more tips.

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 them from the file system using the standard GetFile.

Apache NiFi

Published at DZone with permission of Tim Spann, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • NiFi In-Memory Processing
  • Streamlining Data Lake ETL With Apache NiFi: A Practical Tutorial
  • Real-Time Analytics: All Data, Any Data, Any Scale, at Any Time
  • What Is a Modern Developer? In Today’s World, It’s a Citizen Engineer

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!