GMail API for Python

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_20454165/article/details/77712198

Prerequisites


To run this quickstart, you’ll need:

  • Python 2.6 or greater.
  • The pip package management tool.
  • Access to the internet and a web browser.
  • A Google account with Gmail enabled.

Step 1: Turn on the Gmail API


  1. Use this wizard to create or select a project in the Google Developers Console and automatically turn on the API. Click Continue, then Go to credentials.
  2. On the Add credentials to your project page, click the Cancel button.
  3. At the top of the page, select the OAuth consent screen tab. Select an Email address, enter a Product name if not already set, and click the Save button.
  4. Select the Credentials tab, click the Create credentials button and select OAuth client ID.
  5. Select the application type Other, enter the name “Gmail API Quickstart”, and click the Create button.
  6. Click OK to dismiss the resulting dialog.
  7. Click the file_download (Download JSON) button to the right of the client ID.
  8. Move this file to your working directory and rename it client_secret.json.

Step 2: Install the Google Client Library


Run the following command to install the library using pip:

$ pip install –upgrade google-api-python-client

See the library’s installation page for the alternative installation options.

Step 3: Set up the sample


Create a file named quickstart.py in your working directory and copy in the following code:

from __future__ import print_function
import httplib2
import os
import email
import base64

from apiclient import discovery
from apiclient import errors
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage

# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/gmail-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/gmail.readonly'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Gmail API Python'


def get_credentials(flags):
    """Gets valid user credentials from storage.

    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.

    Returns:
        Credentials, the obtained credential.
    """
    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


class GMail(object):

    def __init__(self, user_id='me'):
        """Initialize GMail class

        :param user_id: User's email address. The special value "me"
        can be used to indicate the authenticated user.
        """
        try:
            import argparse
            self._flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
        except ImportError:
            self._flags = None

        credentials = get_credentials(self._flags)
        http = credentials.authorize(httplib2.Http())
        self._service = discovery.build('gmail', 'v1', http=http)
        self._userId = user_id

    def ListMessagesMatchingQuery(self, query=''):
        """List all Messages of the user's mailbox matching the query.

        Args:
        service: Authorized Gmail API service instance.
        query: String used to filter messages returned.
        Eg.- 'from:user@some_domain.com' for Messages from a particular sender.

        Returns:
        List of Messages that match the criteria of the query. Note that the
        returned list contains Message IDs, you must use get with the
        appropriate ID to get the details of a Message.
        structure see https://developers.google.com/gmail/api/v1/reference/users/messages
        """
        try:
            response = self._service.users().messages().list(userId=self._userId,
                                                             q=query).execute()
            messages = []
            if 'messages' in response:
                messages.extend(response['messages'])

            while 'nextPageToken' in response:
                page_token = response['nextPageToken']
                response = self._service.users().messages().list(userId=self._userId, q=query,
                                                                 pageToken=page_token).execute()
                messages.extend(response['messages'])

            return messages
        except errors.HttpError, error:
            print('An error occurred: %s' % error)

    def ListThreadsMatchingQuery(self, query=''):
        """List all Threads of the user's mailbox matching the query.

        Args:
            query: String used to filter messages returned.
                   Eg.- 'label:UNREAD' for unread messages only.

        Returns:
            List of threads that match the criteria of the query. Note that the returned
            list contains Thread IDs, you must use get with the appropriate
            ID to get the details for a Thread.
        """
        try:
            response = self._service.users().threads().list(userId=self._userId, q=query).execute()
            threads = []
            if 'threads' in response:
                threads.extend(response['threads'])

            while 'nextPageToken' in response:
                page_token = response['nextPageToken']
                response = self._service.users().threads().list(userId=self._userId, q=query,
                                                                pageToken=page_token).execute()
                threads.extend(response['threads'])

            return threads
        except errors.HttpError, error:
            print('An error occurred: %s' % error)

    def GetThread(self, thread_id):
        """Get a Thread.

        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.
        thread_id: The ID of the Thread required.

        Returns:
        Thread with matching ID. structure in
                {
                  "id": string,
                  "snippet": string,
                  "historyId": unsigned long,
                  "messages": [
                    users.messages Resource
                  ]
                }
        """
        try:
            thread = self._service.users().threads().get(userId=self._userId, id=thread_id).execute()
            # messages = thread['messages']
            # print('thread id: %s - number of messages in this thread: %d' % (thread['id'], len(messages)))
            return thread
        except errors.HttpError, error:
            print('An error occurred: %s' % error)

    def GetSubjectOfThread(self, thread):
        """Get the subject of specified thread

        :param thread: the messages of some thread containing properties "id", "threadId", "labelIds", "snippet",
        "payload", "snippet" and so on. you can get full version at
        https://developers.google.com/gmail/api/v1/reference/users/messages#resource
        :return: the subject of the specified thread
        """
        messages = thread['messages']
        for msg in messages:
            for header in msg['payload']['headers']:
                if header['name'] == 'Subject':
                    return header['value']

    def GetThreadBySubject(self, subject):
        """Get the thread by specified subject name

        :param subject: string
        :return:
        """
        threads = self.ListThreadsMatchingQuery()
        for trd in threads:
            thread = self.GetThread(trd['id'])
            if self.GetSubjectOfThread(thread) == subject:
                return thread

    def GetMessage(self, 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 = self._service.users().messages().get(userId=self._userId, id=msg_id).execute()

            print('Message snippet: %s' % message['snippet'])

            return message
        except errors.HttpError, error:
            print('An error occurred: %s' % error)

    def GetMimeMessage(self, 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 = self._service.users().messages().get(userId=self._userId, 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)

            return mime_msg
        except errors.HttpError, error:
            print('An error occurred: %s' % error)

    def IsThreadContainingKeyword(self, thread_id, keyword):
        thread = self.GetThread(thread_id)
        for msg in thread['messages']:
            parts = msg['payload']['parts']
            for p in parts:
                if p['mimeType'] == u'text/plain':
                    text = p['body']['data']
                    if keyword in base64.urlsafe_b64decode(text.encode('ASCII')):
                        return True
        return False

    def GetThreadContainingKeyword(self, keyword):
        """Get a thread containing the given keyword

        :param keyword:
        :return:
        """
        threads = self.ListThreadsMatchingQuery()
        for trd in threads:
            if self.IsThreadContainingKeyword(trd['id'], keyword) is True:
                return trd
        else:
            return None


if __name__ == '__main__':
    gmail = GMail()

This version of code was rewritten, and has some sample usages of GMail API, enjoy!

Step 4: Run the sample


Run the sample using the following command:

$ python quickstart.py

  1. The sample will attempt to open a new window or tab in your default browser. If this fails, copy the URL from the console and manually open it in your browser.
    If you are not already logged into your Google account, you will be prompted to log in. If you are logged into multiple Google accounts, you will be asked to select one account to use for the authorization.
  2. Click the Accept button.
  3. The sample will proceed automatically, and you may close the window/tab.

The sample actually will get the authorization for the first time when you run it. And it will cache the authorization so it won’t pop a window to ask you to do confirmation next time.


Reference: https://developers.google.com/gmail/api/quickstart/python

猜你喜欢

转载自blog.csdn.net/sinat_20454165/article/details/77712198
今日推荐