Skip to content

Instantly share code, notes, and snippets.

@sente
Forked from jleedev/gmail_chat.py
Last active December 16, 2015 18:49
Show Gist options
  • Save sente/5480332 to your computer and use it in GitHub Desktop.
Save sente/5480332 to your computer and use it in GitHub Desktop.
import email
import email.parser
import imaplib
import getpass
def imap_login(username=None, password=None):
"""
login and return the connection
"""
username = username or raw_input("Gmail address: ")
password = password or getpass.getpass()
sock = imaplib.IMAP4_SSL("imap.gmail.com", 993)
sock.login(username, password)
return sock
def search_chats(sock):
"""
Return a list of msg_id's in your Chats label
"""
ok, _ = sock.select("[Gmail]/Chats", readonly=True)
if ok == 'NO':
sock.select("[Google Mail]/Chats", readonly=True)
ok, [ids] = sock.search(None, '(ALL)')
ids = ids.split()
return ids
def get_message(msg_id):
"""
returns the content of an individual chat
"""
resp, data = sock.fetch(msg_id, '(RFC822)')
msg = email.parser.Parser().parsestr(data[0][1])
for part in msg.walk():
if part.get_content_type() != 'text/html':
continue
return part.get_payload(decode=True)
if __name__ == '__main__':
sock = imap_login()
chat_ids = search_chats(sock)
for id in chat_ids:
payload = get_message(id)
print id, len(payload)
open('data/%05d.html' % int(id), 'w').write(payload)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment