This is a repost from lovinglinux.
After a lot of research I finally figure out a simple way of doing this using IMAP and a shell script.
1. Install offlineimap and mpack
sudo apt-get install offlineimap mpack
2. Create a folder ~/mail for storing the Gmail messages
3. Create a text file and save it as ~/.offlineimaprc
This is the configuration file for offlineimap which will sync your Gmail with local maildir files, using IMAP. Add the following code to it:
accounts = GMail
ui = Noninteractive.Basic
localrepository = GMailLocalMaildirRepository
remoterepository = GMailServerRepository
type = Maildir
localfolders = ~/mail/
type = IMAP
remotehost = imap.gmail.com
remoteuser = firstname.lastname@example.org
remotepass = yourgmailpassword
ssl = yes
Then run the following command on a terminal:
offlineimap && munpack /home/yourusername/mail/LABEL/new/*
The offlineimap command will sync Gmail with local files and munpack will extract any new messages and attachments in the "LABEL" folder, where each folder (label) correspond to Gmail labels.