如何解决 HttpError 403 Insufficient Permission?(gmail api,python)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32143126/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:05:38  来源:igfitidea点击:

How do I get around HttpError 403 Insufficient Permission? (gmail api, python)

pythonapigmail

提问by semiflex

I keep getting the following error when I execute my code:

当我执行我的代码时,我不断收到以下错误:

An error occurred: <HttpError 403 when requesting https://www.googleapis.com/gmail/v1/users/me/messages/send?alt=json returned "Insufficient Permission">

This is my code:

这是我的代码:

import httplib2
import os
from httplib2 import Http

from apiclient import discovery
import oauth2client
from oauth2client import client
from oauth2client import tools

try:
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

#SCOPES = 'https://www.googleapis.com/'
SCOPES = 'https://www.googleapis.com/auth/gmail.compose'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Gmail API Quickstart'

def get_credentials():
    """Gets valid user credentials from storage.

    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.

    Returns:
        Credentials, the obtained credential.
    """
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,
                                   'gmail-quickstart.json')

    store = oauth2client.file.Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else: # Needed only for compatability with Python 2.6
            credentials = tools.run(flow, store)
        print 'Storing credentials to ' + credential_path
    return credentials

def CreateMessage(sender, to, subject, message_text):
  """Create a message for an email.

  Args:
    sender: Email address of the sender.
    to: Email address of the receiver.
    subject: The subject of the email message.
    message_text: The text of the email message.

  Returns:
    An object containing a base64 encoded email object.
  """
  message = MIMEText(message_text)
  message['to'] = to
  message['from'] = sender
  message['subject'] = subject
  return {'raw': base64.b64encode(message.as_string())}

testMessage = CreateMessage('ENTER SENDERS EMAIL ADDRESS', 'ENTER RECEIVERRS EMAIL ADDRESS', 'ENTER SUBJECT', 'ENTER EMAIL BODY')

def SendMessage(service, user_id, message):
  """Send an email message.

  Args:
    service: Authorized Gmail API service instance.
    user_id: User's email address. The special value "me"
    can be used to indicate the authenticated user.
    message: Message to be sent.

  Returns:
    Sent Message.
  """
  try:
    message = (service.users().messages().send(userId=user_id, body=message)
               .execute())
    print 'Message Id: %s' % message['id']
    return message
  except errors.HttpError, error:
    print 'An error occurred: %s' % error


testSend = SendMessage(service, 'me', testMessage)

I keep reading that I need to edit a credentials file, but I can't seem to find it. I have windows 7 installed. Does anyone know what I need to do in order to get past this error? I'm a total noob at this so please excuse me if I seem a bit nooby about this. Thanks!

我一直在读我需要编辑凭证文件,但我似乎找不到它。我安装了Windows 7。有谁知道我需要做什么才能克服这个错误?我在这方面完全是个菜鸟,所以如果我对此有点笨手笨脚,请原谅我。谢谢!

采纳答案by Olshansk

Even though the accepted answer is 100% correct. I think it's worth pointing out that why that's the case.

即使接受的答案是 100% 正确的。我认为值得指出为什么会这样。

When you authorize a gmail service client, you can specify several different scopes: All, compose, labels, etc...

当您授权 Gmail 服务客户端时,您可以指定几个不同的范围:全部、撰写、标签等...

These are all listed here: https://developers.google.com/gmail/api/auth/scopes

这些都在这里列出:https: //developers.google.com/gmail/api/auth/scopes

The scope mentioned in the answer provides complete gmail access.

答案中提到的范围提供了完整的 gmail 访问权限。

回答by semiflex

Solved it by changing the SCOPES line to:

通过将 SCOPES 行更改为:

SCOPES = 'https://mail.google.com/'

Email sending works perfectly

电子邮件发送完美

回答by apadana

Gmail API has these scopes: gmail api scopes

Gmail API 具有以下范围: gmail api 范围

For sending emails, https://www.googleapis.com/auth/gmail.sendis needed or full access https://mail.google.com/.

