Gmail API - 在线程中获取最后一条消息[Python]

时间:2018-02-18 13:04:15

标签: python gmail-api

我使用Gmail API检索帖子中的最后一条消息。 在下面的代码中,我得到了所有看不见的线程。然后,对于每个线程,我得到最后一条消息。但是当我想得到最后一条消息文本时,我会得到一个漏洞文本。

import httplib2
import os
import json
from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
import base64
import email

try:
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

SCOPES = 'https://www.googleapis.com/auth/gmail.readonly'
CLIENT_SECRET_FILE = str(os.path.dirname(os.path.abspath(__file__))).replace('MailAssistant', '') + '/static/MailAssistant/main/assets/client_secret.json'
APPLICATION_NAME = 'Gmail API Python Quickstart'


def get_credentials():

    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,
                                   'gmail-python-quickstart.json')

    store = Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else: # Needed only for compatibility with Python 2.6
            credentials = tools.run(flow, store)
        print('Storing credentials to ' + credential_path)
    return credentials


def GetMessageBody(service, user_id, msg_id):

        message = service.users().messages().get(userId=user_id, id=msg_id, format='raw').execute()
        msg_str = base64.urlsafe_b64decode(message['raw'].encode('ASCII'))
        mime_msg = email.message_from_bytes(msg_str)
        messageMainType = mime_msg.get_content_maintype()
        if messageMainType == 'multipart':
                for part in mime_msg.walk():
                        if part.get_content_maintype() == 'text':
                                return part.get_payload()
                return ""
        elif messageMainType == 'text':
                return mime_msg.get_payload()


def get_unread_threads(service, user_id='me'):
    # I get unseen threads
    threads = service.users().threads().list(userId=user_id, q='is:unread').execute().get('threads', [])
    print("Unread Threads: ", len(threads))
    biggest_internal_date = 0
    last_msg = []
    # Iterate each Thread
    for thread in threads:
        # I get those threads info
        tdata = service.users().threads().get(userId=user_id, id=thread['id']).execute()
        # I get the last message from the actual Thread
        for message in tdata['messages']:
            if int(message['internalDate']) > int(biggest_internal_date):
                biggest_internal_date = message['internalDate']
                last_msg = message
        # I get the data from that last message
        print(GetMessageBody(service, user_id, last_msg['id']))


def main():
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('gmail', 'v1', http=http)

    get_unread_threads(service)


if __name__ == '__main__':
    main()

但是我得到了所有的主题消息:

tuturuturururlastmessage

On Sat, Feb 17, 2018 at 11:43 PM, Danny Julian <dannyjulian.x@gmail.com>
wrote:

> asdadsadsas
>
> On Fri, Feb 16, 2018 at 12:35 PM, Danny Julian <dannyjulian.x@gmail.com>
> wrote:
>
>> message3
>>
>> On Fri, Feb 16, 2018 at 12:34 PM, Daniel Julian <djulian@x.com>
>> wrote:
>>
>>> message2
>>>
>>>
>>>
>>> 2018-02-16 12:33 GMT-03:00 Danny Julian <dannyjulian.x@gmail.com>:
>>>
>>>> message1
>>>>
>>>
>>>
>>
>

有没有办法我只能获得“tuturuturururlastmessage”?或者我必须找到解析整个事情的方法?

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

没有。从技术上讲,你只得到一条消息,恰好可以将所有先前的消息引回到第一条消息。这是该主题的最后一条消息,并且您正确地返回了它。

顺便提一下,GMail网络界面(以及此后的其他邮件客户端)通过抓取提示(通常是缩进或'&gt;'标志)来隐藏引号。

如果您希望从附加引号中隔离最后一条消息的实际内容,则必须通过解析和转换字符串来执行类似的操作。