[英]How do I get around HttpError 403 Insufficient Permission? (gmail api, python)
當我執行我的代碼時,我不斷收到以下錯誤:
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。 有誰知道我需要做什么才能克服這個錯誤? 我在這方面完全是個菜鳥,所以如果我對此有點笨手笨腳,請原諒我。 謝謝!
即使接受的答案是 100% 正確的。 我認為值得指出為什么會這樣。
當您授權 Gmail 服務客戶端時,您可以指定幾個不同的范圍:全部、撰寫、標簽等...
這些都在這里列出: https : //developers.google.com/gmail/api/auth/scopes
答案中提到的范圍提供了完整的 gmail 訪問權限。
通過將 SCOPES 行更改為:
SCOPES = 'https://mail.google.com/'
電子郵件發送完美
要發送電子郵件,需要https://www.googleapis.com/auth/gmail.send或完全訪問https://mail.google.com/ 。
從這里獲取的范圍。
如果您之前運行過官方的“ gmail-python-quickstart ”,請刪除系統中的“gmail-quickstart.json”文件。 再次重新運行您的程序,以便您可以根據需要設置權限。
除了來自以下方面的答案:
並作為 ccy 答案的進一步...
如果您使用的是原始gmail-python-quickstart
代碼,請確保同時更新以下內容:
'/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)
強制True
以便邏輯操作肯定會在client.flow
操作中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
代碼,這會打開身份驗證窗口瀏覽器並要求最終用戶在發送電子郵件之前接受安全協議。我發現做以下工作:
secret-client-####.html.json
文件復制到get_credentials()
方法的第一個代碼塊中定義的目錄。 基本上,將其復制到您的user/.credentials
目錄gmail-python-quickstart.json
gmail-python-quickstart.json
運行您的代碼,然后它應該可以正常工作。
如果您使用 google 的官方示例,則~/.credentials/
目錄中應該有一個舊的文件夾,刪除該目錄中的所有內容並重新運行您的代碼。 然后您必須添加新權限,然后一切正常!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.