20 June 2023
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:
Three examples of how you might use the IMAP
FETCH query to see the raw data that your mail client uses
Above, 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
\r\n, which is required for IMAP commands.
After opening a connection, you can login with your password:
Which should have the server respond with:
Great, now select a mailbox, such as your 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.