0

I am fairly new to Python, and I am trying to export key data points from .msg files into a single .csv

I've followed guidance from this thread: Parsing outlook .msg files with python

This, combined with using the csv module, has allowed me to export the results from a single .msg file, but I don't know how to program it to parse through all the .msg files in the same folder, and insert the results of each file in the subsequent rows in the csv file.

import extract_msg
import csv

f = r'\Email.msg'  
msg = extract_msg.Message(f)
msg_sender = msg.sender
msg_date = msg.date
msg_subj = msg.subject
msg_message = msg.body

with open(r'\Email.csv', mode='w') as file:
    fieldnames = ['Subject', 'Date', 'Sender']
    writer = csv.DictWriter(file, fieldnames=fieldnames)

    writer.writeheader()
    writer.writerow({'Subject': msg_subj, 'Date': msg_date, 'Sender': msg_sender})

1 Answers1

0

The following adds a loop that opens and looks at all the msg files in the current directory and outputs to a single csv file

import os
import extract_msg
import csv

with open(r'Email.csv', mode='w') as file:
    fieldnames = ['Subject', 'Date', 'Sender']
    writer = csv.DictWriter(file, fieldnames=fieldnames)

    writer.writeheader()

    for f in os.listdir('.'):
        if not f.endswith('.msg'):
            continue

        msg = extract_msg.Message(f)
        msg_sender = msg.sender
        msg_date = msg.date
        msg_subj = msg.subject
        msg_message = msg.body

        writer.writerow({'Subject': msg_subj, 'Date': msg_date, 'Sender': msg_sender})
Dan D.
  • 73,243
  • 15
  • 104
  • 123
  • Just what I needed, very much appreciated! – RP_MISWitham Jul 09 '19 at 14:16
  • I'm attempting to run this but not having any luck. Initially, I kept getting "unexpected indent" errors, so it would create the CSV file but never put anything into it. I was able to get rid of the errors by removing the line breaks, but now it just reaches the last line of code and hangs forever, without creating the CSV. Any idea where I'm going wrong? – bdb484 Apr 05 '20 at 14:13