如何解决 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
How do I get around HttpError 403 Insufficient Permission? (gmail api, python)
提问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
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:
除了来自以下方面的答案:
- ccy
- apadana
- ragnampiza
- ccy
- 阿帕达纳
- 拉格南皮萨
and as a furtherance of ccy's answer...
并作为 ccy 答案的进一步...
Solution 1...
解决方案一...
... a hack fix
...一个黑客修复
If you're using the original gmail-python-quickstart
code, make sure to also update the following:
如果您使用的是原始gmail-python-quickstart
代码,请确保同时更新以下内容:
- CLIENT_SECRET_FILE =
'/path/to/your/secret_client.json'
- Force
get_credentials()
to use the failed credentials logic path...
- CLIENT_SECRET_FILE =
'/path/to/your/secret_client.json'
- 强制
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 True
so that the logic operation will definitely work the client.flow
operations:
强制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
flow
code, 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:
我发现做以下工作:
- Copy the downloaded the
secret-client-####.html.json
file to the directory defined in the first block of code from theget_credentials()
method. Basically, copy it to youruser/.credentials
directory - Delete the current
gmail-python-quickstart.json
- Rename your downloaded file to
gmail-python-quickstart.json
- 将下载的
secret-client-####.html.json
文件复制到get_credentials()
方法的第一个代码块中定义的目录。基本上,将其复制到您的user/.credentials
目录 - 删除当前
gmail-python-quickstart.json
- 将下载的文件重命名为
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/
目录中应该有一个旧的文件夹,删除该目录中的所有内容并重新运行您的代码。然后您必须添加新权限,然后一切正常!