如何使用Python访问Gmail邮箱
在本教程中,我们将详细介绍如何使用Python访问Gmail邮箱。通过本教程,你将学会如何设置Gmail API、编写Python代码以及获取邮件信息。
目录
准备工作
在开始之前,你需要确保以下几点:
- 拥有一个Google账户。
- 安装了Python 3.6或更高版本。
- 安装了
pip
包管理工具。
设置Gmail API
1. 创建Google Cloud项目
- 访问 Google Cloud Console。
- 点击“创建项目”按钮,输入项目名称,然后点击“创建”。
2. 启用Gmail API
- 在Google Cloud Console中,导航到“API和服务” > “库”。
- 在搜索框中输入“Gmail API”,然后点击“Gmail API”。
- 点击“启用”按钮以启用Gmail API。
3. 配置OAuth同意屏幕
- 在Google Cloud Console中,导航到“API和服务” > “OAuth同意”。
- 选择“外部”作为用户类型,然后点击“创建”。
- 填写应用名称、用户支持邮箱、开发者联系信息等必填字段。
- 在“测试用户”部分,添加你的Google账户邮箱地址。
- 点击“保存并继续”完成配置。
4. 创建OAuth 2.0凭据
- 在Google Cloud Console中,导航到“API和服务” > “凭据”。
- 点击“创建凭据”按钮,选择“OAuth客户端ID”。
- 选择“桌面应用”作为应用类型,然后点击“创建”。
- 下载凭据文件(
credentials.json
)并保存到你的项目目录中。
安装Python库
你需要安装以下Python库来访问Gmail API:
pip install --upgrade google-auth google-auth-oauthlib google-auth-httplib2 google-api-python-client
编写Python代码
以下是一个示例代码,用于获取Gmail邮箱中的前10封邮件:
import os.path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
# 如果修改了SCOPES,请删除token.json文件。
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']
def get_credentials():
"""获取并保存用户凭据。"""
creds = None
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
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(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
with open('token.json', 'w') as token:
token.write(creds.to_json())
return creds
def list_messages(service, user_id='me', max_results=10):
"""列出用户邮箱中的邮件。"""
results = service.users().messages().list(userId=user_id, maxResults=max_results).execute()
messages = results.get('messages', [])
return messages
def get_message(service, user_id, msg_id):
"""获取邮件内容。"""
message = service.users().messages().get(userId=user_id, id=msg_id, format='full').execute()
return message
def main():
creds = get_credentials()
service = build('gmail', 'v1', credentials=creds)
messages = list_messages(service)
for msg in messages:
message = get_message(service, 'me', msg['id'])
print(f"Message ID: {message['id']}")
print(f"Snippet: {message['snippet']}")
print('-' * 50)
if __name__ == '__main__':
main()
运行代码
将代码保存为gmail.py
,然后运行它:
python gmail.py
首次运行时,系统会提示你授权访问Gmail账户。授权后,程序将输出前10封邮件的ID和摘要。
常见问题及解决方法
1. 403: access_denied
- 原因:通常是由于OAuth同意屏幕配置问题或未启用Gmail API。
- 解决方法:
- 确保已在Google Cloud Console中启用Gmail API。
- 确保OAuth同意屏幕已正确配置,并添加了测试用户。
- 删除
token.json
文件并重新运行代码以重新授权。
2. 重定向URI不匹配
- 原因:Google Cloud Console中配置的重定向URI与代码中使用的URI不匹配。
- 解决方法:确保重定向URI已正确配置。
3. 访问令牌过期
- 原因:
token.json
文件中的访问令牌已过期。 - 解决方法:删除
token.json
文件并重新运行代码以重新授权。
总结
通过本教程,你学会了如何使用Python访问Gmail邮箱。我们详细介绍了如何设置Gmail API、安装Python库、编写代码以及解决常见问题。如果验证成功,但是卡住,看看你是否启用了终端代理。