Outlook / Hotmail 邮箱监控配置流程
Outlook / Hotmail 邮箱监控配置流程1. 注册 Microsoft Azure 账号正常注册通常需要绑定 Visa 信用卡。没有信用卡时,可尝试走学生通道。学生通道需要 edu 邮箱。可通过闲鱼获取 edu 邮箱;请注意合规与账号安全风险。2. 进入 Microsoft Entra ID注册完成后,在 Microsoft Azure 主页找到Microsoft Entra ID菜单。进入该菜单。3. 注册应用点击添加→应用注册。填写应用名称。受支持的账户类型:选择“任何 Entra 租户和个人账户”。重定向 URI:平台选择:公共客户端/本机(移动和桌面)URI 填写:https://login.microsoftonline.com/common/oauth2/nativeclient点击注册。记录应用程序id,需要在代码中使用4. 配置 API 权限进入应用页面 →管理→API 权限。点击添加权限。选择以下权限:Mail.Readoffline_accessUser.Read5. 启用公共客户端流进入管理→Authentication (Preview)。在设置中启用:允许公共客户端流权限说明权限用途Mail.Read读取邮件offline_access获取刷新令牌,便于长期访问User.Read读取用户基本资料安全提示不要泄露应用密钥、访问令牌或刷新令牌。仅申请实际需要的权限。定期检查并撤销不再使用的应用授权。#!/usr/bin/env python3# -*- coding: utf-8 -*-""" Graph Mail Monitor - 监控多个 Outlook.com 邮箱收件箱 使用 Microsoft Graph API 轮询未读邮件 """importosimportsysimportjsonimporttimeimportsqlite3importloggingimportthreadingimportargparsefromconcurrent.futuresimportThreadPoolExecutor,as_completedfromdatetimeimportdatetime,timezone,timedeltaimportmsalimportrequests# ---------- 日志配置 ----------logger=logging.getLogger("GraphMailMonitor")logger.setLevel(logging.INFO)formatter=logging.Formatter("%(asctime)s [%(levelname)s] %(threadName)s - %(message)s",datefmt="%Y-%m-%d %H:%M:%S")ch=logging.StreamHandler()ch.setFormatter(formatter)logger.addHandler(ch)fh=logging.FileHandler("graph_monitor.log",encoding="utf-8")fh.setFormatter(formatter)logger.addHandler(fh)# ---------- 配置类 ----------classConfig:def__init__(self,path="config.json"):self.path=pathifnotos.path.exists(path):self._create_default()raiseFileNotFoundError(f"已创建默认配置文件{path},请填写 client_id 和 accounts 后重新运行。")withopen(path,"r",encoding="utf-8")asf:data=json.load(f)self.client_id=data["client_id"]self.authority=data.get("authority","https://login.microsoftonline.com/consumers")self.scopes=data.get("scopes",["https://graph.microsoft.com/Mail.Read","https://graph.microsoft.com/User.Read"])self.poll_interval=data.get("poll_interval",60)self.db_path=data.get("db_path","graph_seen.db")self.token_cache_file=data.get("token_cache_file","token_cache.bin")self.accounts=data.get("accounts",[])self._data=data# 保留原始数据以便回写def_create_default(self):default={"client_id":"YOUR_CLIENT_ID","authority":"https://login.microsoftonline.com/consumers","scopes":["https://graph.microsoft.com/Mail.Read","https://graph.microsoft.com/User.Read"],"poll_interval":60,"db_path":"graph_seen.db","token_cache_file":"token_cache.bin","accounts":[{"email":"account01@outlook.com","refresh_token":""},{"email":"account02@outlook.com","refresh_token":""}]}withopen(self.path,"w",encoding="utf-8")asf:json.dump(default,f,indent=2,ensure_ascii=False)defsave(self):"""将当前 accounts 的 refresh_token 写回配置文件"""self._data["accounts"]=self.accountswithopen(self.path,"w",encoding="utf-8")