Thaian Thaian - 4 months ago 10
Python Question

'str' object has no attribute 'message_from_bytes'

I have pieco of code to get emails from messages from my inbox(gmail). Getting emails work correct when I print email_from but I would like to do some operation on data split name and email etc. but then code broke after print first loop step and I get error:

Traceback (most recent call last):
File "C:\Users\loc\Desktop\extract_gmail.py", line 24, in <module>
email_message_raw = email.message_from_bytes(data[0][1])
AttributeError: 'str' object has no attribute 'message_from_bytes'


Can you give me some advice how to solve problem?

Code:

import imaplib
import email
from email.header import Header, decode_header, make_header

# Connection settings
HOST = 'imap.gmail.com'
USERNAME = '***'
PASSWORD = '***'

m = imaplib.IMAP4_SSL(HOST, 993)
m.login(USERNAME, PASSWORD)
m.select('INBOX')

result, data = m.uid('search', None, "ALL")
if result == 'OK':
for num in data[0].split()[:5]:
result, data = m.uid('fetch', num, '(RFC822)')
if result == 'OK':
# Get raw message
email_message_raw = email.message_from_bytes(data[0][1])

# Decode headers
email_from = str(make_header(decode_header(email_message_raw['From'])))

# Print each name and email
name, email = email_from.split('<')
email.replace(">", "")
print(name + "|" + email)

# When i swap to just print email_from then works
# print(email_from)



# Close server connection
m.close()
m.logout()

Answer

In your code you replaced the email variable..

Try this...

import imaplib
import email
from email.header import Header, decode_header, make_header

# Connection settings
HOST = 'imap.gmail.com'
USERNAME = '***'
PASSWORD = '***'

m = imaplib.IMAP4_SSL(HOST, 993)
m.login(USERNAME, PASSWORD)
m.select('INBOX')

result, data = m.uid('search', None, "ALL")
if result == 'OK':
    for num in data[0].split()[:5]:
        result, data = m.uid('fetch', num, '(RFC822)')
        if result == 'OK':
            # Get raw message
            email_message_raw = email.message_from_bytes(data[0][1])

            # Decode headers
            email_from = str(make_header(decode_header(email_message_raw['From'])))

            # Print each name and email
            name, email_addr = email_from.split('<')
            email_addr.replace(">", "")
            print(name + "|" + email_addr)

            # When i swap to just print email_from then works
            # print(email_from)



# Close server connection
m.close()
m.logout()
Comments