簡體   English   中英

無法將Google服務帳戶驗證為Gmail

[英]Can't authenticate Google service account to Gmail

我有一個GSuite電子郵件地址example@gmail.com,並且創建了一個Google服務帳戶example-sa@iam.gserviceaccount.com。

我的目標是從該SA發送電子郵件,就像發送電子郵件一樣,但是我無法對SA進行身份驗證。

但是,我可以使用以下代碼登錄服務帳戶Google雲端硬盤:

from google.oauth2 import service_account
from googleapiclient import discovery

SCOPES = ['https://www.googleapis.com/auth/drive']
SERVICE_ACCOUNT_FILE = 'sa-credentials.json'
creds = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
service = discovery.build('drive', 'v3', credentials=creds, cache_discovery=False)

# code

但是,當我嘗試對gmail進行相同操作時,出現錯誤:

from google.oauth2 import service_account
from googleapiclient import discovery

SCOPES = ['https://mail.google.com/']
SERVICE_ACCOUNT_FILE = 'sa-credentials.json'
creds = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
service = discovery.build('gmail', 'v1', credentials=creds, cache_discovery=False)

profile = service.users().getProfile(userId='me').execute()

錯誤:

  raise HttpError(resp, content, uri=self.uri) googleapiclient.errors.HttpError: <HttpError 400 when requesting https://www.googleapis.com/gmail/v1/users/me/profile?alt=json returned "Bad Request"> 

如果單擊錯誤消息中提供的URL,則會得到:

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "required",
    "message": "Login Required",
    "locationType": "header",
    "location": "Authorization"
   }
  ],
  "code": 401,
  "message": "Login Required"
 }
}

看到類似的問題: GMail API-我可以使用服務帳戶發送電子郵件嗎?

否。GmailAPI適用於Gmail用戶, 服務帳戶僅用於對真實Gmail帳戶進行身份驗證,他們沒有自己的Gmail帳戶 ,等等。

換句話說,該服務帳戶似乎不是您可以訪問的Gmail郵箱。

您需要使用服務帳戶來訪問其他郵箱,並且要執行此操作,您需要執行以下兩項操作之一:

  1. 使用Oauth2流獲取您想要用來授予訪問權限的郵箱的所有者(請參閱: https : //developers.google.com/gmail/api/auth/web-server

要么

  1. 如果您控制/擁有Gsuite域,請將該域的整個域范圍的權限授予您的服務帳戶。 請參閱: https : //developers.google.com/admin-sdk/directory/v1/guides/delegation

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM