简体   繁体   中英

How can you get the recipients of an email gmail python API

def getBody():
    """Shows basic usage of the Gmail API.
    Lists the user's Gmail labels.
    """
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    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)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)
    service = build('gmail', 'v1', credentials=creds)
    # Call the Gmail API
    while True:
        labelName = "READ-BY-SCRIPT"
        LABEL_ID = 'Label_8507504117657095973'
        results = service.users().messages().list(
            userId='me', q="-label:"+labelName, maxResults=1).execute()
        messages = results.get('messages', [])
        body = []
        if not messages:
            TEACHER_NAME = "a "
            LINK = "https://google.com"
            DATE = "c"
            body = "d"
            return TEACHER_NAME, LINK, DATE, body
            break
        else:
            for message in messages:
                msg = service.users().messages().get(
                    userId='me', id=message['id']).execute()
                body.append(msg['payload']['parts'])
                if 'data' in body[0][0]['body']:
                    body = base64.urlsafe_b64decode(
                        body[0][0]['body']['data'])
                elif 'data' in body[0][1]['body']:
                    body = base64.urlsafe_b64decode(
                        body[0][1]['body']['data'])
                body = str(body)
                
                body = body.replace("\\\r", "\r").replace("\\\n", "\n").replace('\\xe2\\x80\\x99', "'").replace('\\xc3\\xa9', 'e').replace('\\xe2\\x80\\x90', '-').replace('\\xe2\\x80\\x91', '-').replace('\\xe2\\x80\\x92', '-').replace('\\xe2\\x80\\x93', '-').replace('\\xe2\\x80\\x94', '-').replace('\\xe2\\x80\\x94', '-').replace('\\xe2\\x80\\x98', "'").replace('\\xe2\\x80\\x9b', "'").replace('\\xe2\\x80\\x9c', '"').replace('\\xe2\\x80\\x9c', '"').replace(
                    '\\xe2\\x80\\x9d', '"').replace('\\xe2\\x80\\x9e', '"').replace('\\xe2\\x80\\x9f', '"').replace('\\xe2\\x80\\xa6', '...').replace('\\xe2\\x80\\xb2', "'").replace('\\xe2\\x80\\xb3', "'").replace('\\xe2\\x80\\xb4', "'").replace('\\xe2\\x80\\xb5', "'").replace('\\xe2\\x80\\xb6', "'").replace('\\xe2\\x80\\xb7', "'").replace('\\xe2\\x81\\xba', "+").replace('\\xe2\\x81\\xbb', "-").replace('\\xe2\\x81\\xbc', "=").replace('\\xe2\\x81\\xbd', "(").replace('\\xe2\\x81\\xbe', ")")
                return body

print(getBody())

This code gets the body of the most recent email and after adjusting format a bit, prints the body. How can I instead get the recipients of the email and print those out? I couldn't seem to find anything about it on the documentation: https://developers.google.com/gmail/api/reference/rest/v1/users.messages

The recipients of a message are available in the headers of the raw message (To, From, Subject). The headers[] object has the following description:

List of headers on this message part. For the top-level message part, representing the entire message payload, it will contain the standard RFC 2822 email headers such as To, From, and Subject.

headers = msg['payload']['headers']
for header in headers:
    if header['name'] == 'To':
        print(header['value'])

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