前言
微软登录方式发生了改变,需要用 oauth2 ,以前的写的脚本都登录不上了,本文记录下更新后的登录方式。
报错如下:
imaplib.IMAP4.error: b’LOGIN failed.’
一、先决条件
1.在Azure 门户注册应用程序
这里可以跟着官方教程走
传送门:https://learn.microsoft.com/zh-cn/azure/active-directory/develop/web-app-quickstart?pivots=devlang-python
注意 !!!:
第10点 重定向的地址改成:https://login.microsoftonline.com/common/oauth2/nativeclient
这个是微软通过的地址,不要用本地的。
第13点注册后 会出现一次的秘钥 (value)记得保存下来。
最后加权限的时候顺便加一下邮箱的权限 (搜索 mail )
顺便加的邮箱权限
二、使用步骤
1.引入库
代码如下:
from playwright.sync_api import Playwright, sync_playwright
import time
import urllib.parse
import requests, json
2.读入数据
1.请求 authorize Api 获取 code
代码如下(示例):
code = ''
userName = '邮箱账号'
passWord = '邮箱密码'
client_id = '你的client_id '
tenant_id = '你的tenant_id '
client_secret = '创建好应用后创建的的秘钥'
redirect_uri = 'https://login.microsoftonline.com/common/oauth2/nativeclient'
url = 'https://login.microsoftonline.com/{}/oauth2/v2.0/authorize?%20client_id={}&response_type=code%20&redirect_uri={}&response_mode=query%20&scope=https%3A%2F%2Fgraph.microsoft.com%2Fmail.read%20&state=12345'.format(tenant_id , client_id , redirect_uri)
#参考资料 https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow
def run(playwright: Playwright) -> None:
browser = playwright.chromium.launch(headless=False)
context = browser.new_context(locale="zh-CN", accept_downloads=True)
# Open new page
page = context.new_page()
page.goto(url)
page.click("[placeholder=\"电子邮件、电话或\\ Skype\"]")
page.fill("[placeholder=\"电子邮件、电话或\\ Skype\"]", userName)
with page.expect_navigation():
page.click("text=下一步")
page.click("[placeholder=\"密码\"]")
page.fill("[placeholder=\"密码\"]", passWord)
with page.expect_navigation():
page.click("text=登录")
page.click("text=否")
time.sleep(3)
global code
query = dict(urllib.parse.parse_qsl(urllib.parse.urlsplit(page.url).query))
#print('code :', query['code'])
#print('state :', query['state'])
#print('session_state :', query['session_state'])
code = query['code']
# ---------------------
context.close()
browser.close()
with sync_playwright() as playwright:
run(playwright)
print('code :', code )
print('-----------end code--------')
- 拿code换token
#get token
myobj = {'client_id': client_id,
'code': code,
'redirect_uri': redirect_uri,
'grant_type': 'authorization_code',
'client_secret': client_secret
}
token_headers = {"Content-Type":"application/x-www-form-urlencoded"}
token_url = 'https://login.microsoftonline.com/{}/oauth2/v2.0/token'.format(tenant_id )
r = requests.post(url= token_url , headers = token_headers , data = myobj)
access_token=json.loads(r.text).get('access_token')
print('Bearer '+access_token)
print("------access_token end------")
3.拿token请求api
# 其他api参考:https://learn.microsoft.com/en-us/graph/api/mailfolder-list-messages?view=graph-rest-1.0&tabs=http
# 获取邮箱文件夹找到你的收件箱id
endpoint ="https://graph.microsoft.com/v1.0/me/mailFolders"
http_headers = {'Authorization': 'Bearer ' + access_token,
'Accept': 'application/json',
'Content-Type': 'application/json'}
data = requests.get(endpoint, headers=http_headers, stream=False).json()
print(data)
# 获取收件箱里面的 邮件
endpoint ="https://graph.microsoft.com/v1.0/me/mailFolders/你的收件箱文件夹id/messages"
http_headers = {'Authorization': 'Bearer ' + access_token,
'Accept': 'application/json',
'Content-Type': 'application/json'}
data = requests.get(endpoint, headers=http_headers, stream=False).json()
print(data)