用微软365邮箱收发邮件【azure-应用注册】

前置条件:

  • 有一个365邮箱,配置好许可证

  • 在azure portal里有Microsoft Entra ID ,注册相关应用时graph API赋权

- 应用的应用程序(客户端) ID,目录(租户) ID,客户端的密码,邮箱的id,名称

1.收件:

python 复制代码
import os
import json
import requests
from .auth2 import get_access_token

def load_token_from_file():
    TOKEN_FILE = 'token_cache.json'
    if os.path.exists(TOKEN_FILE):
        with open(TOKEN_FILE, 'r') as f:
            data = json.load(f)
            return data.get('access_token', None)
    return None

def fetch_unread_emails():
    try:
        access_token = get_access_token()
        if not access_token:
            print('无法加载访问令牌。')
            return

        headers = {
            'Authorization': f'Bearer {access_token}',
            'Content-Type': 'application/json'
        }

        user_id = '-------'
        url = f'https://graph.microsoft.com/v1.0/users/{user_id}/mailfolders/inbox/messages?$filter=isRead eq false'

        response = requests.get(url, headers=headers)
        print(f"Response Status Code: {response.status_code}")
        print(f"Response Content: {response.content}")

        if response.status_code != 200:
            print(f"Error fetching emails: {response.content}")
            return
###代码仅为示例,如想了解更多收发邮件功能,实现赋能gpt的自动收发,处理,function calling,add wx: MTMwMTE4MjY1OTI= (base64)
        emails = response.json().get('value', [])
        for email in emails:
            print(f"Email ID: {email['id']}")
            print(f"From: {email['from']['emailAddress']['address']}")
            print(f"Subject: {email['subject']}")
            print(f"Content: {email['body']['content']}")
            print(f"Received Time: {email['receivedDateTime']}")
            print("-" * 40)

    except Exception as ex:
        print("Error fetching unread emails: ", ex)

# Test fetching unread emails
if __name__ == "__main__":
    fetch_unread_emails()

2.发件:

python 复制代码
from flask import Flask, request, jsonify
import requests
import base64
import msal
import os

app = Flask(__name__)

# Configuration variables
CLIENT_ID = 'your_client_id'
CLIENT_SECRET = 'your_client_secret'
TENANT_ID = 'your_tenant_id'
SCOPES = ['https://graph.microsoft.com/.default']
CACHE_FILE = 'token_cache.bin'
URL = 'https://graph.microsoft.com/v1.0/me/sendMail'

def load_cache():
    cache = msal.SerializableTokenCache()
    if os.path.exists(CACHE_FILE):
        cache.deserialize(open(CACHE_FILE, "r").read())
    return cache

def save_cache(cache):
    if cache.has_state_changed:
        with open(CACHE_FILE, "w") as f:
            f.write(cache.serialize())

def get_access_token():
    cache = load_cache()
    app = msal.ConfidentialClientApplication(
        CLIENT_ID,
        authority=f"https://login.microsoftonline.com/{TENANT_ID}",
        client_credential=CLIENT_SECRET,
        token_cache=cache
    )

    result = app.acquire_token_silent(SCOPES, account=None)
    if not result:
        result = app.acquire_token_for_client(scopes=SCOPES)

    if "access_token" in result:
        save_cache(cache)
        return result['access_token']
    else:
        raise ValueError(f"Failed to obtain access token: {result.get('error_description')}")

def create_attachment(file_path, content_id):
    with open(file_path, "rb") as f:
        content_bytes = base64.b64encode(f.read()).decode('utf-8')
    return {
        "@odata.type": "#microsoft.graph.fileAttachment",
        "name": os.path.basename(file_path),
        "contentBytes": content_bytes,
        "contentId": content_id
    }

@app.route('/send-email', methods=['POST'])
def send_email_api():
    data = request.json
    try:
        token = get_access_token()
        sender_email = data['sender']
        recipients_emails = data['recipients']
        subject = data['subject']
        body = data['body']
        attachments = [create_attachment(file_path, content_id) for file_path, content_id in data.get('attachments', [])]

        email_data = {
            "message": {
                "subject": subject,
                "body": {
                    "contentType": "HTML",
                    "content": body
                },
                "toRecipients": [{"emailAddress": {"address": recipient}} for recipient in recipients_emails],
                "from": {"emailAddress": {"address": sender_email}},
                "attachments": attachments
            }
        }

        headers = {
            "Authorization": f"Bearer {token}",
            "Content-Type": "application/json"
        }

        response = requests.post(URL, headers=headers, json=email_data)

        if response.status_code == 202:
            return jsonify({"message": "Email sent successfully"}), 200
        else:
            return jsonify({"error": f"Failed to send email: {response.status_code}"}), 500
    except Exception as e:
        return jsonify({"error": str(e)}), 500

if __name__ == "__main__":
    app.run(debug=True, port=5000)
相关推荐
编码者卢布4 小时前
【Azure Developer】azd 安装最新版无法登录中国区问题二:本地Windows环境遇问题
microsoft·flask·azure
编码者卢布1 天前
【Azure Developer】中国区Azure环境中查看用户账号是否可用(accountEnabled)的操作步骤
microsoft·flask·azure
编码者卢布1 天前
【Azure APIM】如何实现对经过APIM并到达后端服务请求的全链路追踪呢?
python·flask·azure
编码者卢布1 天前
【Azure Stream Analytic】用 JavaScript UDF 解决 JSON 字段被转成 Record 的关键点
javascript·json·azure
编码者卢布1 天前
【Azure App Service】部署在应用服务上的WebJob中,为何会多出一个名为“DaaS“的 WebJob呢?
microsoft·azure
晚霞的不甘1 天前
Flutter for OpenHarmony构建全功能视差侧滑菜单系统:从动效设计到多页面导航的完整实践
前端·学习·flutter·microsoft·前端框架·交互
逻极1 天前
Claude Code实战——打造智能研报 CLI 工具:45分钟零构建智能研报助手CLI,解锁AI编程效率革命
microsoft·ai编程·ai辅助编程·claude code·python实战·cli开发
xixixi777771 天前
Prompt脱敏——不损失(或尽量少损失)原文本语义和上下文价值的前提下,防止原始敏感数据暴露给模型服务方、潜在的攻击者或出现在模型训练数据中
人工智能·microsoft·ai·大模型·数据安全·提示词·敏感信息
HyperAI超神经1 天前
【TVM教程】设备/目标交互
人工智能·深度学习·神经网络·microsoft·机器学习·交互·gpu算力
晚霞的不甘1 天前
Flutter for OpenHarmony实现高性能流体粒子模拟:从物理引擎到交互式可视化
前端·数据库·经验分享·flutter·microsoft·计算机视觉