Python imaplib获取正文电子邮件gmail

时间:2012-12-25 10:24:21

标签: python email request imap imaplib

read this already并写了这个脚本来获取某些邮箱中的电子邮件正文,标题以'$'开头,由一些发件人发送。

import email, getpass, imaplib, os

detach_dir = "F:\PYTHONPROJECTS" # where you will save attachments
user = raw_input("Enter your GMail username --> ")
pwd = getpass.getpass("Enter your password --> ")

# connect to the gmail imap server
m = imaplib.IMAP4_SSL("imap.gmail.com")
m.login(user, pwd)

m.select("PETROLEUM") # here you a can choose a mail box like INBOX instead
# use m.list() to get all the mailboxes

resp, items = m.search(None, '(FROM "EIA_eLists@eia.gov")')
items = items[0].split() # getting the mails id

my_msg = [] # store relevant msgs here in please
msg_cnt = 0
break_ = False
for emailid in items[::-1]:
    resp, data = m.fetch(emailid, "(RFC822)")
    if ( break_ ):
        break 
    for response_part in data:
      if isinstance(response_part, tuple):
          msg = email.message_from_string(response_part[1])
          varSubject = msg['subject']
          if varSubject[0] == '$':
              msg_cnt += 1
              my_msg.append(msg)
              print msg_cnt
              print email.message_from_string(response_part[1])
              if ( msg_cnt == 5 ):
                  break_ = True 

如果我打印email.message_from_string(response_part[1]),我可以看到它包含第一个信息(标题,从,到,日期......),全文正文。但是,我无法取得身体本身。 email.message_from_string(response_part[0])打印邮件IDS,email.message_from_string(response_part[2])超出范围。 email.message_from_string(response_part[1][0])也没有这样做。

谢谢和问候。

更新

现在,我几乎可以拥有正文。然而,它仍然被首先出现的信息声明所破坏。我得到了结果

From nobody Tue Dec 25 11:42:58 2012

US=3D$4.030

EastCst=3D$4.036

NewEng=3D$4.205

CenAtl=3D$4.149

LwrAtl=3D$3.921

Midwst=3D$3.984

GulfCst=3D$3.945

RkyMt=3D$4.195

WCst=3D$4.187

CA=3D$4.268

我希望摆脱From nobody Tue Dec 25 11:42:58 2012这是信息。我知道我可以解析文本寻找第一条相关的行...我知道。

实现目标的代码(插入我的第一个样本)是

  if varSubject[0] == '$':
      r, d = m.fetch(emailid, "(UID BODY[TEXT])")
      msg_cnt += 1
      my_msg.append(msg)
      print email.message_from_string(d[0][1])

你有更好的方法(没有信息字符串)???更多:现在获取日期的命令是什么?我知道我可以varDate = msg['date']在上面适合的地方,但是如何才能获取每月 - 每年?致谢

4 个答案:

答案 0 :(得分:8)

我已设法使用Gmail工作,它会提取有用位并将其输出到文本文件:

const object = {/**/}

type SomeType = {
    foo: string,
    bar: bool,
    baz: Object,
}

describe('object', () => {
    describe('.subfield', () => {
        it('conforms to SomeType', () => {
            // Here I want to write an 'expect'
            // that checks if object.subfield
            // conforms to the SomeType flow type?
        })
    });
});

答案 1 :(得分:5)

您可以通过执行以下任何操作来获取正文的内容

msg.as_string()
str(msg)
repr(msg)

http://docs.python.org/2.7/library/email.message.html#email.message.Message

答案 2 :(得分:0)

from imap_tools import MailBox

# get all attachments from INBOX and save them to files
with MailBox('imap.my.ru').login('acc', 'pwd', 'INBOX') as mailbox:
    for msg in mailbox.fetch():
        print(msg.text)
        print(msg.html)
    

这将需要外部库,但要简单得多。

https://github.com/ikvk/imap_tools

答案 3 :(得分:-1)

client.send_message(chat_id, "message") # i want 2 this at 12:00 for example