Validus A dead simple Python data validation library.…
Python 读取gmail, Python 搜索gmail, Python操作gmail, How to access Gmail using Python
步骤1:开启Gmail API
中文版:
开启Gmail API
首先,您需要启用Gmail API并从您的Google帐户获取所需的OAuth凭据。步骤如下所示。
1。使用此向导可以在Google Developers Console中创建或选择一个项目,然后自动打开API。单击“继续(Continue)”,然后单击“凭据(credentials)”。
2。在 “添加凭据(Add credentials)” 页面上,单击“ 取消(Cancel)”按钮。
3。在页面左边,选择OAuth同意屏幕 (OAuth consent screen) 标签。选择一个电子邮件地址,输入产品名称(如果尚未设置),然后单击保存(Save)按钮。
4。选择“ 凭据(credentials)”标签,点击“ 创建凭据(Create credentials)”按钮,然后选择OAuth客户端ID (Auth client ID)。
5。选择应用程序类型“ 其他 (Other)”,输入名称“ Gmail API快速入门”,然后单击“ 创建(Create)”按钮。
6。单击“ 确定(OK)”关闭出现的对话框。
7。点击客户端ID右侧的Download JSON按钮。
8。将此文件移至您的工作目录,并将其重命名为client_secret.json。
英文版:
Turning on the Gmail api
You first need to enable Gmail api and get the required OAuth credentials from your Google account. The steps which are shown below.
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 Download JSON button to the right of the client ID.
8. Move this file to your working directory and rename it client_secret.json.
步骤2:安装Google客户端库
运行以下命令以使用pip安装该库:
pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
请参阅库的安装页面以获取替代安装选项。
步骤3:设置样本
quickstart.py
在您的工作目录中创建一个名为的文件,并复制以下代码:
步骤4:运行示例
使用以下命令运行示例:
python quickstart.py
- 该示例将尝试在默认浏览器中打开新窗口或标签。如果失败,请从控制台复制URL,然后在浏览器中手动打开它。如果尚未登录Google帐户,则会提示您登录。如果登录多个Google帐户,系统将要求您选择一个帐户进行授权。
- 单击接受按钮。
- 该示例将自动进行,您可以关闭窗口/选项卡。
认证部分也可以参考:
Google Ads API 使用第一步:申请 Google OAuth 2.0 存取Google API, 生成 adsapi_php.ini (Google Client ID)
现在,要从Gmail获取实际邮件,我们将使用以下代码。初始授权代码相同,只是api调用更改。
# Call the Gmail API, only get 1 of the the recent message ids # First get the message id for the message results = service.users().messages().list(userId='me', maxResults=1).execute() # get the message id from the results object message_id = results['messages'][0]['id'] # use the message id to get the actual message, including any attachments message = service.users().messages().get(userId='me', id=message_id).execute() # now the message object contains the entire recent message
此处 提供了用于访问Gmail api的详细功能列表。
个人实例:
#!/usr/bin/env python # coding=utf-8 from __future__ import print_function import pickle import os.path import base64 import re from datetime import datetime import html2text from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request from apiclient import errors # pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib # pip install html2text # If modifying these scopes, delete the file token.pickle. SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'] # 获取gmail授权 def get_credit(credential_json_name, token_file_name): creds = None # The file token.pickle stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists(token_file_name): with open(token_file_name, 'rb') as token: creds = pickle.load(token) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file(credential_json_name, SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open(token_file_name, 'wb') as token: pickle.dump(creds, token) return build('gmail', 'v1', credentials=creds) # 多gmail账号转换 def get_account(acc): # token.pickle: jk@gmail.com (credentials_jk.json) # token.pickle2: Hallel@gmail.com (credentials_halle.json) service_accounts = { 'jk': {"json": "credentials_jk.json", "token": "token.pickle"}, 'hallel': {"json": "credentials_hallel.json", "token": "token.pickle2"} } return service_accounts[acc] # 获取gmail的label名称,以及对应的label id def get_labels(service): output = {} results = service.users().labels().list(userId='me').execute() labels = results.get('labels', []) if not labels: print('No labels found.') else: for label in labels: output[label['name']] = label['id'] # print(label['name'] + ': ' + label['id']) return output # 通过条件查询,获取gmail邮件 # Gmail 中可使用的搜索运算符:https://support.google.com/mail/answer/7190?hl=zh-Hans def get_messages_by_query(service, query='', label_ids=['INBOX'], user_id='me'): try: response = service.users().messages().list(userId=user_id, labelIds=label_ids, q=query).execute() messages = [] if 'messages' in response: messages.extend(response['messages']) while 'nextPageToken' in response: page_token = response['nextPageToken'] response = service.users().messages().list(userId=user_id, q=query, pageToken=page_token).execute() messages.extend(response['messages']) return messages except errors.HttpError as error: print('An error occurred: %s' % error) # 通过lable id获取gmail邮件 def get_messages_by_labels(service, label_ids=[], user_id='me'): try: response = service.users().messages().list(userId=user_id, labelIds=label_ids).execute() messages = [] if 'messages' in response: messages.extend(response['messages']) while 'nextPageToken' in response: page_token = response['nextPageToken'] response = service.users().messages().list(userId=user_id, labelIds=label_ids, pageToken=page_token).execute() messages.extend(response['messages']) return messages except errors.HttpError as error: print('An error occurred: %s' % error) # 通过邮件id,获取邮件内容 def get_message(service, msg_id, user_id='me', msg_format='raw'): try: message = service.users().messages().get(userId=user_id, id=msg_id, format=msg_format).execute() msg_str = base64.urlsafe_b64decode(message['raw'].encode('ASCII')) message['body'] = msg_str.decode("utf-8") return message except errors.HttpError as error: print('An error occurred: %s' % error) # 获取的邮件默认是html,转换成纯文本(' '.join(s.split()) 可以实现 删除字符串中的连续空格只保留一个) def html_to_text(html): return (' '.join(html2text.html2text(html).split())).strip() # 通过邮件id数组,获取邮件数组 def get_messages(service, message_ids): output = [] for message_id in message_ids: message = get_message(service, message_id['id']) # print(message['body']) output.append(message['body']) return output # 获取邮件内容中的 认证码 (个人使用,别人可能用不到次函数) def get_verify_code(text): result = re.search('Use the code below to verify your device: (\d+) \[No,', html_to_text(text)) return result.group(1) # 主函数 def main(acc): account = get_account(acc) service = get_credit(account["json"], account["token"]) # two_mins_ago = (datetime.datetime.now() - datetime.timedelta(days=5)).strftime("%Y-%m-%d %H:%M"); messages_ids = get_messages_by_query(service, 'from:accounts@bigcommerce.com subject:"Login from New Device to BigCommerce" after:' + datetime.now().strftime( "%Y-%m-%d")) messages = get_messages(service, messages_ids) for message in messages: verify_code = get_verify_code(message) print(verify_code) if __name__ == '__main__': main('hallel')
可以参考的网站:
Gmail API Python, PHP, Java 说明文档
Gmail 中可使用的搜索运算符,Search operators you can use with Gmail
Linux: 利用 Alpine 在命令行里访问 Gmail
本文:Python 读取gmail, Python 搜索gmail, Python操作gmail, How to access Gmail using Python