【问题标题】:googleapiclient returns Bad Request error when trying to send email through Gmailgoogleapiclient 尝试通过 Gmail 发送电子邮件时返回错误请求错误
【发布时间】:2020-04-20 22:42:38
【问题描述】:

当我的 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 文档的步骤。我想我已经正确设置了所有访问和权限。我错过了什么以及为什么会出错?

非常感谢任何帮助。

【问题讨论】:

    标签: google-api gmail


    【解决方案1】:

    原来问题出在上面的 self.EMAIL_FROM 上。这需要设置为具有正确权限集的用户才能发送电子邮件。这首先解决了我的问题。但是,我不清楚我需要为要用于委派的用户设置哪些权限。目前它似乎只适用于管理员电子邮件。

    如果有人对此有一定的了解,请回复。

    【讨论】:

    • 在我的案例中已经设置了域范围的委派,这是可行的。我在我的代码中使用了别名电子邮件,但这不起作用。如果你使用原版,它可以工作。
    猜你喜欢
    • 2015-12-12
    • 1970-01-01
    • 2018-08-13
    • 1970-01-01
    • 1970-01-01
    • 2019-05-06
    • 1970-01-01
    • 2016-06-03
    • 2020-01-12
    相关资源
    最近更新 更多