http://y6gnjkv2xrjfb7qgs3kmsfyw5qwe7avjvvrnh7wpz5hvtrocm4rbetid.onion/tag/script
I used imapclient instead of the built-in imaplib because it is more Pythonic and handles all the tedious conversions between bytes, strings, and other types. The center of the script is the process function. It connects to an IMAP server, queries the list of folders, and downloads all the messages from each one but trash and spam (but notice that the comparison is case-sensitive!).