python - Gmail API : "Invalid Label" When Trying to Set Message Label to One That I Created

标签 python gmail-api

我通过典型方法在 Gmail 的网络界面中创建了一个标签“handler_gmail”。

当我尝试通过 Gmail API(Python 客户端库)为邮件设置该标签时,我收到响应 HttpError 400,返回“无效标签:handler_gmail”。

我确定该标签存在(我检查了多次 – 没有拼写错误)。

我试着这样设置:

gs.users().messages().modify(userId=用户名, id=m['id'], body={"addLabelIds": ['handler_gmail']}).execute()

我尝试将 "removeLabelIds": [] 键/值对添加到字典中(认为这可能是必需的),但出现了相同的“无效标签”错误。

非常感谢任何帮助!非常接近能够完成我需要完成的项目!

最佳答案

正如其他人所指出的,您必须使用标签 ID,而不是标签名称。我通过使用 gmail API 的 sample code 解决了这个问题并修改它以打印出除名称之外的 ID:

results = service.users().labels().list(userId='me').execute()
labels = results.get('labels', [])

if not labels:
    print('No labels found.')
else:
  print('Labels:')
  for label in labels:
    print(label['name']+ " "+label['id'])

所以一旦你得到相应的id,你的代码应该是这样的:

gs.users().messages().modify(userId=username, id=m['id'], body={"addLabelIds":     
['Label_1']}).execute()

关于python - Gmail API : "Invalid Label" When Trying to Set Message Label to One That I Created,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26963868/

相关文章:

python - 如何在硬超时时重试 celery 任务?

python - 将 Excel 中的多个工作表附加到 pandas 数据框中 - 排序问题

python - Scipy 作为对 travis-ci 的依赖并且没有名为 _csr 的模块

python - 从 C(++) 访问 python 数据

gmail-api - GMail API - 我可以使用服务帐户发送电子邮件吗?

python - 从命名元组基类继承

go - Gmail API : Trashing first email seems to remove entire thread

oauth-2.0 - Gmail API 返回 403 错误代码和 "Delegation denied for <user email>"

google-apps-script - 在 Gmail 插件中使用 UrlFetchApp 的权限错误

api - 在 gmail api 中搜索特定的回复 header