I’m working on a Python application to manage Gmail filters and running into issues when trying to create new filters. I can successfully read existing filters and labels, but creating new ones throws an error.
import os
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
def setup_gmail_filter():
scopes = ['https://www.googleapis.com/auth/gmail.settings.basic']
creds_path = 'client_credentials.json'
token_path = 'gmail_token.json'
creds = None
if os.path.exists(token_path):
creds = Credentials.from_authorized_user_file(token_path, scopes)
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
auth_flow = InstalledAppFlow.from_client_secrets_file(creds_path, scopes)
creds = auth_flow.run_local_server(port=0)
with open(token_path, 'w') as f:
f.write(creds.to_json())
gmail_service = build('gmail', 'v1', credentials=creds)
new_filter = {
'criteria': {'from': '[email protected]'},
'action': {'removeLabelIds': ['SPAM']}
}
response = (
gmail_service.users()
.settings()
.filters()
.create(userId='me', body=new_filter)
.execute()
)
return response
if __name__ == '__main__':
setup_gmail_filter()
The error message says “Filter doesn’t have any actions” even though I’m specifying an action. Has anyone encountered this before? What’s the correct way to structure the filter action?