执行代码时不断收到以下错误:
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”文件。再次重新运行您的程序,以便您可以根据需要设置权限。
如果您使用谷歌的官方示例,
~/.credentials/
目录中应该有一个旧文件夹,删除该目录中的所有内容并重新运行您的代码。然后你必须添加新的权限,然后一切就OK了!
除了以下答案:
并作为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
运行你的代码,然后它应该可以正常工作。
只是想说,我必须将credentials.json复制到另一个文件,删除credentials.json,重新粘贴到新的credentials.json,然后重新运行应用程序才能使其正常工作。我在互联网上搜索了几个小时,因为删除 token.json 对我来说不起作用。对于那些在同一条船上的人来说,这似乎对我有用。