1

I'm using the following code to delete emails from a webmail:

def process_webmail():
    box = imaplib.IMAP4_SSL(server)
    box.login(username, password)
    print("Connected to webmail")
    _tuple = box.list()
    if len(_tuple) <= 0:
        return

    before_date = (datetime.date.today() - datetime.timedelta(30)).strftime("%d-%b-%Y") 
    for folder in _tuple[1]:
        _folder_name = folder.split('\"/\"')
                    
        f = _folder_name[1].strip().strip('\"')
        if f.lower() == "inbox":
            pass
        else:
            box.select(f)
            # typ, data = box.search(None, 'ALL')
            typ, data = box.search(None, '(BEFORE {0})'.format(before_date))
            if data != ['']:
                for num in data[0].split():
                    box.store(num, '+FLAGS', '\\Deleted')

    print(box.expunge())
    box.close()
    box.logout()

We have 2 types of folders. 1) created folder and copied mails to it manually. 2) filters applied to have copied mails.

The above code is working on 1, while the emails are just being marked as deleted in case of 2. Not sure what was the issue. Someone please help me understand the issue.

Roundcube is the webmail being used.

srikanth
  • 958
  • 16
  • 37
  • What else are you expecting to happen? The only thing you're doing is making them deleted. Is it the expunge that doesn't seem to be working? What is the server software? – Max Sep 28 '20 at 15:09

1 Answers1

0

The following code worked. Misplaced .expunge()

def process_webmail():
    box = imaplib.IMAP4_SSL(server)
    box.login(username, password)
    print("Connected to webmail")
    _tuple = box.list()
    if len(_tuple) <= 0:
        return
    
    before_date = (datetime.date.today() - datetime.timedelta(30)).strftime("%d-%b-%Y") 
    for folder in _tuple[1]:
        _folder_name = folder.split('\"/\"')
                       
        f = _folder_name[1].strip().strip('\"')
        if f.lower() == "inbox":
            pass
        else:
            box.select(f)
            # typ, data = box.search(None, 'ALL')
            typ, data = box.search(None, '(BEFORE {0})'.format(before_date))
            if data != ['']:
                for num in data[0].split():
                    box.store(num, '+FLAGS', '\\Deleted')
                box.expunge()
    
    box.close()
    box.logout()
srikanth
  • 958
  • 16
  • 37