Python 微软邮箱 OAuth2 认证 Demo
简介
使用 OAuth2 认证相较于传统的 SMTP 方法更高效且安全。
本示例代码通过 email
, client_id
, refresh_token
获取 access_token
,然后使用 access_token
读取邮件列表。更多功能可以自行扩展。
示例代码
导入必要的库
# -*- coding: utf-8 -*-
import email as email_reader
import random
import ssl
from email.header import decode_header
from enum import Enum
import requests
import imaplib
获取 access_token
方法
def get_access_token_from_refresh_token(refresh_token, client_id):
headers = {
'Host': 'login.microsoftonline.com',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36',
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
}
data = {
"client_id": client_id,
"refresh_token": refresh_token,
"grant_type": "refresh_token"
}
rr = requests.post("https://login.microsoftonline.com/common/oauth2/v2.0/token", headers=headers, data=data)
if rr.json().get("error") is None:
return {"code": 0, "access_token": rr.json()["access_token"], "refresh_token": rr.json()["refresh_token"]}
if rr.json().get("error_description").find("User account is found to be in service abuse mode") != -1:
return {"code": 1, "message": "account was blocked or wrong username, password, refresh_token, client_id"}
return {"code": 1, "message": "get access token is wrong"}
IMAP OAuth2 认证方法
def imap_authenticate_with_oauth2(username, access_token):
auth_string = f"user={username}\1auth=Bearer {access_token}\1\1"
mail = imaplib.IMAP4_SSL("outlook.office365.com")
mail.authenticate("XOAUTH2", lambda x: auth_string)
return mail
读取邮件方法
def read_mail(email, access_token):
mail = imap_authenticate_with_oauth2(email, access_token)
mail.list()
mail.select("inbox")
status, messages = mail.search(None, 'ALL')
messages = messages[0].split()
for mail_id in messages:
status, msg_data = mail.fetch(mail_id, '(RFC822)')
email_msg = msg_data[0][1].decode('utf-8')
print(email_msg)
print("done")
示例调用
def example():
email = "wendeyvenys@hotmail.com"
client_id = "8b4ba9dd-3ea5-4e5f-86f1-ddba2230dcf2"
refresh_token = "M.C525_BAY.0.U.-CvxMhLe1rlmKZ3H6fEdCrNRAggUCP5Z55X1C3lwChG0YP7CbpvsWBNTR778D8VEcZ2YPv8iUGUCWxx*f0j4SIjSz3HX!4pFIvFD1OR6udxZEiv*6E!2sqwU4qoYk410ie31TxjhVaUoXbZ5xXCHYxvYzJjPEZ1PeibIxBau4N!Duie73iVM!vGY81tJuFLPTFahzdB6Eu9CftyxqloI7TO*elPnuIIr0NJ*4g1vcQV0qiJuUUOKGDBFIaRUaUtbahmS66O*ZqOub5HoiZ*zZLHeZ!vAL9usCz3TOsMI82KxCK50dgSv87dbn1tryQ!VrKWpZcoPlP6YgjWFelADWSJMBAvnUOTWkBjNclHO35WnqeMh!OdtWqmP1HktZWCPEytOBU8RynGl7Z2j7ct!Q7tqUoOmiczZ!y1LGK3deUFPWA9IHdtJYxl2yEGBYkbQbDA$"
token = get_access_token_from_refresh_token(refresh_token, client_id)
read_mail(email, token["access_token"])
# 调用示例
example()
注意事项
- 必要参数:
email
,client_id
,refresh_token
- 安全性建议:避免在代码中直接存储敏感信息(如
client_id
和refresh_token
)。可以使用环境变量或配置文件管理。 - 更多功能(如发送邮件、过滤邮件等)需自行扩展开发。