from IPython.display import Image

Image('http://i.imgur.com/SYija2N.png')

"""
Explanation: Graph Gmail inbox data with IPython notebook
End of explanation
"""


import mailbox
from email.utils import parsedate
from dateutil.parser import parse
import itertools
import plotly.plotly as py
from plotly.graph_objs import *

path = '/Users/jack/Desktop/All mail Including Spam and Trash.mbox'

"""
Explanation: Download your Gmail inbox as a ".mbox" file by clicking on "Account" under your Gmail user menu, then "Download data"
Install the Python libraries mailbox and dateutils with <code>sudo pip install mailbox</code> and <code>sudo pip install dateutils</code>
End of explanation
"""


mbox = mailbox.mbox(path)

"""
Explanation: Open your ".mbox" file with <code>mailbox</code>
End of explanation
"""


def extract_date(email):
    date = email.get('Date')
    return parsedate(date)

sorted_mails = sorted(mbox, key=extract_date)
mbox.update(enumerate(sorted_mails))
mbox.flush()

"""
Explanation: Sort your mailbox by date
End of explanation
"""


all_dates = []
mbox = mailbox.mbox(path)
for message in mbox:
    all_dates.append( str( parse( message['date'] ) ).split(' ')[0] )

"""
Explanation: Organize dates of email receipt as a list
End of explanation
"""


email_count = [(g[0], len(list(g[1]))) for g in itertools.groupby(all_dates)]

email_count[0]

x = []
y = []
for date, count in email_count:
    x.append(date)
    y.append(count)

py.iplot( Data([ Scatter( x=x, y=y ) ]) )

"""
Explanation: Count and graph emails received per day
End of explanation
"""


import plotly.tools as tls
tls.embed('https://plot.ly/~jackp/3266')

"""
Explanation: Restyle the chart in Plotly's GUI
End of explanation
"""


from IPython.core.display import HTML
import urllib2
HTML(urllib2.urlopen('http://bit.ly/1Bf5Hft').read())

"""
Explanation: Custom css styling
End of explanation
"""


