Search code examples
python-2.7imapgmail-imap

I want to retrieve emails from gmail account with the body using imap in python


This is my code and m trying to get the emails from gmail with the body but it end with the error. " mail = email.message_from_string(data0) AttributeError: 'str' object has no attribute 'message_from_string'" Any help is appriciated!. the error message is being shown in the picture

#!/usr/bin/env python


import getpass
import imaplib
import email
from email.parser import HeaderParser

M = imaplib.IMAP4_SSL("imap.gmail.com", 993)
email = raw_input("Email address: ")
password = getpass.getpass()
M.login(email, password)

M.select()
resp, data = M.FETCH(1, '(RFC822)')
mail = email.message_from_string(data[0][1])

for part in mail.walk():
  # multipart are just containers, so we skip them
  if part.get_content_maintype() == 'multipart':
      continue

  # we are interested only in the simple text messages
  if part.get_content_subtype() != 'plain':
    continue

  payload = part.get_payload()
  print payload

Solution

  • You've overwritten the "email" module with a string you've inputted from the user.

    import email
    ...
    email = raw_input("Email address: ")
    ...
    mail = email.message_from_string(data[0][1])
    

    Change the line email = raw_input("Email address: ") to some other name, such as address = raw_input("Email address: ") and adjust your code as required.