企業內部系統常需整合 Outlook 行事曆,自動發送會議邀請。雖 Microsoft Graph API 是現代首選,但舊專案或離線環境仍大量使用 Microsoft.Office.Interop.Outlook。本文完整示範建立會議邀請流程,重點解決「指定寄件人帳號」與「集合索引從 1 開始」兩大隱藏坑點。
using Microsoft.Office.Interop.Outlook;using System;
using Microsoft.Office.Interop.Outlook;
namespace OutlookMeetingDemo
{
class Program
{
static void Main(string[] args)
{
try
{
// 1. 建立 Application 實例(會啟動或連接既有 Outlook 進程)
Application outlookApp = new Application();
// 2. 建立約會項目並設為會議
AppointmentItem meeting = (AppointmentItem)outlookApp.CreateItem(OlItemType.olAppointmentItem);
meeting.MeetingStatus = OlMeetingStatus.olMeeting;
// 3. 基本屬性設定
meeting.Subject = "專案啟動會議";
meeting.Body = "議程:\n1. 專案範圍確認\n2. 里程碑規劃\n3. 風險識別";
meeting.Location = "會議室 A / Teams 線上";
meeting.Start = DateTime.Now.AddDays(1).Date.AddHours(10); // 明天 10:00
meeting.End = meeting.Start.Value.AddHours(2); // 12:00 結束
meeting.ReminderSet = true;
meeting.ReminderMinutesBeforeStart = 15;
meeting.AllDayEvent = false;
meeting.BusyStatus = OlBusyStatus.olBusy;
// 4. 【關鍵】指定寄件人帳號 —— Accounts 集合索引從 1 開始!
// 建議先列印所有帳號確認索引
for (int i = 1; i <= outlookApp.Session.Accounts.Count; i++)
{
Console.WriteLine($"[{i}] {outlookApp.Session.Accounts[i].DisplayName} - {outlookApp.Session.Accounts[i].SmtpAddress}");
}
// 假設第 2 個帳號為發送帳號
meeting.SendUsingAccount = outlookApp.Session.Accounts[2];
// 5. 新增收件人(必選、可選、召集人)
AddRecipient(meeting, "alice@company.com", OlMeetingRecipientType.olRequired);
AddRecipient(meeting, "bob@company.com", OlMeetingRecipientType.olOptional);
AddRecipient(meeting, "organizer@company.com", OlMeetingRecipientType.olOrganizer);
// 6. 解析收件人(驗證地址簿)並發送
meeting.Recipients.ResolveAll();
meeting.Send();
Console.WriteLine("會議邀請已發送!");
}
catch (System.Exception ex)
{
Console.WriteLine($"發生錯誤:{ex.Message}");
if (ex.InnerException != null)
Console.WriteLine($"內部錯誤:{ex.InnerException.Message}");
}
Console.ReadLine();
}
static void AddRecipient(AppointmentItem meeting, string email, OlMeetingRecipientType type)
{
Recipient recip = meeting.Recipients.Add(email);
recip.Type = (int)type;
}
}
}
這是 COM 互通層的歷史遺留設計。outlookApp.Session.Accounts[1] 才是第一個帳號,[0] 會拋出「索引超出範圍」例外。務必用迴圈列印確認索引,不要硬編碼。
未解析的收件人會導致發送失敗或郵件卡在寄件匣。解析過程會連線 Exchange/地址簿驗證。
Start/End 屬性型別為 DateTime,Outlook 內部以 UTC 儲存並依用戶時區顯示。TimeZoneInfo.ConvertTimeToUtc 明確指定時區,避免伺服器時區與參會者不一致導致時間偏移。新專案強烈建議改用 Graph API:
POST /users/{id}/events,JSON 包含 attendees、isOnlineMeeting 等豐富屬性。Microsoft.Graph,搭配 Azure.Identity 做 OAuth2 驗證。Outlook Interop 能快速滿足舊系統「發會議」需求,但僅適合桌面端、單使用者、互動式場景。核心坑點在於 Accounts[1] 起始索引與發送身分綁定登入設定檔。伺服器端自動化請務必遷移至 Microsoft Graph API,獲得穩定、安全、可擴展的整合體驗。