I wrote this a few years ago to archive my Gmail emails to text files (and the attachments to whatever they are).
I haven't ran it in awhile but when I did it worked and was able to download my emails from the very beginning without crashing. Anyway, you might find it useful...