簡體   English   中英

使用 Gmail API 而不在 Python 中打開瀏覽器

[英]Using Gmail API without opening browser in Python

我在 Jetson Xavier 中有無頭軟件。 我正在使用 Gmail API 發送郵件。 我的代碼在筆記本電腦中正常工作,但是在 Jetson 中禁用了 GUI 服務,無法打開瀏覽器。 因此,當我嘗試在 Jetson 中使用 Gmail API 時,身份驗證失敗。

我已將經過身份驗證的“token.pickle”從筆記本電腦復制到 Jetson。 它可以在短時間內正常工作。 然后,它想要再次進行身份驗證。

我該如何解決這個問題? 如何阻止瀏覽器在 Jetson 中打開進行身份驗證?

謝謝。

這部分代碼用於身份驗證:

class EmailSender:

    def __init__(self):

        # If modifying these scopes, delete the file token.pickle.
        SCOPES = ['https://www.googleapis.com/auth/gmail.compose']

        creds = None
        # The file token.pickle stores the user's access and refresh tokens, and is
        # created automatically when the authorization flow completes for the first
        # time.
        if os.path.exists('token.pickle'):
            with open('token.pickle', 'rb') as token:
                creds = pickle.load(token)
        # If there are no (valid) credentials available, let the user log in.
        if not creds or not creds.valid:
            if creds and creds.expired and creds.refresh_token:
                creds.refresh(Request())
            else:
                creds_dir = os.path.dirname(os.path.abspath(__file__)) + '/credentials.json'
                flow = InstalledAppFlow.from_client_secrets_file(
                    creds_dir, SCOPES)
                creds = flow.run_local_server(port=0)
            # Save the credentials for the next run
            with open('token.pickle', 'wb') as token:
                pickle.dump(creds, token)

        self.service = build('gmail', 'v1', credentials=creds)

不幸的是,出於安全原因,gmail(以及大多數現代身份驗證服務)不允許您直接自動登錄。 為了確保第三方服務不會竊取您的帳戶,谷歌會要求您作為人類輸入您的帳戶和密碼,並且谷歌會向您嘗試登錄的服務返回一個 cookie 或令牌。

但是,由於您正在處理自己的項目,並且我假設您知道該程序不會使您的帳戶面臨風險,因此您可以使用 selenium 模擬瀏覽器並自動鍵入您的帳戶。 你可以參考這篇文章來學習如何做。

暫無
暫無

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

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