要发送电子邮件,需要https://www.googleapis.com/auth/gmail.send或完全访问https://mail.google.com/

The scopes taken from here.

这里获取的范围。

回答by ccy

If you run the official "gmail-python-quickstart" before, please delete the file "gmail-quickstart.json" in your system. Rerun your program again so that you can set the priviledge as you want.

如果您之前运行过官方的“ gmail-python-quickstart”,请删除系统中的“gmail-quickstart.json”文件。再次重新运行您的程序,以便您可以根据需要设置权限。

回答by Andrew

In Addition to the answers from:

除了来自以下方面的答案:

  1. ccy
  2. apadana
  3. ragnampiza
  1. ccy
  2. 阿帕达纳
  3. 拉格南皮萨

and as a furtherance of ccy's answer...

并作为 ccy 答案的进一步...



Solution 1...

解决方案一...

... a hack fix

...一个黑客修复

If you're using the original gmail-python-quickstartcode, make sure to also update the following:

如果您使用的是原始gmail-python-quickstart代码,请确保同时更新以下内容:

  1. CLIENT_SECRET_FILE = '/path/to/your/secret_client.json'
  2. Force get_credentials()to use the failed credentials logic path...
  1. CLIENT_SECRET_FILE = '/path/to/your/secret_client.json'
  2. 强制get_credentials()使用失败的凭据逻辑路径...
if True:
    flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
    flow.user_agent = APPLICATION_NAME
    if flags:
        credentials = tools.run_flow(flow, store, flags)
    else: # Needed only for compatibility with Python 2.6
        credentials = tools.run(flow, store)
    print('Storing credentials to ' + credential_path)

to force Trueso that the logic operation will definitely work the client.flowoperations:

强制True使逻辑操作肯定会执行client.flow操作:

if True:
    flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
    flow.user_agent = APPLICATION_NAME
    if flags:
        credentials = tools.run_flow(flow, store, flags)
    else: # Needed only for compatibility with Python 2.6
        credentials = tools.run(flow, store)
    print('Storing credentials to ' + credential_path)

This is a hacky fix, but will get you up and going in short time.

这是一个 hacky 修复,但可以让你在短时间内开始工作。

The Problem...

问题...

  • The problem with this approach is that it forces the flowcode, which opens up the authentication window browser and requires that the end user accept the security protocol before sending the email.
  • This obviously breaks the concept of automated email generation and sending.
  • 这种方法的问题在于它强制flow代码,这会打开身份验证窗口浏览器并要求最终用户在发送电子邮件之前接受安全协议。
  • 这显然打破了自动生成和发送电子邮件的概念。


Solution 2...

解决方案2...

...a stable, more automated solution

...稳定、自动化程度更高的解决方案

I found that doing the following works:

我发现做以下工作:

  1. Copy the downloaded the secret-client-####.html.jsonfile to the directory defined in the first block of code from the get_credentials()method. Basically, copy it to your user/.credentialsdirectory
  2. Delete the current gmail-python-quickstart.json
  3. Rename your downloaded file to gmail-python-quickstart.json
  1. 将下载的secret-client-####.html.json文件复制到get_credentials()方法的第一个代码块中定义的目录。基本上,将其复制到您的user/.credentials目录
  2. 删除当前 gmail-python-quickstart.json
  3. 将下载的文件重命名为 gmail-python-quickstart.json

Run your code, and then it should work fine.

运行您的代码,然后它应该可以正常工作。

Benefits...

好处...

  • The authentication page does not show up
  • The email is sent automatically
  • 认证页面不显示
  • 电子邮件是自动发送的

回答by Iman Mirzadeh

If you used google's official example, there should be a folder in ~/.credentials/directory which is old, remove everything inside that directory and re-run your code. then you have to add new permissions and then everything is OK!

如果您使用 google 的官方示例,则~/.credentials/目录中应该有一个旧的文件夹,删除该目录中的所有内容并重新运行您的代码。然后您必须添加新权限,然后一切正常!