【问题标题】:Why do I get an authentication error with SMTP?为什么使用 SMTP 时会出现身份验证错误?
【发布时间】:2020-01-09 00:39:46
【问题描述】:

每次我运行这个程序时,它第一次运行,但第二次在终端出现此错误:

Traceback (most recent call last):
  File "main.py", line 30, in <module>
    timenow = datetime.now()
  File "main.py", line 27, in temperature
    moApparent = regexApparentTemp.search(str(json_object))
  File "/usr/local/lib/python3.7/dist-packages/gspread/models.py", line 888, in append_row
    return self.spreadsheet.values_append(self.title, params, body)
  File "/usr/local/lib/python3.7/dist-packages/gspread/models.py", line 119, in values_append
    r = self.client.request('post', url, params=params, json=body)
  File "/usr/local/lib/python3.7/dist-packages/gspread/client.py", line 79, in request
    raise APIError(response)
gspread.exceptions.APIError: {
  "error": {
    "code": 401,
    "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
    "status": "UNAUTHENTICATED"
  }
}

代码是:

import requests, pprint, re, gspread, time
from oauth2client.service_account import ServiceAccountCredentials
from datetime import datetime



def temperature():
    from oauth2client.service_account import ServiceAccountCredentials
    from datetime import datetime
    scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']

    credentials = ServiceAccountCredentials.from_json_keyfile_name('Singapore-Weather-84def2be176a.json', scope)

    gc = gspread.authorize(credentials)

    wks = gc.open('Singapore Weather').sheet1
    r = requests.get('https://api.darksky.net/forecast/b02b5107a2c9c27deaa3bc1876bcee81/1.312914,%20103.780257')
    json_object = r.text


    regexCurrentTemp = re.compile(r'"temperature":(\d\d.\d\d)')
    moTemp = regexCurrentTemp.search(str(json_object))
    temperature = moTemp.group(1)

    regexApparentTemp = re.compile(r'"apparentTemperature":(\d\d.\d\d)')
    moApparent = regexApparentTemp.search(str(json_object))
    apparent = moApparent.group(1)

    timenow = datetime.now()
    wks.append_row([str(timenow), temperature, apparent])

while True:
    temperature()
    time.sleep(3597)

我将 autentication 放在循环中的函数内,这样它就可以工作,但它没有。有什么问题?

【问题讨论】:

  • 我在您的代码中看不到 SMTP(发送邮件传输协议)。如果出现错误,请首先使用print() 检查变量中的内容。也许你发送了错误的值。
  • 顺便说一句:darksky 以 JSON 格式发送数据,因此您不必转换为字符串并使用正则表达式,而是 apparent = r.json()['currently']['apparentTemperature']temperature = r.json()['currently']['temperature']
  • 我为什么放了SMTP???
  • 无论如何,它第一次工作,但后来我得到一个身份验证错误
  • 也许你应该只授权一次 - 在while True之前。

标签: python google-api google-sheets-api


【解决方案1】:

正如您在 Github googleapis/oauth2client 上看到的那样,已弃用

建议你试试官方Gmail API Python example:

def create_message(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(
))}

如果您对上面的示例感到困惑,请尝试Gmail API Quickstart Python tutorial

【讨论】:

  • 这不是答案。我不想发送电子邮件,我想做谷歌表格。这应该是作为建议的评论,而不是答案。问题是“为什么我会收到 SMTP 身份验证错误?”。我不是故意说 SMTP,所以我道歉。但是,如果您阅读我的代码的前三行,您会发现我根本没有使用 SMTP。
猜你喜欢
  • 2019-01-03
  • 2013-12-12
  • 2016-04-25
  • 2017-06-22
  • 1970-01-01
  • 2020-08-06
  • 1970-01-01
  • 1970-01-01
  • 2023-02-24
相关资源
最近更新 更多