虽然我从互联网上得到了一段允许我授权用户的代码,但我不知道如何使用授权时保存的会话来读取gmail;我附上了下面的代码
import os
import pathlib
import requests
from flask import Flask, session, abort, redirect, request, render_template
from google.oauth2 import id_token
from google_auth_oauthlib.flow import Flow
from pip._vendor import cachecontrol
import google.auth.transport.requests
from googleapiclient.discovery import build
app = Flask("Google Login App")
app.secret_key = "msassignment"
os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"
GOOGLE_CLIENT_ID = "xxxxxxxx"
client_secrets_file = os.path.join(pathlib.Path(__file__).parent, "client_secret.json")
flow = Flow.from_client_secrets_file(
client_secrets_file=client_secrets_file,
scopes=[ "https://www.googleapis.com/auth/userinfo.profile",
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/gmail.modify",
"https://www.googleapis.com/auth/gmail.readonly",
"openid"
],
redirect_uri="http://127.0.0.1:5000/callback"
)
def login_is_required(function):
def wrapper(*args, **kwargs):
if "google_id" not in session:
return abort(401) # Authorization required
else:
return function()
return wrapper
@app.route("/login")
def login():
authorization_url, state = flow.authorization_url()
session["state"] = state
return redirect(authorization_url)
@app.route("/callback")
def callback():
flow.fetch_token(authorization_response=request.url)
if not session["state"] == request.args["state"]:
abort(500) # State does not match!
credentials = flow.credentials
request_session = requests.session()
cached_session = cachecontrol.CacheControl(request_session)
token_request = google.auth.transport.requests.Request(session=cached_session)
id_info = id_token.verify_oauth2_token(
id_token=credentials._id_token,
request=token_request,
audience=GOOGLE_CLIENT_ID
)
session["google_id"] = id_info.get("sub")
session["name"] = id_info.get("name")
return redirect("/protected_area")
@app.route("/logout")
def logout():
session.clear()
return redirect("/")
@app.route("/")
def index():
return render_template("index.html")
@app.route("/protected_area")
@login_is_required
def protected_area():
return f"{session['name']}! <br/> <a href='/logout'><button>BYE</button></a>"
if __name__ == "__main__":
app.run(debug=True)
流程将是这样的,我想开发一个网络应用程序来读取 gmail 并使用自然语言处理对其进行总结。期待想法
我尝试更新作用域、回调和定义函数;
def get_unread_emails(credentials):
service = build('gmail', 'v1', credentials=credentials)
results = service.users().messages().list(userId='me', q='is:unread').execute()
messages = results.get('messages', [])
return messages
但对我来说没有任何作用
尝试这个版本,注意我如何使用列表消息,然后获取每条消息。还有
format='raw'
def ListMessages(credentials):
try:
# create a gmail service object
service = build('gmail', 'v1', credentials=credentials)
# Call the Gmail v1 API
results = service.users().messages().list(userId='me').execute()
messages = results.get('messages', [])
if not messages:
print('No messages where found.')
return
print('Messages:')
for message in messages:
getMessage(credentials, message['id'])
except HttpError as error:
# TODO(developer) - Handle errors from gmail API.
print(f'An error occurred: {error}')
def getMessage(credentials, message_id):
# get a message
try:
service = build('gmail', 'v1', credentials=credentials)
# Call the Gmail v1 API, retrieve message data.
message = service.users().messages().get(userId='me', id=message_id, format='raw').execute()
# Parse the raw message.
mime_msg = email.message_from_bytes(base64.urlsafe_b64decode(message['raw']))
print(mime_msg['from'])
print(mime_msg['to'])
print(mime_msg['subject'])
print("----------------------------------------------------")
# Find full message body
message_main_type = mime_msg.get_content_maintype()
if message_main_type == 'multipart':
for part in mime_msg.get_payload():
if part.get_content_maintype() == 'text':
print(part.get_payload())
elif message_main_type == 'text':
print(mime_msg.get_payload())
print("----------------------------------------------------")
# Message snippet only.
# print('Message snippet: %s' % message['snippet'])
except HttpError as error:
# TODO(developer) - Handle errors from gmail API.
print(f'A message get error occurred: {error}')