GMail API for Python

这篇博客介绍了如何使用Python与GMail API进行集成。首先,你需要满足Python环境和pip等前提条件,并启用GMail API。然后安装Google客户端库,设置样例代码。最后运行样例,首次运行会进行授权,后续将自动缓存授权信息。
摘要由CSDN通过智能技术生成

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(
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值