要获取 Gmail 中邮件的摘要,我们可以使用 Gmail API。下面是使用 Python 和 Gmail API 获取邮件摘要的一般步骤:
1、问题背景
在使用 Gmail API 时,用户尝试获取邮件摘要,但始终返回空字符串。在使用 JavaScript Node SDK 和 Python SDK 时都遇到了此问题。
2、解决方案
- 使用 service.users().messages().get() 方法获取特定邮件的摘要。
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);
- 确保请求中包含 format=raw 参数。
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()
最后需要注意的是,此脚本仅获取了收件箱中的最新邮件的摘要。我们可以根据需要对其进行扩展,以获取更多邮件的信息或者根据特定标签过滤邮件等。