如何在删除"less secure app"后使用 imaplib 阅读 gmail。(或替代方案)托管在 AWS 上时



我使用的是一个简单的脚本,它使用imaplib读取我的gmail,使用我的用户名和密码并"不太安全的应用程序";Gmail选项。Gmail将禁用";不太安全的应用程序";选项,所以我需要在这之前修复登录凭据。

我已经学习了关于使用Oauth2的教程,但问题是脚本没有在本地运行(在AWS ubuntu 20.04上运行(,所以我无法在运行脚本的机器上打开web身份验证,登录失败。

更准确地说,当我运行教程代码时,我会得到以下内容:

Please visit this URL to authorize this application: https://accounts.google.com/o/oauth2/...

我无法在AWS命令行上打开该URL,在本地机器上登录也不起作用(它使用凭据重定向到localhost(。

我相信以下代码获得了带有凭据的谷歌响应:

flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
creds = flow.run_local_server(port=0)

我认为一种选择是让凭据在本地运行脚本,或者用本地服务器捕获它们,然后将它们发送到AWS,但如果它们过期,我需要再次这样做,可能无论如何都不会奏效。

我的直觉认为这不是应该走的路。有什么想法吗?

如果你想继续使用imaplib,那么描述不太安全的应用程序的最简单的解决方案是切换到使用应用程序pasword

这可能会继续,也可能不会继续——没有办法真正知道。

那个教程。

该教程的工作方式是将用户的credentials存储在文件token.pickle中。如果该文件不存在,它会提示您对其进行授权。

# The file token.pickle contains the user access token.
# Check if it exists
if os.path.exists('token.pickle'):
# Read the token from the file and store it in the variable creds
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If credentials are not available or are invalid, ask the user to log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the access token in token.pickle file for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)

你可以做的是在获得token.pickle后运行你的代码,并确保在上传到AWS时包含该文件。

确保你将你的应用程序设置为生产版,或者你的刷新令牌只会在七天内有效,并且在那一刻它将停止工作。

我的直觉说这不是应该走的路。有什么想法吗?

除非这是谷歌工作区域电子邮件,否则没有其他选择。

相关内容

最新更新