我想使用python中的imap从gmail帐户检索电子邮件

时间:2015-03-24 14:33:52

标签: python-2.7 imap gmail-imap

这是我的代码,我试图从机身获取gmail的电子邮件,但它以错误结束。 " mail = email.message_from_string(data 0) AttributeError:' str'对象没有属性' message_from_string'" 任何帮助是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

1 个答案:

答案 0 :(得分:0)

您已覆盖"电子邮件"带有您从用户输入的字符串的模块。

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

将行email = raw_input("Email address: ")更改为其他名称,例如address = raw_input("Email address: "),并根据需要调整代码。