简体   繁体   中英

Fetch email from Junk folder by string in body using imap_tools in Lambda

Using AWS Lambda with a Python script and imap_tools library https://github.com/ikvk/imap_tools#search-criteria

I want to search the Junk folder for emails containing a specific string on the body, then move those emails to the Inbox. I have the following code which works except it seems to move random emails from the Junk folder and not the ones containing the string in the body.

Does anyone know what I am doing wrong? I'm a bit of a noob to Python so maybe I'm making a rookie mistake.

from imap_tools import MailBox, A, AND, OR, NOT

def lambda_handler(event, context):
    try:
        with MailBox('imap-mail.outlook.com').login('address@msn.com', 'PASSWORD') as mailbox:
            mailbox.folder.set('JUNK')
            mailbox.fetch(AND(body='TESTSTRING'))
            for msg in mailbox.fetch():
                mailbox.move(msg.uid, 'INBOX')
    except:
        print('No emails with tag!')
    finally:
        MailBox.logout
  • read about work fetch and move methods
  • try to understand why are you call fetch twice
  • move after loop
  • read about context managers, and python at all
  • what line MailBox.logout doing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM