Sunday, October 16, 2011

Download GMail email attachments by subject

I used to use my work scanner to scan all of my documents, photos, etc. So recently I needed to find something. However, since all of them are labeled as Document.pdf I had hard time finding what I was looking. My options were to download my mail using Thunderbird and then search for those emails or to download one attachment at the time. I did not like either. So, I wrote this simple groovy script that downloads attachments for a specific email subject.
import javax.mail.*
import java.util.Properties


def emailAddress = "you@gmail.com"
def password = "password"
def server = "imap.gmail.com"
def port = 993
def props = new Properties()

props.setProperty("mail.store.protocol", "imaps")
props.setProperty("mail.imaps.host", server)
props.setProperty("mail.imaps.port", port.toString())
//very important or you will get errors such as Exception in thread "main" com.sun.mail.util.DecodingException: BASE64Decoder: Error in encoded stream: needed 4 valid base64 characters but only got 1 before EOF, the 10 most recent characters were: "Q3w5ilxj2P"

props.setProperty("mail.imaps.partialfetch", "false");

def session = javax.mail.Session.getDefaultInstance(props, null)
def store = session.getStore("imaps")

store.connect(emailAddress, password)
println "connected to Gmail"

def inboxFolder = "INBOX"
def folder = store.getFolder(inboxFolder)
folder.open(Folder.READ_ONLY)


javax.mail.search.SearchTerm searchTerm = new javax.mail.search.AndTerm(
        new javax.mail.search.SubjectTerm("SUBJECT YOUR ARE SEARCHING FOR"),
)

def messages = folder.search(searchTerm)
messages.eachWithIndex {message, i ->

    def content = message.content
    if (content instanceof javax.mail.Multipart) {
        javax.mail.Multipart mp = (javax.mail.Multipart) content;

        for (int j = 0; j < mp.getCount(); j++) {
            javax.mail.Part part = mp.getBodyPart(j)
            String disposition = part.getDisposition()
            if (disposition != null && disposition.equalsIgnoreCase(javax.mail.Part.ATTACHMENT)) {
                saveFile(part.getFileName(), part.getInputStream())
            }
        }
    }

}

def saveFile(String fileName, InputStream inputStream) {
    println 'Saving file: ' + fileName

    def file = new File('/tmp/' + fileName)
    if (file.exists()) {
        for (int i = 0; file.exists(); i++) {
            file = new File('/tmp/' + i + '_' + fileName)
        }
    }
    file.append(inputStream)
    println 'File saved: ' + fileName


}

No comments: