我如何解决HttpError 403不足的权限? (gmail api,python)

时间:2015-08-21 14:38:03

标签: python api gmail

执行代码时,我一直收到以下错误:

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

这是我的代码:

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)

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

6 个答案:

答案 0 :(得分:14)

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

当您授权gmail服务客户端时,您可以指定几个不同的范围:All,compose,labels等...

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

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

答案 1 :(得分:10)

通过将SCOPES行更改为:

来解决此问题
SCOPES = 'https://mail.google.com/'

电子邮件发送完美无缺

答案 2 :(得分:9)

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

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

范围取自here

答案 3 :(得分:8)

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

答案 4 :(得分:2)

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

答案 5 :(得分:1)

除了以下答案:

  1. CCY
  2. Apadana酒店
  3. ragnampiza
  4. 并且作为ccy答案的推动......

    解决方案1 ​​......

    ......修复

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

    1. CLIENT_SECRET_FILE = '/path/to/your/secret_client.json'
    2. 强制get_credentials()使用失败的凭据逻辑路径...
    3. 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)

      强制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)

      这是一个hacky修复,但会在短时间内让你上手。

      问题......

      • 这种方法的问题在于它强制flow代码,这会打开身份验证窗口浏览器,并要求最终用户在发送电子邮件之前接受安全协议。
      • 这显然打破了自动电子邮件生成和发送的概念。

      解决方案2 ......

      ......一个稳定,更自动化的解决方案

      我发现做以下工作:

      1. 将下载的secret-client-####.html.json文件复制到get_credentials()方法中第一个代码块中定义的目录。基本上,将其复制到您的user/.credentials目录
      2. 删除当前的gmail-python-quickstart.json
      3. 将下载的文件重命名为gmail-python-quickstart.json
      4. 运行您的代码,然后它应该可以正常工作。

        优势...

        • 身份验证页面未显示
        • 电子邮件自动发送