前言
微软登录方式发生了改变,需要用 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 注意 !!!: 在第6点注册后 会出现一次的秘钥 (secret或者value)记得保存下来 第10点 重定向的地址改成:https://login.microsoftonline.com/common/oauth2/nativeclient 这个是微软通过的地址,不要用本地的。 最后加权限的时候顺便加一下邮箱的权限 (搜索 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:
url = 'https:
#参考资料 https:
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:
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:
# 获取邮箱文件夹找到你的收件箱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)
|