Small tips for accessing programmatically the Gmail
Talking to IMAP services can be a source of frustration especially when each service implements parts of the protocol or add some secret ingredients to the sauce. One of the most popular services, as we all know is Gmail.
XOAuth
Gmail adds a lot of nice touches to the mail business. One of the latest additions is the use of XOAuth in order to authenticate against the service without any need of username and password. This can be especially handy if your app your app should read or just parse the headers of the users' emails but you do not want to save passwords, have extra UI for this purpose or let the user revoke the access at will. You can easily use xoauth in your webapp today using this small library.
Example code:
Searching
By default when you use imap.select() you will be able to search within the INBOX folder but sometimes you may want to search in both Sent messages and Inbox. In order to do so you have to do give the following command:
imap_conn.select("[Gmail]/All Mail")
Fetching an email without setting it as SEEN
When you want to fetch an email in order to parse you usually do:
typ, msg_data = imap_conn.fetch(uid, 'RFC822')
which will do exactly what you want, but if the email is not read (SEEN) it will mark it as read which something you may not want if you are not building a Gmail client. If you simply want to parse/read the email then do the following
typ, msg_data = imap_conn.fetch(uid, '(BODY.PEEK[HEADER])')
Find the body message and decode it
This can be really tricky as there can be a lot of forwards and replies plus an awful lot of encodings. Usually we the encoding of an email is appended in the subject. The following gist can be to some help:
If you have any suggestions, corrections please feel free to fork the gists and let me know :)

