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

在Visual Studio中通过MAPI/API连接Outlook实现用户匹配验证

Outlook用户名查询解决方案(基于MAPI/Interop)

问题描述

本人是编程新手,现在要开发一个工作项目:读取包含用户名列表的文本文件,通过代码在Outlook中查询这些用户名,返回是否存在匹配结果(true/false)。想知道如何通过MAPI或API将Outlook与代码连接,以下是我目前编写的代码:

namespace QC_OUTLOOK
{
    internal class Program
    {
        private static object MessageBox;
        private static object objFile;
        private static int i;
        private static object Strings;
        private static object response;

        static int Main(string[] args)
        {
            string filePath = @"C:\Users\Documents\QC\User_list.txt";

            // string[] lines = File.ReadAllLines(filePath);

            List<string> lines = new List<string>();
            lines = File.ReadAllLines(filePath).ToList();
            using (StreamWriter streamWriter = File.CreateText(filePath));

                foreach (String line in lines)
            {
                Console.WriteLine(line);
            }
            Console.ReadLine();
            {
                Outlook._Application oApp = new OutLook.Application();
                //Get MAPI namespace
                Outlook.AddressLists oNS = oNS.AddressLists;
                Outlook.AddressList oGal = oALs.Item("Global Address List");
                //Get all entries
                Outlook.AddressEntries oEntries = oGal.AddressEntries;
                // Get first user found 
                Outlook.AddressEntry oEntry = oEntries.GetFirst();
                Outlook_UserName_Output = "";

                response = sa.GetAllUsers;
                Console.WriteLine(response);
        //
                UserCount = 0;
                UsersFound = 0;
                LastNameMatches = 0;
                InactiveUser_Count = 0;
                Inconsistent_EmailAddrs  = 0;
                GIS_UserCount = 0;
                TodaysDate = DateTime.Today;
                object value = objFile.WriteLine("Date:" + TodaysDate);
                object value1 = objFile.WriteLine("QC_UserID, QC_FullName, OutLook_Last_Name, OutLook_First_Name");
                for (i = 1; i <= Strings.Len(response) ; i++);

                Outlook.Application oApp = new Outlook.Application();

                // Get the MAPI namespace.
                Outlook.NameSpace oNS = oApp.GetNamespace("mapi");

                oNS.Logon(Missing.Value, Missing.Value, false, true);


                Outlook.MAPIFolder oInbox = oNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);


            }

        
            DataTable dt = new DataTable();
                dt.Columns.Add("FirstName");
                dt.Columns.Add("LastName");
                

                Microsoft.Office.Interop.Outlook.Items OutlookItems;
                Microsoft.Office.Interop.Outlook.Application outlookObj = new Microsoft.Office.Interop.Outlook.Application();
                Microsoft.Office.Interop.Outlook.MAPIFolder Folder_Contacts = (MAPIFolder)outlookObj.Session.GetDefaultFolder(OlDefaultFolders.olFolderContacts);
                OutlookItems = Folder_Contacts.Items;

                foreach (var item in OutlookItems)
                {
                    var contact = item as ContactItem;
                    if (contact != null)
                    {
                        DataRow dr = dt.NewRow();
                        dr["FirstName"] = contact.FirstName;
                    dr["LastName"] = contact.LastName;
                        dt.Rows.Add(dr);
                    }
                }
            return 0;
        }
    }
}

核心解决方案

1. 连接Outlook的方式

使用Microsoft.Office.Interop.Outlook库(基于MAPI协议),这是微软官方提供的.NET与Outlook交互工具。步骤:

  • 在项目中安装NuGet包:Install-Package Microsoft.Office.Interop.Outlook
  • 初始化Outlook应用实例,通过GetNamespace("mapi")获取MAPI命名空间,完成与Outlook的连接

2. 修正后的完整代码

以下代码实现:读取用户名文件、连接Outlook查询全局地址列表(GAL)、输出每个用户名的匹配结果

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Office.Interop.Outlook;

namespace QC_OUTLOOK
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // 1. 读取用户名列表文件
            string filePath = @"C:\Users\Documents\QC\User_list.txt";
            if (!File.Exists(filePath))
            {
                Console.WriteLine("文件不存在!");
                return;
            }
            List<string> userNames = File.ReadAllLines(filePath).ToList();

            // 2. 初始化Outlook并连接MAPI
            Application outlookApp = new Application();
            NameSpace mapiNamespace = outlookApp.GetNamespace("mapi");
            // 静默登录(使用当前Outlook配置文件)
            mapiNamespace.Logon(null, null, false, true);

            try
            {
                // 3. 获取全局地址列表(企业环境用户列表,个人用户可替换为联系人文件夹)
                AddressList globalAddressList = mapiNamespace.AddressLists["Global Address List"];
                AddressEntries allEntries = globalAddressList.AddressEntries;

                // 4. 遍历每个用户名,查询是否存在匹配
                foreach (string userName in userNames)
                {
                    bool isFound = false;
                    // 遍历地址列表匹配(可优化为更高效的查找方式)
                    foreach (AddressEntry entry in allEntries)
                    {
                        // 匹配规则:全名包含用户名,可根据需求改为匹配邮箱/登录名
                        if (entry.Name.IndexOf(userName, StringComparison.OrdinalIgnoreCase) >= 0)
                        {
                            isFound = true;
                            break;
                        }
                    }
                    Console.WriteLine($"用户名:{userName},是否存在:{isFound}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"查询出错:{ex.Message}");
            }
            finally
            {
                // 清理资源
                mapiNamespace.Logoff();
                System.Runtime.InteropServices.Marshal.ReleaseComObject(outlookApp);
            }

            Console.ReadLine();
        }
    }
}

3. 关键说明

  • 环境要求:必须安装Outlook客户端,且当前用户有Outlook配置文件
  • 匹配规则:代码中使用Name.IndexOf进行模糊匹配,可修改为精确匹配(如entry.Name == userName)或匹配邮箱地址entry.Address
  • 性能优化:遍历地址列表效率较低,可使用AddressEntries.Find()方法高效查找:AddressEntry foundEntry = allEntries.Find("[Name] = '" + userName + "'");
  • 个人联系人替代:若无需查询企业GAL,可替换为个人联系人文件夹逻辑:
    MAPIFolder contactsFolder = mapiNamespace.GetDefaultFolder(OlDefaultFolders.olFolderContacts);
    Items contactItems = contactsFolder.Items;
    foreach (ContactItem contact in contactItems)
    {
        if (contact.FullName.IndexOf(userName, StringComparison.OrdinalIgnoreCase) >=0)
        {
            isFound = true;
            break;
        }
    }
    

内容的提问来源于stack exchange,提问作者Lis12

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 17:06:23