Search code examples
gmaillabelgmail-api

Gmail API - How to relabel emails as spam using Filters?


I am attempting to write a bot which searches for an email by a keyword, then creates a filter sending all future emails from that sender to spam. Here is my code:

async def remove_subscription(service, from_email, message):
    # labels =  service.users().labels().list(userId='me').execute().get('labels', [])
    # for label in labels:
    #     print(label['id'])
    filter_content = {
        'criteria': {
            'from': from_email
        },
        'action': {
            'addLabelIds': ['SPAM'],
            'removeLabelIds': ['INBOX']
        }
    }

    try:
        result = service.users().settings().filters().create(
            userId='me', body=filter_content).execute()
        print(F'Created filter with id: {result.get("id")}')

        return True

    except:
        print('An error occurred')
        await message.channel.send('An error occurred.')
        return False

As you can see, it is pretty much the given code from the google docs: https://developers.google.com/gmail/api/guides/filter_settings?hl=en

The api won't allow me to use addLabelIds: ['SPAM'], and it does not work while attempting to do the same query on the gmail docs in-webpage testing (So I know it isnt an issue with the rest of my code). Here is the error:

raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://gmail.googleapis.com/gmail/v1/users/me/settings/filters?alt=json returned "Invalid label SPAM in AddLabelIds". Details: "[{'message': 'Invalid label SPAM in AddLabelIds', 'domain': 'global', 'reason': 'invalidArgument'}]">

I can't seem to find an explanation anywhere which states that I can't add SPAM as a label ID. I confirmed with lines 2-4 that the label ID is indeed 'SPAM".

Is this just not allowed by the api? How could I create a filter which sends all emails from a specific sender to spam?

Thanks ahead of time.


Solution

  • Issue:

    I don't think Gmail allows messages to be sent to SPAM via filters. This is true not just for the API, but for the user-interface too:

    enter image description here

    If you'd like this feature to be added to Gmail, I'd suggest requesting it via Send feedback on the user-interface. Nevertheless, it's likely that this is a deliberate limitation. In any case, you could use a custom label to act as SPAM.

    Related: