Part 1 - Start Script, import function from extenal script
01
pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
https://mail.google.com/
Do this with tstudystuff instead, review getting started 01-gettingStarted and codeTops - getting start
02
This is my simplified create_service script
import os.path
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
def create_service(client_secret,api_name,api_version,*scopes):
CLIENT_SECRET = client_secret
API_NAME = api_name
API_VERSION = api_version
SCOPES = [scope for scope in scopes[0]]
creds = None
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json',SCOPES)
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.json','w') as token:
token.write(creds.to_json())
try:
service = build(API_NAME,API_VERSION,credentials=creds)
return service
except HttpError as e:
print('error', e)
Part 2 - Search for the emails
01
Use the following function to search for the emails, review codeTops 01-getStart - part 7 and 8 for better understanding
Labels allows us to search for things such as 'Subject'
or 'Sender' / 'from'
This tutorial is sloppy, chat gpt provided the code below which
def search_emails(query,Labels=None):
next_page_token = None
email_messages = []
while True:
message_response = service.users().messages().list(
userId='me',
labelIds=Labels,
includeSpamTrash=False,
q=query,
maxResults=500,
pageToken=next_page_token
).execute()
email_messages.extend(message_response.get('messages', []))
next_page_token = message_response.get('nextPageToken')
if not next_page_token:
break
return email_messages
02
Now insert the query, subject: delete this and labels.
This will return the two emails seen in the pictures above "delete this 1 and delete this 2" and their key value pairs including the ids
from google_service import create_service
CLIENT_SECRET = 'credentials.json'
API_NAME = 'gmail'
API_VERSION = 'v1'
SCOPES = ['https://mail.google.com/']
service = create_service(CLIENT_SECRET,API_NAME,API_VERSION,SCOPES)
def search_email(query, Labels=None):
next_page_token = None
email_messages = []
while True:
message_response = service.users().messages().list(
userId='me',
labelIds=Labels,
includeSpamTrash=False,
q=query,
maxResults=500,
pageToken=next_page_token
).execute()
email_messages.extend(message_response.get('messages', []))
next_page_token = message_response.get('nextPageToken')
if not next_page_token:
break
return email_messages
query_string = 'subject:delete this'
email_results = search_email(query_string)
print(email_results)
03
To delete the email, loop through the results and use the id
value.
query_string = 'subject: delete this'
email_results = search_email(query_string)
for email in email_results:
service.users().messages().trash(
userId='me',
id=email['id']
).execute()
Part 3 - Full code - scrips
Here is the full code for each script
pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
https://mail.google.com/
from google_service import create_service
CLIENT_SECRET = 'credentials.json'
API_NAME = 'gmail'
API_VERSION = 'v1'
SCOPES = ['https://mail.google.com/']
service = create_service(CLIENT_SECRET,API_NAME,API_VERSION,SCOPES)
def search_email(query, Labels=None):
next_page_token = None
email_messages = []
while True:
message_response = service.users().messages().list(
userId='me',
labelIds=Labels,
includeSpamTrash=False,
q=query,
maxResults=500,
pageToken=next_page_token
).execute()
email_messages.extend(message_response.get('messages', []))
next_page_token = message_response.get('nextPageToken')
if not next_page_token:
break
return email_messages
query_string = 'subject:delete this'
email_results = search_email(query_string)
for email in email_results:
service.users().messages().trash(
userId='me',
id=email['id']
).execute()
import os.path
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
def create_service(client_secret,api_name,api_version,*scopes):
CLIENT_SECRET = client_secret
API_NAME = api_name
API_VERSION = api_version
SCOPES = [scope for scope in scopes[0]]
creds = None
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json',SCOPES)
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.json','w') as token:
token.write(creds.to_json())
try:
service = build(API_NAME,API_VERSION,credentials=creds)
return service
except HttpError as e:
print('error', e)