将Gmail电子邮件作为字符串获取 - 我如何从电子邮件中获取图像

时间:2017-10-16 20:45:10

标签: python email gmail email-attachments imaplib

我使用以下代码检索了Gmail中的电子邮件正文。我现在想要搜索它并使用与你在字符串上使用的find命令类似的东西来挑选正文的某些部分。 E.G。

DVRName = email_message[email_message.find("ALARM NAME(NUM):" +1:email_message.find("Report")-1]

当我尝试这个时会产生错误:

AttributeError: 'Message' object has no attribute 'find'

我认为这是因为我使用的查找不正确或电子邮件数据不是字符串?

此代码会生成电子邮件以及大量乱码。

import imaplib
import datetime
from datetime import timezone
from email.parser import HeaderParser
timezone = ('gmt')

mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('f*****m', 'f******3')
mail.list()
# Out: list of "folders" aka labels in gmail.
mail.select("inbox") # connect to inbox.
result, data = mail.search(None, "All")

ids = data[0] # data is a list.
id_list = ids.split() # ids is a space separated string
latest_email_id = id_list[-1] # get the latest

# fetch the email body (RFC822) for the given ID
result, data = mail.fetch(latest_email_id, ("(UID BODY[TEXT])"))

raw_email = data[0][1] # here's the body, which is raw text of the whole email
# including headers and alternate payloads
raw_email_string = raw_email.decode('utf-8')
email_message = email.message_from_string(raw_email_string)

print (email_message)

还可以分别检索主题,日期等吗?

0 个答案:

没有答案