C#使用Exchange實(shí)現(xiàn)發(fā)送郵件
最近項(xiàng)目中需要用到exchange的操作,就參照msdn弄了一個(gè)簡(jiǎn)單的操作類。目前先實(shí)現(xiàn)了,發(fā)送郵件和拉取收件箱的功能,其他的以后在慢慢的添加。
using Microsoft.Exchange.WebServices.Data; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace WebSite.Utilities.Mail { /// <summary> /// exchange郵件客戶端類 /// </summary> public class ExChangeMailClient { /// <summary> /// exchange服務(wù)對(duì)象 /// </summary> private static ExchangeService _exchangeService = new ExchangeService(ExchangeVersion.Exchange2010_SP1); /// <summary> /// 獲取收件箱 /// </summary> /// <param name="userId">當(dāng)前用戶名</param> /// <param name="pwd">密碼</param> /// <param name="domain">域</param> /// <param name="pageSize">一次加載的數(shù)量</param> /// <param name="offset">偏移量</param> /// <returns></returns> public static List<Email> GetInbox(string userId, string pwd, string domain, int pageSize, int offset) { try { if (string.IsNullOrEmpty(userId) || string.IsNullOrEmpty(pwd) || string.IsNullOrEmpty(domain)) { throw new ArgumentNullException("當(dāng)前用戶信息為空,無法訪問exchange服務(wù)器"); } List<Email> lstEmails = new List<Email>(); _exchangeService.Credentials = new NetworkCredential(userId, pwd, domain); _exchangeService.Url = new Uri(WebConfig.ExchangeServerUrl); ItemView view = new ItemView(pageSize, offset); FindItemsResults<Item> findResults = _exchangeService.FindItems(WellKnownFolderName.Inbox, SetFilter(), view); foreach (Item item in findResults.Items) { item.Load(PropertySet.FirstClassProperties); //轉(zhuǎn)化為EmailMessage獲取 獲取郵件詳情 var currentEmail = (Microsoft.Exchange.WebServices.Data.EmailMessage)(item); List<string> ccRecipientsEmailLists = new List<string>(); List<string> bccRecipientsEmailLists = new List<string>(); foreach (var cc in currentEmail.CcRecipients) { ccRecipientsEmailLists.Add(cc.Address); } foreach (var bcc in currentEmail.BccRecipients) { bccRecipientsEmailLists.Add(bcc.Address); } lstEmails.Add(new Email() { ExchangeItemId = item.Id.ChangeKey, body = item.Body.Text, Mail_cc = string.Join(";", ccRecipientsEmailLists.ToArray()), Mail_bcc = string.Join(";", bccRecipientsEmailLists.ToArray()), Mail_from = currentEmail.From.Address, IsRead = item.IsNew, Subject = item.Subject, CreateOn = item.DateTimeCreated }); } return lstEmails; } catch (Exception ex) { throw ex; } } /// <summary> /// 根據(jù)用戶郵件地址返回用戶的未讀郵件數(shù) /// </summary> /// <param name="user"></param> /// <returns></returns> public static int GetUnReadMailCountByUserMailAddress(string userId, string pwd, string domain, string email) { int unRead = 0; try { _exchangeService.Credentials = new NetworkCredential(userId, pwd, domain); _exchangeService.Url = new Uri(WebConfig.ExchangeServerUrl); _exchangeService.ImpersonatedUserId = new Microsoft.Exchange.WebServices.Data.ImpersonatedUserId(Microsoft.Exchange.WebServices.Data.ConnectingIdType.SmtpAddress, email); unRead = Microsoft.Exchange.WebServices.Data.Folder.Bind(_exchangeService, Microsoft.Exchange.WebServices.Data.WellKnownFolderName.Inbox).UnreadCount; } catch (Exception ex) { throw ex; } return unRead; } /// <summary> /// 過濾器 /// </summary> /// <returns></returns> private static SearchFilter SetFilter() { List<SearchFilter> searchFilterCollection = new List<SearchFilter>(); //searchFilterCollection.Add(new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false)); //searchFilterCollection.Add(new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, true)); //篩選今天的郵件 SearchFilter start = new SearchFilter.IsGreaterThanOrEqualTo(EmailMessageSchema.DateTimeCreated, Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 00:00:00"))); SearchFilter end = new SearchFilter.IsLessThanOrEqualTo(EmailMessageSchema.DateTimeCreated, Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 23:59:59"))); searchFilterCollection.Add(start); searchFilterCollection.Add(end); SearchFilter filter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, searchFilterCollection.ToArray()); return filter; } /// <summary> /// 發(fā)送郵件 /// </summary> /// <param name="email"></param> /// <returns></returns> public static void SendMail(Email email, string userId, string pwd, string domain) { try { _exchangeService.Credentials = new NetworkCredential(userId, pwd, domain); _exchangeService.Url = new Uri(WebConfig.ExchangeServerUrl); //發(fā)送人 Mailbox mail = new Mailbox(email.Mail_from); //郵件內(nèi)容 EmailMessage message = new EmailMessage(_exchangeService); string[] strTos = email.Mail_to.Split(';'); //接收人 foreach (string item in strTos) { if (!string.IsNullOrEmpty(item)) { message.ToRecipients.Add(item); } } //抄送人 foreach (string item in email.Mail_cc.Split(';')) { if (!string.IsNullOrEmpty(item)) { message.CcRecipients.Add(item); } } //郵件標(biāo)題 message.Subject = email.Subject; //郵件內(nèi)容 message.Body = new MessageBody(email.body); //發(fā)送并且保存 message.SendAndSaveCopy(); } catch (Exception ex) { throw new Exception("發(fā)送郵件出錯(cuò)," + ex.Message + "\r\n" + ex.StackTrace); } } } }
總結(jié)
1. 使用Exchange協(xié)議發(fā)送郵件可以無需設(shè)置主機(jī),如需設(shè)置可通過service.url傳入IP6地址(_exchangeService.Url = new Uri(WebConfig.ExchangeServerUrl););
2. Exchange Server doesn't support the requested version 錯(cuò)誤;
message調(diào)用save等操作或發(fā)送郵件方法,報(bào)錯(cuò) Exchange Server doesn't support the requested version , 需查看提供具體Exchange Server版本(ExchangeService _exchangeService = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
以上就是C#使用Exchange實(shí)現(xiàn)發(fā)送郵件的詳細(xì)內(nèi)容,更多關(guān)于C#發(fā)送郵件的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Unity3D啟動(dòng)外部程序并傳遞參數(shù)的實(shí)現(xiàn)
這篇文章主要介紹了Unity3D啟動(dòng)外部程序并傳遞參數(shù)的實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2021-04-04Unity中的InitializeOnLoad特性實(shí)踐深入解析
這篇文章主要為大家介紹了Unity中的InitializeOnLoad特性實(shí)踐深入解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-05-05C#客戶端程序調(diào)用外部程序的3種實(shí)現(xiàn)方法
這篇文章主要給大家介紹了關(guān)于C#客戶端程序調(diào)用外部程序的3種實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2018-04-04C#使用StringBuilder實(shí)現(xiàn)高效處理字符串
這篇文章主要為大家詳細(xì)介紹了C#如何使用StringBuilder實(shí)現(xiàn)高效處理字符串,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-01-01Unity實(shí)現(xiàn)物體沿自身的任意軸向旋轉(zhuǎn)
這篇文章主要為大家詳細(xì)介紹了Unity實(shí)現(xiàn)物體沿自身的任意軸向旋轉(zhuǎn),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-01-01c# NPOI 如何在指定單元格導(dǎo)入導(dǎo)出圖片
這篇文章主要介紹了c# NPOI 如何在指定單元格導(dǎo)入導(dǎo)出圖片,幫助大家更好的理解和學(xué)習(xí)使用c#,感興趣的朋友可以了解下2021-03-03C# 手動(dòng)/自動(dòng)保存圖片的實(shí)例代碼
C# 手動(dòng)/自動(dòng)保存圖片的實(shí)例代碼,需要的朋友可以參考一下2013-03-03