#!.env/bin/python
from __future__ import unicode_literals
from imapclient import IMAPClient
from datetime import date
import yaml
HOST="buran.htu.tuwien.ac.at"
USERNAME="andis"
PASSWORD="t4MJAvU2"
ssl=True
server=IMAPClient(HOST, use_uid=True, ssl=ssl)
server.login(USERNAME,PASSWORD)

select_info=server.select_folder('INBOX')

messages=server.search([u'SUBJECT', 'service',u'SINCE', date(2017,06,1)])
#pritn(select_info)


#response = server.fetch(messages, ['FLAGS', 'RFC822.SIZE', 'BODY', 'ENVELOPE','X-GM-THRID', 'X-GM-MSGID'])
#response = server.fetch(messages, ['ENVELOPE'])

#print(response)
#for msgid, data in response.iteritems():
#    print('   ID %d: %d bytes, flags=%s, %s' % (msgid,
#                                            data[b'RFC822.SIZE'],
#                                                data[b'FLAGS'], data['ENVELOPE']))
#response = server.thread()

print "\n\n --------------------------------\n"
response= server.thread(criteria=[u'SUBJECT', 'service',u'SINCE', date(2017,04,1)])
print(response)
#resp=server.thread('X-GM')
#for msgid, data in response.iteritems():
#    print('   ID %d: \t %s \t %s' % (msgid, data[b'X-GM-THRID'], data[b'X-GM-MSGID']))
print "\n---------------------\n"
print response[0], len(response[0])


def get_msg(mid):
    print mid
    sf=server.fetch([mid],['ENVELOPE'])
    for msgid, data in sf.iteritems():
        return {"msgid": msgid, "envelope": data[b'ENVELOPE']}
    

def get_msg_tuple(ids):
    r=[]
    for i in ids:
        if type(i) is int:
            r.append(get_msg(i))
        elif type(i) is tuple:
            r.append(get_msg_tuple(i))
    return r

r=[]
for ids in response:
        r.append(get_msg_tuple(ids))

print yaml.dump(r,default_flow_style=False)
file=open("envelopes.yaml","w")
file.write(yaml.dump(r,default_flow_style=False))
file.close()
