代码 Python 微软邮箱 OAuth2 认证 Demo

2024-11-20 15:42:09 +0800 CST views 3245

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_idrefresh_token)。可以使用环境变量或配置文件管理。
  • 更多功能(如发送邮件、过滤邮件等)需自行扩展开发。
复制全文 生成海报 编程 电子邮件 安全性 API Python

推荐文章

Vue3 实现页面上下滑动方案
2025-06-28 17:07:57 +0800 CST
一个数字时钟的HTML
2024-11-19 07:46:53 +0800 CST
html一个包含iPhoneX和MacBook模拟器
2024-11-19 08:03:47 +0800 CST
Vue3中如何进行异步组件的加载?
2024-11-17 04:29:53 +0800 CST
软件定制开发流程
2024-11-19 05:52:28 +0800 CST
Python Invoke:强大的自动化任务库
2024-11-18 14:05:40 +0800 CST
Vue3 组件间通信的多种方式
2024-11-19 02:57:47 +0800 CST
Vue3中的v-for指令有什么新特性?
2024-11-18 12:34:09 +0800 CST
JavaScript 上传文件的几种方式
2024-11-18 21:11:59 +0800 CST
Vue 3 路由守卫详解与实战
2024-11-17 04:39:17 +0800 CST
Rust 与 sqlx:数据库迁移实战指南
2024-11-19 02:38:49 +0800 CST
Vue3中的虚拟滚动有哪些改进?
2024-11-18 23:58:18 +0800 CST
手机导航效果
2024-11-19 07:53:16 +0800 CST
php使用文件锁解决少量并发问题
2024-11-17 05:07:57 +0800 CST
XSS攻击是什么?
2024-11-19 02:10:07 +0800 CST
CentOS 镜像源配置
2024-11-18 11:28:06 +0800 CST
程序员茄子在线接单