尝试使用 python 脚本向 Gmail 添加过滤器时出错

问题描述 投票:0回答:1

我正在尝试创建一个简单的Python应用程序,它能够删除Gmail过滤器和向Gmail添加过滤器。使用不同的范围,我可以轻松列出标签、过滤器等,但在尝试添加新过滤器时出现错误。

下面的代码是我的实际代码的简化(分为一组函数),但基本上,它的功能与我的完整代码完全相同。

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

def main():
    scope = ['https://www.googleapis.com/auth/gmail.settings.basic']
    credentials_file = 'credentials.json'
    token_file = f'token_test.json'

    credentials = None
    if os.path.exists(token_file):
        credentials = Credentials.from_authorized_user_file(token_file, scope)
    if not credentials or not credentials.valid:
        if credentials and credentials.expired and credentials.refresh_token:
            credentials.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(credentials_file, scope)
            credentials = flow.run_local_server(port=0)
        with open(token_file, 'w') as token:
            token.write(credentials.to_json())

    service = build('gmail', 'v1', credentials=credentials)
    filter_body = {'criteria': {'from': '[email protected]'}, 'action': {'removeLabelsIds': ['SPAM']}}
    result = (
        service.users()
        .settings()
        .filters()
        .create(userId='me', body=filter_body)
        .execute())

    return result

if __name__ == '__main__':
    main()

我收到此错误

Traceback (most recent call last):
  File "C:\DATA\WORK\Assets\Development\Python\GmailManager\src\temp.py", line 36, in <module>
    main()
  File "C:\DATA\WORK\Assets\Development\Python\GmailManager\src\temp.py", line 31, in main
    .execute())
     ^^^^^^^^^
  File "C:\DATA\WORK\Assets\Development\Python\GmailManager\.venv\Lib\site-packages\googleapiclient\_helpers.py", line 130, in positional_wrapper
    return wrapped(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\DATA\WORK\Assets\Development\Python\GmailManager\.venv\Lib\site-packages\googleapiclient\http.py", line 938, in execute
    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 "Filter doesn't have any actions". Details: "[{'message': "Filter doesn't have any actions", 'domain': 'global', 'reason': 'invalidArgument'}]">

链接下的信息 https://gmail.googleapis.com/gmail/v1/users/me/settings/filters?alt=json 是这个吗

{
    "error": {
        "code": 401,
        "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
        "errors": [
            {
                "message": "Login Required.",
                "domain": "global",
                "reason": "required",
                "location": "Authorization",
                "locationType": "header"
            }
        ],
        "status": "UNAUTHENTICATED",
        "details": [
            {
                "@type": "type.googleapis.com/google.rpc.ErrorInfo",
                "reason": "CREDENTIALS_MISSING",
                "domain": "googleapis.com",
                "metadata": {
                    "method": "caribou.api.proto.MailboxService.ListFilters",
                    "service": "gmail.googleapis.com"
                }
            }
        ]
    }
}

这很奇怪,因为现在我不知道错误是否源于过滤器的内容或身份验证错误。

python gmail-api
1个回答
0
投票

请按如下方式修改您的脚本。

来自:

filter_body = {'criteria': {'from': '[email protected]'}, 'action': {'removeLabelsIds': ['SPAM']}}

致:

filter_body = {'criteria': {'from': '[email protected]'}, 'action': {'removeLabelIds': ['SPAM']}}
  • 在此修改中,
    Labels
    removeLabelsIds
    被修改为
    Label
    ,如
    removeLabelIds

参考:

© www.soinside.com 2019 - 2024. All rights reserved.