我尝试使用python中的Gmail API发送电子邮件。我想我遵循了相关文档和youtube vids。
我遇到了这个错误:
googleapiclient.errors.HttpError: HttpError 403 when requesting https://www.googleapis.com/gmail/v1/users/me/messages/send?alt=json returned "Insufficient Permission"
这是我的剧本:
#!/usr/bin/env python from googleapiclient.discovery import build from httplib2 import Http from oauth2client import file, client, tools from email.mime.text import MIMEText import base64 import errors SCOPES = 'https://mail.google.com/' CLIENT_SECRET = 'client_secret.json' store = file.Storage('storage.json') credz = store.get() if not credz or credz.invalid: flags = tools.argparser.parse_args(args=[]) flow = client.flow_from_clientsecrets(CLIENT_SECRET, SCOPES) credz = tools.run_flow(flow, store, flags) GMAIL = build('gmail', 'v1', http=credz.authorize(Http())) 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 base64url encoded email object. """ message = MIMEText(message_text) message['to'] = to message['from'] = sender message['subject'] = subject return {'raw': base64.urlsafe_b64encode(message.as_string())} 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 message = CreateMessage('testemail@gmail.com', 'testemail@gmail.com', 'test_subject', 'foo') print message SendMessage(GMAIL, 'me', message)
我尝试添加范围,尝试不同的电子邮件等。我也通过登录我的浏览器进行了身份验证。 (testemail@gmail.com是虚拟电子邮件btw)
答案 0 :(得分:2)
尝试删除生成的storage.json文件,然后重新尝试。
您可能正在尝试使用不同范围的此脚本,因此" storage.json"可能有错误的细节。
答案 1 :(得分:0)
我遇到了同样的问题。
我通过再次运行提供谷歌的quickstart.py
并更改SCOPE
来解决这个问题,以便谷歌可以为您提供所需的所有权限。在此之后,您不需要在新代码上SCOPE
或CLIENT_SECRET
发送消息,只需get_credentials()
,CreateMessage()
和SendMessage()
方法。