博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[C#]exchange发送,收件箱操作类
阅读量:6991 次
发布时间:2019-06-27

本文共 6022 字,大约阅读时间需要 20 分钟。

最近项目中需要用到exchange的操作,就参照msdn弄了一个简单的操作类。目前先实现了,发送邮件和拉取收件箱的功能,其他的以后在慢慢的添加。

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{    ///     /// exchange邮件客户端类    ///     public class ExChangeMailClient    {        ///         /// exchange服务对象        ///         private static ExchangeService _exchangeService = new ExchangeService(ExchangeVersion.Exchange2010_SP1);        ///         /// 获取收件箱        ///         /// 当前用户名        /// 密码        /// 域        /// 一次加载的数量        /// 偏移量        /// 
public static List
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("当前用户信息为空,无法访问exchange服务器"); } List
lstEmails = new List
(); _exchangeService.Credentials = new NetworkCredential(userId, pwd, domain); _exchangeService.Url = new Uri(WebConfig.ExchangeServerUrl); ItemView view = new ItemView(pageSize, offset); FindItemsResults
findResults = _exchangeService.FindItems(WellKnownFolderName.Inbox, SetFilter(), view); foreach (Item item in findResults.Items) { item.Load(PropertySet.FirstClassProperties);

//转化为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;            }        }        ///         /// 根据用户邮件地址返回用户的未读邮件数        ///         ///         /// 
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; } /// /// 过滤器 /// ///
private static SearchFilter SetFilter() { List
searchFilterCollection = new List
(); //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; } ///
/// 发送邮件 /// ///
///
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); //发送人 Mailbox mail = new Mailbox(email.Mail_from); //邮件内容 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); } } //邮件标题 message.Subject = email.Subject; //邮件内容 message.Body = new MessageBody(email.body); //发送并且保存 message.SendAndSaveCopy(); } catch (Exception ex) { throw new Exception("发送邮件出错," + ex.Message + "\r\n" + ex.StackTrace); } } }}

 

转载于:https://www.cnblogs.com/wolf-sun/p/5390782.html

你可能感兴趣的文章
关于CCS中一些错误的解决方法
查看>>
回归到jquery
查看>>
安卓截屏如何实现将摄像头显示画面截下来
查看>>
jquery常识
查看>>
EF中的MySql返回 DataTable公共类库
查看>>
Visual Studio 2008常见问题
查看>>
【洛谷 P4254】 [JSOI2008]Blue Mary开公司(李超线段树)
查看>>
scrapy初体验 - 安装遇到的坑及第一个范例
查看>>
OC内存管理
查看>>
C#中Split用法
查看>>
3月6日 c#语言
查看>>
[LeetCode] Surrounded Regions, Solution
查看>>
MySQL系列:数据库基本操作(1)
查看>>
cpu真实核数
查看>>
hdu1058(dp)
查看>>
android EditText与TextView几个常用的属性
查看>>
SDN第五次上机作业
查看>>
redis 重要的配置参数
查看>>
Oracle 高级编程 01 ~
查看>>
JS重点整理之JS原型链彻底搞清楚
查看>>