def GetMessage(service, user_id, msg_id):
"""Get a Message with given ID.
Args:
service: Authorized Gmail API service instance.
user_id: User's email address. The special value "me"
can be used to indicate the authenticated user.
msg_id: The ID of the Message required.
Returns:
A Message.
"""
try:
message = service.users().messages().get(userId=user_id, id=msg_id).execute()
return message
except errors.HttpError, error:
print 'An error occurred: %s' % error
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('gmail', 'v1', http=http)
results = service.users().messages().list(userId='me', labelIds='UNREAD').execute()
messages = results.get('messages', [])
for msg in messages:
id = msg['id']
msgobj = GetMessage(service, 'me', id)
print msgobj['snippet']
当您通过Gmail回复时,您会收到消息,然后是之前回复中的消息。消息的“片段”部分也会收到回复。我想在电子邮件中找到最新的文本(而不是回复部分)
yeah that sounds good
On Sun, Feb 21, 2016 at 7:36 PM, <apple@gmail.com> wrote:
you want to play ball? ________________________________________ From: banana@gmail.com
除了片段之外还有其他任何内容可以获取最新的电子邮件文本吗?
答案 0 :(得分:2)
遗憾的是,没有什么可以做到的。 snippet
是消息的一小部分,(基于API Explorer观察)通常约为100 + - 字符。如果消息太短,它将获得前面消息的回复部分。
我观察到的是,该片段的消息部分通常具有On [date]
语句。我认为如果有一个类似的短语,你可以检查和分割消息(这会有点棘手,因为短语本身也可以是部分的)。
答案 1 :(得分:0)
def GetMimeMessage(service, user_id, msg_id):
"""Get a Message and use it to create a MIME Message.
Args:
service: Authorized Gmail API service instance.
user_id: User's email address. The special value "me"
can be used to indicate the authenticated user.
msg_id: The ID of the Message required.
Returns:
A MIME Message, consisting of data from Message.
"""
try:
message = service.users().messages().get(userId=user_id, id=msg_id,
format='raw').execute()
#print 'Message snippet: %s' % message['snippet']
msg_str = base64.urlsafe_b64decode(message['raw'].encode('ASCII'))
mime_msg = email.message_from_string(msg_str)
for part in mime_msg.walk():
if part.get_content_type() == 'text/plain':
print part.get_payload()
return mime_msg
except errors.HttpError, error:
print 'An error occurred: %s' % error
我决定改为使用Mimemessage。如果有的话,这似乎总是有回复部分。这样可以更容易地查找并解析它们