You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中如何改用Microsoft Graph API替代MSOnline创建邮件及模块疑问

问题描述

我目前使用MsolService创建邮件,希望改用Microsoft Graph API,但找不到对应的C#实现文档。当前我通过以下C#代码调用PowerShell库连接Microsoft Online Services,不确定要导入哪个模块以使用mgGraph,也不清楚现有PowerShell库是否包含mgGraph模块:

using System.Management.Automation.Host;
using Microsoft.PowerShell.Commands;

// Create Initial Session State for runspace.
InitialSessionState initialSession = InitialSessionState.CreateDefault();
initialSession.ImportPSModule(new[] { "MSOnline" });

// Create credential object.
PSCredential credential = new PSCredential(UserCredential.UserName, UserCredential.Password);

// Create command to connect office 365.
Command connectCommand = new Command("Connect-MsolService");
connectCommand.Parameters.Add((new CommandParameter("Credential", credential)));
解决方案

一、优先使用Microsoft Graph .NET SDK(推荐)

在C#中调用Microsoft Graph API,不建议通过PowerShell模块中转,直接使用官方提供的.NET SDK是更规范、高效的方式:

  1. 安装NuGet包
    安装核心SDK和身份认证包:

    Install-Package Microsoft.Graph
    Install-Package Microsoft.Graph.Auth
    
  2. 认证与创建邮件示例代码
    以用户名密码认证为例(生产环境建议使用证书或客户端凭据等更安全的方式):

    using Microsoft.Graph;
    using Microsoft.Graph.Auth;
    using Microsoft.Identity.Client;
    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    
    class Program
    {
        static async Task Main(string[] args)
        {
            var clientId = "你的应用客户端ID"; // 在Azure AD注册应用获取
            var tenantId = "你的租户ID";
            var username = "用户邮箱";
            var password = "用户密码";
    
            var scopes = new[] { "Mail.Send" };
    
            var publicClientApplication = PublicClientApplicationBuilder
                .Create(clientId)
                .WithTenantId(tenantId)
                .Build();
    
            var authProvider = new UsernamePasswordProvider(publicClientApplication, scopes);
            var graphClient = new GraphServiceClient(authProvider);
    
            // 创建邮件对象
            var message = new Message
            {
                Subject = "测试邮件",
                Body = new ItemBody
                {
                    ContentType = BodyType.Text,
                    Content = "这是通过Microsoft Graph SDK发送的测试邮件"
                },
                ToRecipients = new List<Recipient>
                {
                    new Recipient
                    {
                        EmailAddress = new EmailAddress
                        {
                            Address = "收件人邮箱"
                        }
                    }
                }
            };
    
            // 发送邮件
            await graphClient.Me.SendMail(message, saveToSentItems: true).Request().PostAsync();
        }
    }
    

二、关于PowerShell模块的疑问

  1. mgGraph模块是否包含在现有库中?
    不包含。MSOnline是旧的Azure AD模块,而Microsoft Graph PowerShell是独立的新模块,两者没有包含关系。

  2. 如何在C#中导入mgGraph模块?
    如果一定要在C#中调用Graph的PowerShell模块,需要先确保机器上已安装该模块(通过Install-Module Microsoft.Graph命令安装),然后修改代码导入模块并连接:

    InitialSessionState initialSession = InitialSessionState.CreateDefault();
    // 导入Microsoft Graph模块
    initialSession.ImportPSModule(new[] { "Microsoft.Graph" });
    
    PSCredential credential = new PSCredential(UserCredential.UserName, UserCredential.Password);
    
    // 连接Graph,需要指定权限范围
    Command connectCommand = new Command("Connect-MgGraph");
    connectCommand.Parameters.Add(new CommandParameter("Credential", credential));
    connectCommand.Parameters.Add(new CommandParameter("Scopes", new[] { "Mail.Send" }));
    

内容的提问来源于stack exchange,提问作者Leon K.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 19:20:15