[docs]defget_gmail_credentials(token_file:Optional[str]=None,client_secrets_file:Optional[str]=None,scopes:Optional[List[str]]=None,)->Credentials:"""Get credentials."""# From https://developers.google.com/gmail/api/quickstart/pythonRequest,Credentials=import_google()InstalledAppFlow=import_installed_app_flow()creds=Nonescopes=scopesorDEFAULT_SCOPEStoken_file=token_fileorDEFAULT_CREDS_TOKEN_FILEclient_secrets_file=client_secrets_fileorDEFAULT_CLIENT_SECRETS_FILE# The file token.json stores the user's access and refresh tokens, and is# created automatically when the authorization flow completes for the first# time.ifos.path.exists(token_file):creds=Credentials.from_authorized_user_file(token_file,scopes)# If there are no (valid) credentials available, let the user log in.ifnotcredsornotcreds.valid:ifcredsandcreds.expiredandcreds.refresh_token:creds.refresh(Request())# type: ignore[call-arg]else:# https://developers.google.com/gmail/api/quickstart/python#authorize_credentials_for_a_desktop_application # noqaflow=InstalledAppFlow.from_client_secrets_file(client_secrets_file,scopes)creds=flow.run_local_server(port=0,open_browser=False)# Save the credentials for the next runwithopen(token_file,"w")astoken:token.write(creds.to_json())returncreds
[docs]defbuild_resource_service(credentials:Optional[Credentials]=None,service_name:str="gmail",service_version:str="v1",)->Resource:"""Build a Gmail service."""credentials=credentialsorget_gmail_credentials()builder=import_googleapiclient_resource_builder()returnbuilder(service_name,service_version,credentials=credentials)
[docs]defclean_email_body(body:str)->str:"""Clean email body."""try:frombs4importBeautifulSouptry:soup=BeautifulSoup(str(body),"html.parser")body=soup.get_text()returnstr(body)exceptExceptionase:logger.error(e)returnstr(body)exceptImportError:logger.warning("BeautifulSoup not installed. Skipping cleaning.")returnstr(body)