.Net對POP3郵件系統已經整合了相應的功能,但是如果是基於Exchange server的郵件系統,相對就比較複雜。如果僅僅是發送,可以簡單地調用CDO來實現(參見我以前的一篇文章http://www.cnblogs.com/Moosdau/archive/2007/09/28/908834.html),但是如果要接收或進行其它一些更複雜一些操作,CDO就無法實現。
事實上,Exchange Server 2003根本不支援與.Net直接互動,據說Exchange Server 2007開放了一組Web Service介面,如果使用了Exchange Server 2007,則可以直接通過Web Service介面直接與Exchange server互動,不過我們公司目前還是使用exchange server 2003,所以也沒有測試這組介面要如何使用。
對使用exchange server 2003的環境來說,代價最低的應該說就是調用outlook的功能了,以下列舉與outlook互動的一些常用操作。
首先,在項目中添加對outlook組件的引用(Project—>Add Reference—>切換到COM標籤頁—>選擇Microsoft Outlook 14.0 Object Library),這裡outlook的具體版本號碼取決於本地安裝的outlook版本,我安裝的是outlook 2010, 所以顯示的版本號碼是14.0,這個關係不大,各個版本之間的代碼似乎是完全相同的。
以下代碼列舉收件匣中的未讀郵件:
var app = new Microsoft.Office.Interop.Outlook.Application(); var ns = app.GetNamespace("MAPI"); ns.Logon("Outlook", Type.Missing, false, false); var inbox = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox); for (int i = 1; i <= inbox.Items.Count; i++) { if (inbox.Items[i].UnRead) { txtMailList.Text += inbox.Items[i].Subject + System.Environment.NewLine; } } ns.Logoff(); Marshal.ReleaseComObject(inbox); Marshal.ReleaseComObject(ns); Marshal.ReleaseComObject(app); inbox = null; ns = null; app = null;
上述代碼第三行中出現的“Outlook”字樣,這是Outlook自動建立的預設profile名稱,如果曾經修改過這個profile,或者當地套件含多個profile,或者不確定profile名稱,請點擊控制台-->User Accounts-->郵件,如:
點擊“顯示設定檔”:
即可看到設定檔的名稱。
用迴圈枚舉收件匣的項目時,需要注意從1開始編號。
如果要讀取本機資料檔案中的郵件:
var localFolder = ns.Stores["Local"].GetRootFolder().Folders["Archieve"];
如果要刪除檔案中的郵件,注意每刪除一封索引號都會重新編號,所以不能遞增迴圈, 而必須從大到小遞減迴圈。
如果需要調用exchange server解析別名的功能:
string alias = "Marvin Yan"; var recipient = app.Session.CreateRecipient(alias); if (!recipient.Resolve()) { //alias can't be recoganized. }
根據recipient擷取smtp地址(username@server 格式的郵件地址):
string mailAddr = recipient.AddressEntry.GetExchangeUser().PrimarySmtpAddress;
如果要回複一封已有郵件:
var mail = item.Reply(); mail.To = item.SenderEmailAddress; mail.Subject = "Hello"; mail.HTMLBody = "F.Y.I.<br />" + mail.HTMLBody; mail.Send();
建立一封新的郵件並發送的代碼如下:
var mail = app.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem); mail.HTMLBody = "Hello!"; //Add an attachment. String attachName = "hello"; int attachPos = (int)mail.Body.Length + 1; int attachType = (int)Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue; //now attached the file mail.Attachments.Add(@"C:\\hello.txt", attachType, attachPos, attachName); //Subject line mail.Subject = "test"; // Add a recipient. var oRecip = mail.Recipients.Add("xx@xxx.com"); oRecip.Resolve(); // Send. mail.Send();