简体   繁体   中英

Excel File from Gmail API Request

I have created a program which gets attachment ids for files in an email and then gets the attachment using the Gmail. The type of files I'm interested in getting are Excel files, so assume that I get an attachment that is a.xlsx.

According to the API reference here the field I need from the response is Data. I am able to get this field in C# but I am stuck turning this into an excel file.

Any examples would be most helpful in Python or C#.

I understand that you have a mail in Gmail with a XLSX file attached and you want to download it into your local folder. I will assume that you already know both your message and attachment identifier, if that is not the case please forgive me and write a comment saying it so I can further help you. If you already have the identifiers, this code will help you:

#!/usr/bin/env python3

# IMPORTs for Gmail API
from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

# IMPORTs for data manipulation
from base64 import urlsafe_b64decode
import email

SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']


def main():
    # Gmail API configuration
    creds = None
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)
    service = build('gmail', 'v1', credentials=creds)

    messageID = "{MESSAGE IDENTIFIER}"
    attachmentID = "{ATTACHMENT IDENTIFIER}"

    # Step I - Getting the attachment
    response = service.users().messages().attachments().get(
        userId='me', messageId=messageID, id=attachmentID).execute()

    # Step II - Manipulating the data
    bytesFile = urlsafe_b64decode(response["data"])
    if bytesFile[0:2] != b'PK':
        raise ValueError('The attachment is not a XLSX file!')
    message = email.message_from_bytes(bytesFile)

    # Step III - Storing the file
    open('attachment.xlsx', 'wb').write(message.get_payload(decode=True))


if __name__ == '__main__':
    main()

The initial setup is to configure a Gmail service; I got this part from the Gmail python quickstart . The first step is to call the .get() method to receive a JSON response with the attachment. The file will be received in the attribute data . After that, in the second step, the code will use urlsafe_b64decode to convert data into a bytes object. Before continuing, the script will check the magic number of the bytes object to verify that it is indeed a XLSX file; and if it's not, an error will be raised. Finally, if everything is correct, a message object will be created from the bytes object using .message_from_bytes() .

In the third and final step the script will save the message as attachment.xlsx using the method .get_payload() . Please, notice how I used the decode parameter for a Content-Transfer-Encoding header of 8bit . The file will be written in the local folder. Please, don't hesitate to ask me any questions if you need me to clarify something.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM