前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >如何获取 Gmail 中邮件的摘要

如何获取 Gmail 中邮件的摘要

原创
作者头像
华科云商小徐
发布2024-05-10 10:28:41
1100
发布2024-05-10 10:28:41
举报
文章被收录于专栏:小徐学爬虫小徐学爬虫

要获取 Gmail 中邮件的摘要,我们可以使用 Gmail API。下面是使用 Python 和 Gmail API 获取邮件摘要的一般步骤:

1、问题背景

在使用 Gmail API 时,用户尝试获取邮件摘要,但始终返回空字符串。在使用 JavaScript Node SDK 和 Python SDK 时都遇到了此问题。

2、解决方案

  1. 使用 service.users().messages().get() 方法获取特定邮件的摘要。
代码语言:javascript
复制
const {google} = require('googleapis');
​
const SCOPES = [
  'https://www.googleapis.com/auth/gmail.readonly',
];
​
const OAuth2 = google.auth.OAuth2;
​
// Create credentials object using client_secret.json file
const credentials = JSON.parse(fs.readFileSync('client_secret.json'));
const client_secret = credentials.installed.client_secret;
const client_id = credentials.installed.client_id;
const redirect_url = credentials.installed.redirect_uris[0];
const oauth2Client = new OAuth2(client_id, client_secret, redirect_url);
​
// Generate the url that will be used for the consent dialog.
const authorizeUrl = oauth2Client.generateAuthUrl({
  access_type: 'offline',
  scope: SCOPES
});
​
// Retrieve the access token from the consent dialog
const getAccessToken = (callback) => {
  console.log('Authorize this app by visiting this url: ', authorizeUrl);
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });
  rl.question('Enter the authorization code: ', (code) => {
    rl.close();
    oauth2Client.getToken(code, (err, token) => {
      if (err) {
        console.log('Error retrieving access token', err);
        return;
      }
      callback(token);
    });
  });
};
​
// Use the access token to make an authenticated API call
const retrieveMessages = (token) => {
  oauth2Client.setCredentials(token);
  const service = google.gmail({version: 'v1', auth: oauth2Client});
  service.users.messages.get({
    'userId': 'me',
    'id': msg_id,
    'format': 'raw'
  }, (err, res) => {
    if (err) {
      console.log('Error retrieving messages', err);
      return;
    }
    // Print the message snippet
    console.log('Message snippet: %s', res.data.snippet);
  });
};
​
getAccessToken(retrieveMessages);
  1. 确保请求中包含 format=raw 参数。
代码语言:javascript
复制
from __future__ import print_function
​
import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
​
​
def get_message(service, user_id, msg_id, format_='metadata'):
    """Get a Message with given ID.
​
    Args:
      service: Authorized Gmail API service instance.
      user_id: User's email address. The special value "me"
      can be used to indicate the authenticated user.
      msg_id: ID of Message to retrieve.
      format: Format to return message, can be 'metadata' or 'full'
​
    Returns:
      Message object, or None when Message not found.
    """
    try:
        message = service.users().messages().get(
            userId=user_id, id=msg_id, format=format_).execute()
        print(F'Message snippet: {message["snippet"]}')
        return message
    except HttpError as error:
        print(F'An error occurred: {error}')
        return None
​
​
def main():
    """Shows basic usage of the Gmail API.
​
    Creates a Gmail API client object and retrieves a recent email message.
    """
    creds, _ = google.auth.default()
    # pylint: disable=maybe-no-member
    service = build('gmail', 'v1', credentials=creds)
    get_message(service, 'me', '146fccb21d960498', 'raw')
​
​
if __name__ == '__main__':
    main()

最后需要注意的是,此脚本仅获取了收件箱中的最新邮件的摘要。我们可以根据需要对其进行扩展,以获取更多邮件的信息或者根据特定标签过滤邮件等。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档