Skip to content

Instantly share code, notes, and snippets.

@davidpelayo
Created March 3, 2016 21:28
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save davidpelayo/139db134ca2337e966bb to your computer and use it in GitHub Desktop.
Save davidpelayo/139db134ca2337e966bb to your computer and use it in GitHub Desktop.
Simple mbox parser to csv in Python
import mailbox
import csv
writer = csv.writer(open("mbox-output.csv", "wb"))
for message in mailbox.mbox('file.mbox/mbox'):
writer.writerow([message['message-id'], message['subject'], message['from']])
@TheDavidJohnson
Copy link

Thanks for posting this!

Quick note about using this with Python 3.6.8 (on Ubuntu 18.04). I got an error trying to write to the .csv file:

TypeError: a bytes-like object is required, not 'str'

By using the w option instead of the wb option, I was able to get it to work properly. Since this is a text file, I think we don't want to open it as binary. Just leaving this here in case it helps someone else.

So the writer = line ended up looking like this for me:

writer = csv.writer(open("mbox-output.csv", "w"))

Thanks again for sharing this snippet!

@davidpelayo
Copy link
Author

@GinaZhai this was 4 years ago. I can't remember; but I'd bet it was Python 2.x. Does it make sense?

@janewongktj
Copy link

Hi David,

I'm a newbie at running python scripts.

Following the steps on this blog https://kamal.io/blog/exporting-email-threads-from-gmail-into-csv-file
led me here.

I've extracted a mbox file (about 120KB), and have tried to run this script in the same directory using Python 3.8.3rc1 IDLE, but the resulting csv file has 0bytes.

I would appreciate any pointers, I am not sure what went wrong?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment