Python GMAIL API 读取完整邮件正文

huangapple go评论63阅读模式
英文:

Python GMAIL API Read Full Email Body

问题

以下是您要翻译的代码部分:

# 从 __future__ 导入 print_function
import os.path
import re
import base64
import email
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

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

def main():
    """Shows basic usage of the Gmail API.
    Lists the user's Gmail labels.
    """
    creds = get_credentials()

    try:
        # 调用 Gmail API
        service = build('gmail', 'v1', credentials=creds)
        messages_list = service.users().messages().list(userId='me', labelIds=None, q=None,
                                                        pageToken=None, maxResults=None, includeSpamTrash=None).execute().get('messages')
        for msg in messages_list:
            txt = service.users().messages().get(userId='me', id=msg['id'],
                                                 format=None, metadataHeaders=None).execute()
            payload = txt['payload']
            headers = payload['headers']
            sender = extract_sender(headers)
            if re.search("^Domo", sender):
                parts = payload.get('parts')
                if parts is not None:
                    parts = parts[0]
                    data = parts['body']['data']
                    decoded_data = decode_base64_data(data)
                    print(decoded_data)

    except HttpError as error:
        handle_api_error(error)

def get_credentials():
    creds = None
    token_file = 'token.json'

    if os.path.exists(token_file):
        creds = Credentials.from_authorized_user_file(token_file, SCOPES)

    if not creds or not creds.valid:
        creds = refresh_credentials(creds, token_file)

    save_credentials(creds, token_file)
    return creds

def refresh_credentials(creds, token_file):
    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)
    return creds

def save_credentials(creds, token_file):
    with open(token_file, 'w') as token:
        token.write(creds.to_json())

def extract_sender(headers):
    for header in headers:
        if header['name'] == 'From':
            return header['value']
    return ''

def decode_base64_data(data):
    data = data.replace("-", "+").replace("_", "/")
    decoded_data = base64.b64decode(data)
    return decoded_data

def handle_api_error(error):
    # TODO(developer) - 处理来自 Gmail API 的错误。
    print(f'An error occurred: {error}')

if __name__ == '__main__':
    main()

如果您有其他需要,请随时告诉我。

英文:

I need to decode email body so it is in human readable text. I have written a function decode_data() that is supposed to ideally decode the message in the email body. However, this doesn't seem to work as I would want it to.
Here's my code

from __future__ import print_function
import os.path
import re
import base64
import email
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']
def main():
"""Shows basic usage of the Gmail API.
Lists the user's Gmail labels.
"""
creds = get_credentials()
try:
# Call the Gmail API
service = build('gmail', 'v1', credentials=creds)
messages_list = service.users().messages().list(userId='me', labelIds=None, q=None,
pageToken=None, maxResults=None, includeSpamTrash=None).execute().get('messages')
for msg in messages_list:
txt = service.users().messages().get(userId='me', id=msg['id'],
format=None, metadataHeaders=None).execute()
payload = txt['payload']
headers = payload['headers']
sender = extract_sender(headers)
if re.search("^Domo", sender):
parts = payload.get('parts')
if parts is not None:
parts = parts[0]
data = parts['body']['data']
decoded_data = decode_base64_data(data)
print(decoded_data)
except HttpError as error:
handle_api_error(error)
def get_credentials():
creds = None
token_file = 'token.json'
if os.path.exists(token_file):
creds = Credentials.from_authorized_user_file(token_file, SCOPES)
if not creds or not creds.valid:
creds = refresh_credentials(creds, token_file)
save_credentials(creds, token_file)
return creds
def refresh_credentials(creds, token_file):
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)
return creds
def save_credentials(creds, token_file):
with open(token_file, 'w') as token:
token.write(creds.to_json())
def extract_sender(headers):
for header in headers:
if header['name'] == 'From':
return header['value']
return ''
def decode_base64_data(data):
data = data.replace("-", "+").replace("_", "/")
decoded_data = base64.b64decode(data)
return decoded_data
def handle_api_error(error):
# TODO(developer) - Handle errors from Gmail API.
print(f'An error occurred: {error}')
if __name__ == '__main__':
main()

I need help with decoding the body so that instead of getting a result similar to this
Python GMAIL API 读取完整邮件正文

the code returns just the text needed in a human readable form

答案1

得分: 1

我测试了你的脚本,并在代码的这一部分做了轻微的更改:

if parts is not None:
    parts = parts[0]
    data = parts['body']['data']
    decoded_data = decode_base64_data(data)
    print(decoded_data)

我将其更改为:

if parts is not None:
    parts = parts[0]
    data = parts['body']['data']
    #decoded_data = decode_base64_data(data)
    decoded_data = base64.urlsafe_b64decode(data).decode('UTF8')
    print(decoded_data)
英文:

I tested your script and I made it work with this slight change in this part of the code:

if parts is not None:
parts = parts[0]
data = parts['body']['data']
decoded_data = decode_base64_data(data)
print(decoded_data)

I changed it to:

if parts is not None:
parts = parts[0]
data = parts['body']['data']
#decoded_data = decode_base64_data(data)
decoded_data = base64.urlsafe_b64decode(data).decode('UTF8')
print(decoded_data)

huangapple
  • 本文由 发表于 2023年5月24日 18:45:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76322669.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定