Search Emails in Mailbox with Imap_tools & Mailparser

149 views Asked by At

First post after searching all over the site.

I am trying to search the body of emails in a outlook mailbox for email addresses. I am using Imap_tools, MailParser and Beautiful Soup. I need to get any email address present in the body of the email to use in another section of the script I'm writing. Maybe I'm doing too much but need this to work.

This is what I have so far.

with MailBox('outlook.office365.com').xoauth2('[email protected]', result['access_token'], 'INBOX') as mailbox:
        for msg in mailbox.fetch(A(seen= True, subject='SUBJECT', from_= 'EMAIL')):
            #to validate it's fetching the correct emails
            print(msg.date_str, msg.subject) 
                email_message = mailparser.parse_from_file_obj(msg.obj)
                soup = BeautifulSoup(email_message.body, "html.parser")
                print(soup)
                text = soup.get_text()
                # Find all email addresses in the body of the email
                email = re.findall(r'[\w\.-]+@[\w\.-]+', text)
                print(email)
                email = email[0]

This is the error I'm getting

Traceback (most recent call last):
  File ".\testServPrinc.py", line 55, in <module>
    email_message = mailparser.parse_from_file_obj(msg.obj)
  File AppData\Roaming\Python\Python38\s
r.py", line 66, in parse_from_file_obj
    return MailParser.from_file_obj(fp)
  File \AppData\Roaming\Python\Python38\s
r.py", line 166, in from_file_obj
    s = fp.read()
AttributeError: 'Message' object has no attribute 'read'

All help appreciated.

1

There are 1 answers

1
Vladimir On
body = msg.text or msg.html 

There may be several mail representation forms in a letter