Have you ever wondered how mail clients work under the hood? Most mail clients fetch your mail with a protocol called called IMAP, and it's surprisingly human-readable.
Here's how it looks:
FETCH
query to see the raw data that your mail client usesAbove, I've queried the same message in three different ways, each returning different data. More info on IMAP commands and queries can be found in the latest RFC: IMAP4rev2.
Here's how you can use IMAP to query your own Gmail account.
First, you'll want to make an app password. This is a password that isn't your real password, but you can give to an app to use for certain functionality on your account. They're nice to have for testing. You can either follow the instructions here or create one directly at this link.
Now, you can use this app password to connect to Gmail! You can use a variety of programs that will let you create a TLS client. We're writing IMAP by hand, after all.
For example, you could connect with ncat using: ncat —ssl imap.gmail.com 993 —crlf
. Or you could connect with socat using: socat ssl:imap.gmail.com:993,crlf readline
. Essentially, these commands connect to Gmail's IMAP server over SSL, and replace your stdin \n
with \r\n
, which is required for IMAP commands.
After opening a connection, you can login with your password:
a LOGIN [email protected] yourapppassword
Which should have the server respond with:
* CAPABILITY IMAP4rev1 UNSELECT IDLE NAMESPACE QUOTA ID XLIST CHILDREN X-GM-EXT-1 UIDPLUS COMPRESS=DEFLATE ENABLE MOVE CONDSTORE ESEARCH UTF8=ACCEPT LIST-EXTENDED LIST-STATUS LITERAL- SPECIAL-USE APPENDLIMIT=35651584 a OK [email protected] authenticated (Success)
Great, now select a mailbox, such as your inbox:
a SELECT INBOX
And you can query away! Try running a FETCH 1 FAST
to see how old your first email in your inbox is.
Now that you're at the bottom of this post, you might be interested in a project I'm working on to automagically sort your emails. If that sounds interesting, you can sign up for the waitlist here.