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 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值