Gmail API 对接问题汇总

1. 权限获取

     官方文档:https://developers.google.com/identity/protocols/oauth2

     gmail遵循auth2协议,需要在页面授权拿到code(授权码) ,服务端就可以保存code到数据库,通过接口请求获取access_token和refresh_token(参考文章:使用HTTP获取 OAuth 2.0 access tokens(Google)_菜鸟的学习笔记-CSDN博客_chrome浏览器怎么查看oauth获取的token)

请求:

POST /oauth2/v4/token HTTP/1.1
Host: www.googleapis.com
Content-Type: application/x-www-form-urlencoded

code=4/v6xr77ewYqhvHSyW6UJ1w7jKwAzu&
client_id=xxxx.apps.googleusercontent.com&
client_secret=your_client_secret&
redirect_uri=https://oauth2.example.com/code&
grant_type=authorization_code

返回:

{
  "access_token": "ya29.GlvbA3LIk7eIVWpXQJAhqcm3yCKxy7Fopilxm9ft5rXQwxKqBy9Xfno8Jz8DKBBtT3N2DFQ2SHVZ-POLJZaNDE6Ricz12EI-qoVTwSV12A0pD2bwLBxBcnNTGXKm",
  "expires_in": 3599,
  "refresh_token": "1/20S52RHS3KSqbbiHzuHENaINOwIPZToRycITjlEUX0s",
  "token_type": "Bearer"
}

refresh_token 很重要,access_token每3600秒失效,需要通过refresh_token重新请求获取,所以做个定时任务,每五十分钟刷新一下access_token即可。

注:refresh_token的有效期基本是永久,除非用户改密码或者权限收回

请求:

POST /oauth2/v4/token HTTP/1.1
Host: www.googleapis.com
Content-Type: application/x-www-form-urlencoded

client_id=xxxxx.apps.googleusercontent.com&
client_secret=your_client_secret&
refresh_token=1/6BMfW9j53gdGImsiyUH5kU5RsR4zwI9lUVX-tqf8JXQ&
grant_type=refresh_token

返回:

{
  "access_token": "ya29.GlvbA2Pfz3-egAlzdN6b5ZLOvfDhrcyiHwLkxGQbj11rjEzD9XH5bCEijQF6Lr4x1oTd76fT-dVXv1B1afkIh5_SAkBiCNtJ8krQwesgSWX9zmiqUZuapzZTWIHy",
  "token_type": "Bearer",
  "expires_in": 3600,

   "token_id": "Bearer eyJhbxxxxxx" // 遵循JWT协议,可以反解析出用户的信息
}

所以,权限的获取,就是要搞清楚code,access_token 和 refresh_token的区别

2. 邮件同步

    参考官方文档:https://developers.google.com/gmail/api/guides/sync

    2.1  全量同步

 GET https://gmail.googleapis.com/gmail/v1/users/{userId}/messages

    2.2  增量同步

GET https://gmail.googleapis.com/gmail/v1/users/{userId}/history

          全量同步后获取的historyId入库,下次同步从historyId开始往后继续同步

          (1) historyId 404问题解决

           参考文档:https://developers.google.com/gmail/api/reference/rest/v1/users.history/list

           historyId会失效,所以需要进行一次全量的同步(通过messageId去重),重新获取有效的                 historyId作增量同步       

          (2) 内容乱码

           遵循Base64 RFC 4648 标准. 需要替换- 为+ , _ 为 /

       string.replaceAll("-",  "+").replaceAll("_",  "/");

        (3)只同步指定日期的邮件

            参考文档:https://support.google.com/mail/answer/7190 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要使用Python获取Gmail的电子邮件,你可以使用Google API客户端库。以下是一个简单的示例代码,可以帮助你开始: 首先,确保你已经安装了google-api-python-client库。你可以使用以下命令进行安装: ``` pip install google-api-python-client ``` 接下来,你需要创建一个Google API项目,并启用Gmail API。在创建项目后,你将获得一个客户端ID和客户端密钥。 ```python from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build # 设置API访问范围 SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'] def authenticate_gmail(): """使用OAuth 2.0进行身份验证,并返回Gmail服务对象""" flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) return build('gmail', 'v1', credentials=creds) def get_emails(): """获取Gmail收件箱中的邮件列表""" service = authenticate_gmail() results = service.users().messages().list(userId='me', labelIds=['INBOX']).execute() messages = results.get('messages', []) if not messages: print('没有找到邮件.') else: print('最新一封邮件的信息:') message = service.users().messages().get(userId='me', id=messages[0]['id']).execute() print('主题:', message['subject']) print('发件人:', message['from']) print('内容:', message['snippet']) get_emails() ``` 在上面的代码中,你需要将 `credentials.json` 替换为你的客户端密钥文件的路径。该代码使用OAuth 2.0进行身份验证,并使用Gmail API获取收件箱中的邮件列表。然后,它打印出最新一封邮件的主题、发件人和摘要。 确保你已经启用了Gmail API,并拥有正确的客户端密钥文件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值