谷歌的GMail API可以用來下載附件。要使用它,首先需要在Google Cloud Platform上注冊一個新的應用程序,然后創建一個OAuth 2.0客戶端ID,并啟用GMail API。
接下來,需要使用Google API客戶端庫,如JavaScript、Python或Java,來訪問GMail API。可以使用以下代碼來訪問GMail API:
// JavaScript
// Initialize the API
gapi.client.init({
'apiKey': 'YOUR_API_KEY',
'clientId': 'YOUR_CLIENT_ID',
'scope': 'https://www.googleapis.com/auth/gmail.readonly',
'discoveryDocs': ['https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest']
}).then(function() {
// Use the API
gapi.client.gmail.users.messages.get({
'userId': 'me',
'id': 'MESSAGE_ID'
}).then(function(response) {
// Get the attachment ID
var attachmentId = response.result.payload.parts[0].body.attachmentId;
// Download the attachment
gapi.client.gmail.users.messages.attachments.get({
'id': attachmentId,
'messageId': 'MESSAGE_ID',
'userId': 'me'
}).then(function(response) {
// Save the attachment
var attachment = response.result;
// ...
});
});
});
// Python
# Initialize the API
service = build('gmail', 'v1', credentials=credentials)
# Use the API
message = service.users().messages().get(userId='me', id='MESSAGE_ID').execute()
# Get the attachment ID
attachment_id = message['payload']['parts'][0]['body']['attachmentId']
# Download the attachment
attachment = service.users().messages().attachments().get(userId='me', messageId='MESSAGE_ID', id=attachment_id).execute()
# Save the attachment
# ...