Parsing Raw email in a Flask API

62 views Asked by At

I need to parse a raw email in a Flask app and use email package and return the content of the email. The email package does not work at all and returns null string. Any thought? Thanks.

This is a test code that I am working on:

from flask import Flask, request, jsonify
import email

app = Flask(__name__)

@app.route('/emails', methods=['POST'])

Emails = []

def get_content(message):
    e = email.message_from_string(message)
    return e.get_payload()

def emails():        
    if request.method == 'POST':
        # Parsing the email

        new_email = request.form['Content']
        
        # Parsing the email
        content = get_content(new_email)
        
        new_obj = {'Content': content}
        Emails.append(new_obj)
        return jsonify(Emails), 201


if __name__=='__main__':
    app.run(debug=True)

                                  

An example of a raw email is something like this: 'Message-ID: <9243650.1075857586383.JavaMail.evans@thyme>\nDate: Tue, 21 Nov 2000 13:30:00 -0800 (PST)\nFrom: [email protected]\nTo: [email protected]\nSubject: Re:\nMime-Version: 1.0\nContent-Type: text/plain; charset=us-ascii\nContent-Transfer-Encoding: 7bit\nX-From: John Arnold\nX-To: John J Lavorato\nX-cc: \nX-bcc: \nX-Folder: \\John_Arnold_Dec2000\\Notes Folders\\Sent\nX-Origin: Arnold-J\nX-FileName: Jarnold.nsf\n\neat shit\n\n\n\n\nJohn J Lavorato@ENRON\n11/18/2000 01:01 PM\nTo: John Arnold/HOU/ECT@ECT\ncc: \nSubject: \n\nFootball bets 200 each\n\nMinn -9.5\nBuff +2.5\nPhil -7\nIndi -4.5\nCinnci +7\nDet +6\nclev +16\nDen +9.5\nDall +7.5\nJack +3.5\n\n\n'

1

There are 1 answers

0
Brian Glassman On

Troubleshooting Step 1 is always "simplify the problem as much as possible". In this case, that means removing Flask and working with just the email. Once you get that working on its own, then connect it back to Flask.

Removing the Flask and JSON stuff I end up with this, which works fine for me. Try running this simplified version, and see if you still get an empty string.

import email

def get_content(message):
    e = email.message_from_string(message)
    return e.get_payload()

def emails(new_email):
    content = get_content(new_email)
    return content

raw = 'Message-ID: <9243650.1075857586383.JavaMail.evans@thyme>\nDate: Tue, 21 Nov 2000 13:30:00 -0800 (PST)\nFrom: [email protected]\nTo: [email protected]\nSubject: Re:\nMime-Version: 1.0\nContent-Type: text/plain; charset=us-ascii\nContent-Transfer-Encoding: 7bit\nX-From: John Arnold\nX-To: John J Lavorato\nX-cc: \nX-bcc: \nX-Folder: \\John_Arnold_Dec2000\\Notes Folders\\Sent\nX-Origin: Arnold-J\nX-FileName: Jarnold.nsf\n\neat shit\n\n\n\n\nJohn J Lavorato@ENRON\n11/18/2000 01:01 PM\nTo: John Arnold/HOU/ECT@ECT\ncc:  \nSubject: \n\nFootball bets 200 each\n\nMinn -9.5\nBuff +2.5\nPhil
-7\nIndi -4.5\nCinnci +7\nDet +6\nclev +16\nDen +9.5\nDall +7.5\nJack +3.5\n\n\n'

print(emails(raw))