0

I need to browse and open a .msg or .eml file in a Django application. I used forms and request.files, but the stream provides the data in octet format. How can I get the raw file object and open it as normal file in order to parse it?

I have code to share.

<form action="{% url "upload_file_eml" %}" method="post" enctype="multipart/form-data">
     {% csrf_token %}
     <p>{{ form.non_field_errors }}</p>
     <p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p>
     <p>
         {{ form.docfile.errors }}
         {{ form.docfile }}
     </p>
     <p><input class="btn btn-primary btn-large" type="submit" value="Start Single Email Test"/></p>
</form>

documents = handle_uploaded_eml_file(request.FILES)

def handle_uploaded_eml_file(fileslist1):
    if(len(fileslist1['docfile']) == 0):
        return "No Files"
    else:
        filename1 = fileslist1['docfile'].name
        if(checking_for_extension for emails with .msg or eml):
            emlfile = fileslist1['docfile'].file
            msg2 = email.message_from_file(emlfile)
           //msg2 is in octet format it doesn't parse because file being .msg
           //what i kind want to do
           //emlfile = open(fileslist1['docfile'].file)
           //msg2 = emlfile.read()
           print("email subject:" + msg2["Subject"])
           return "Upload Success"
        else:
            return "Unsupported Format"
py563
  • 15
  • 5
  • so please share the code – sebb Sep 19 '16 at 14:08
  • Cleaned up grammar, spelling, and phrasing. – Prune Sep 19 '16 at 16:54
  • `msg` and `eml` files both require their own parsers: http://stackoverflow.com/questions/31392361/how-to-read-eml-file-in-python AND https://msdn.microsoft.com/en-us/library/cc463912(v=exchg.80).aspx – jmunsch Sep 19 '16 at 17:27
  • @sebb please find code. please ignore syntactic errors if any.. i tagged wrong person few days back – py563 Sep 22 '16 at 14:10
  • so why dont you just read your inmemoryfileupload ? `data = request.FILES['myfile'].read()` – sebb Sep 22 '16 at 14:14
  • .read() in this case give octet content as msg files are not parsed by python or django without a third-party package. i found some packages but they except the raw file not the django interpreted file – py563 Jan 28 '17 at 00:52
  • Sounds like you need to use [`email.message_from_binary_file`](https://docs.python.org/3/library/email.parser.html#email.message_from_binary_file) or [`email.message_from_bytes`](https://docs.python.org/3/library/email.parser.html#email.message_from_bytes) after reading the whole file into memory. – Cristian Ciupitu May 09 '22 at 14:45

0 Answers0