尝试通过Gmail发送电子邮件时,googleapiclient返回错误请求错误

时间:2020-04-20 22:42:38

标签: google-api gmail

当我的python代码尝试发送简单的测试电子邮件时,出现以下错误。

googleapiclient.errors.HttpError: <HttpError 400 when requesting https://www.googleapis.com/gmail/v1/users/me/messages/send?alt=json returned "Bad Request">

我的代码如下:

      scope = ['https://www.googleapis.com/auth/gmail.send']
      path = <path to my serice account key in json format>
      self.credentials = ServiceAccountCredentials.from_json_keyfile_name(
          path + <service account key>, scope )
      self.EMAIL_FROM = self.credentials.service_account_email
      self.delegated_credentials = self.credentials.create_delegated(self.EMAIL_FROM)
      self.service = build('gmail', 'v1', credentials=self.delegated_credentials)

   def send( self, to, subject, body ):
      message = MIMEText(body)
      message['to'] = to
      message['from'] = <valid email account>
      message['subject'] = subject
      message = {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode()}

      try:
         message = (self.service.users().messages().send(userId=<valid email account>, body=message)
                    .execute())
         print('Message Id: %s' % message['id'])
         return message
      except errors.HttpError as error:
         print('An error occurred: %s' % error)

我严格按照https://medium.com/lyfepedia/sending-emails-with-gmail-api-and-python-49474e32c81f和现有Gmail API文档的步骤进行操作。我想我已经正确设置了所有访问和权限。我缺少什么,为什么会出错?

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

事实证明,问题出在上述self.EMAIL_FROM上。这需要设置为具有正确权限集的用户才能发送电子邮件。首先解决了我的问题。但是,对于我来说,尚不清楚我需要为用户设置哪些权限才能用于委派。目前看来,它仅适用于管理员电子邮件。

如果有人对此有明确的了解,请回复。

相关问题