Search code examples
pythongmailimap

Transferring emails in gmail from one label to another in python using IMAP


I have emails that will be flagged by gmail settings to move to a certain label called "Test". This script I am writing when ran, downloads any attachments in that label then moves all those emails to another label called "Checked" (to keep that label clear).

I have the download and parsing part done but I can't seem to manage moving the emails.

Here is the completed part of the program:

import imaplib
import email
import os
import base64
#import Const

user = '[email protected]'
password = 'imnottellingyou'
imap_url = 'imap.gmail.com'

def auth(user, password, imap_url):
    con = imaplib.IMAP4_SSL(imap_url)
    con.login(user, password)
    return con

con = auth(user, password, imap_url)
con.select('Test')

type, data = con.search(None, 'ALL')
mail_ids = data[0]
id_list = mail_ids.split()
print(id_list)
print(mail_ids)

for num in data[0].split():
    typ, data = con.fetch(num, '(RFC822)')
    raw_email = data[0][1]
    # converts byte literal to string removing b''
    raw_email_string = raw_email.decode('utf-8')
    email_message = email.message_from_string(raw_email_string)

    for part in email_message.walk():
        if part.get_content_maintype() == 'multipart':
            continue
        if part.get('Content-Disposition') is None:
            continue
        fileName = part.get_filename()

        if bool(fileName):
            filePath = os.path.join(
                'C:/Users/User/Desktop/test', fileName)
            if not os.path.isfile(filePath):
                fp = open(filePath, 'wb')
                fp.write(part.get_payload(decode=True))
                fp.close()
for uid in id_list:
    con.uid('STORE', uid, '+X-GM-LABELS', 'Checked')
    con.uid('STORE', uid, '-X-GM-LABELS', 'Test')

Here is the trouble area. This is what I have tried:

#after emails in label have been checked for attachments and downloaded
#emails will be transferred to a "checked" labe

for uid in id_list:
    con.uid('STORE', uid, '+X-GM-LABELS', 'Checked')
    con.uid('STORE', uid, '-X-GM-LABELS', 'Test')

The program executes fine, and no error messages appear but nothing changes in my gmail inbox.


Solution

  • Finally was able to come up with a solution.

    for uid in id_list:
        #adds the checked label (new label) to all emails that are in the id list
        con.store(uid, '+X-GM-LABELS', '(Checked)')
        #instead of "removing" original label it deletes the email from the label
        #since labels act like folders in gmail
        con.store(uid,'+FLAGS', '\\Deleted')