Want to move all mails from spam folder to inbox with imaplib python in gmail using python

Viewed 50

I'm trying to move all mails present in gmail's spam folder to inbox using imaplib. But as a I'm facing issue like below.

"apply_lbl_msg = obj.uid('COPY', mail_ids, "todays") AttributeError: 'str' object has no attribute 'uid' Mail IDs : ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35']"

I'm able to fetch mail IDs but after that I'm not getting what to do I went through various tutorials but still facing the same issue.

Please help me with this friends.Below is my code as far as I tried.If anyone knew the answer means please send me the code.So I can understand....Thanks in advance...

import imaplib
obj = imaplib.IMAP4_SSL('imap.gmail.com', 993)
obj.login('my@gmail.com', 'password')
# obj.select("trials")
resp_code, mail_count = obj.select(mailbox="trials", readonly=True)

############### Retrieve Mail IDs for given Directory #############
obj, mail_ids = obj.search(None, "ALL")

print("Mail IDs : {}\n".format(mail_ids[0].decode().split()))
apply_lbl_msg = obj.uid('COPY', mail_ids, "todays")
if apply_lbl_msg[0] == 'OK':
    mov, data = obj.uid('STORE', mail_ids , '+FLAGS', '(\Deleted)')
    obj.expunge()

With above code I tried,But didn't got required result.

1 Answers

While it is possible to use imaplib directly I would recommend using a more user friendly library like imap_tools:

with MailBox('imap.mail.com').login('test@mail.com', 'pwd', initial_folder='INBOX') as mailbox:

    # MOVE all messages from current folder to INBOX/folder2
    mailbox.move(mailbox.uids(), 'INBOX/folder2')

For the specific case of Google Mail I would recommend using their Python API . For example I wrote a small program to filter emails using Python and the Google API, you can find the code on Github .

Related