执行代码时,我一直收到以下错误:
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。有谁知道我需要做什么才能克服这个错误?我这是一个完全的菜鸟所以请原谅我,如果我对此有点不高兴。谢谢!
答案 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)
要发送电子邮件,需要 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)
除了以下答案:
并且作为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
操作起作用:
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
运行您的代码,然后它应该可以正常工作。