Moving An Email To A Folder In Gmail Using Python

I receive daily activity statements from my broker and I wanted to download them, extract the data into a MySQL database and then archive the statement on the hard drive. The first part is downloading the attachment, and then moving the email to another imap folder, which is something I had trouble with in Gmail. I use Python to do it, and the email and imaplib packages. Here’s a look at the code that moves all the messages in the inbox from a single recipient to another imap folder.

 

import Messaging, Util, Const
import email, imaplib, os

m = imaplib.IMAP4_SSL(Const.IMAP_SERVER)
m.login(Const.IMAP_USER, Const.IMAP_PWD)
m.select()

resp, items = m.search(None, 'FROM', '"donotreply@interactivebrokers.com"')
items = items[0].split()

for emailid in items:
    resp, data = m.fetch(emailid, "(RFC822)")
    if resp == 'OK':
        email_body = data[0][1].decode('utf-8')
        mail = email.message_from_string(email_body)

        if mail.get_content_maintype() != 'multipart':
            continue

        if mail["Subject"].find("Activity Statement") > 0:
            print("Moving message " + mail["Subject"] + " to " + Const.IMAP_DEST_FOLDER)
            result = m.store(emailid, '+X-GM-LABELS', Const.IMAP_DEST_FOLDER)
            #result = m.store(emailid, '+FLAGS', '\\Deleted')
            mov, data = m.uid('STORE', emailid , '+FLAGS', '(\Deleted)')
            m.expunge()

m.close()

I use another file called Const.Py to store all my configurations, so change those to whatever you need. The key here is to change the label with the line “result = m.store(emailid, ‘+X-GM-LABELS’, Const.IMAP_DEST_FOLDER)”, and then add the “Deleted” flag, before expunging the inbox.

 

Leave a Reply

Your email address will not be published. Required fields are marked *