exchange收件箱操作类实践指南
诗诗 2018-03-14 来源 :网络 阅读 1173 评论 0

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

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

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服务对象

        /// </summary>

        private static ExchangeService _exchangeService = new ExchangeService(ExchangeVersion.Exchange2010_SP1);

        /// <summary>

        /// 获取收件箱

        /// </summary>

        /// <param name="userId">当前用户名</param>

        /// <param name="pwd">密码</param>

        /// <param name="domain">域</param>

        /// <param name="pageSize">一次加载的数量</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("当前用户信息为空,无法访问exchange服务器");

                }

                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);

                    lstEmails.Add(new Email()

                    {

                        ExchangeItemId = item.Id.ChangeKey,

                        body = item.Body.Text,

                        Mail_cc = item.DisplayCc,

                        Mail_from = item.LastModifiedName,

                        IsRead = item.IsNew,

                        Subject = item.Subject,

                        CreateOn = item.DateTimeCreated

                    });

                }

                return lstEmails;

            }

            catch (Exception ex)

            {

 

                throw ex;

            }

 

        }

 

        /// <summary>

        /// 根据用户邮件地址返回用户的未读邮件数

        /// </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>

        /// 发送邮件

        /// </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);

                //发送人

                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);

            }

        }

    }

}

 

希望这篇文章可以帮助到你。总之,同学们,你想要的职坐标IT频道都能找到!


本文由 @诗诗 发布于职坐标。未经许可,禁止转载。
喜欢 | 0 不喜欢 | 0
看完这篇文章有何感觉?已经有0人表态,0%的人喜欢 快给朋友分享吧~
评论(0)
后参与评论

您输入的评论内容中包含违禁敏感词

我知道了

助您圆梦职场 匹配合适岗位
验证码手机号,获得海同独家IT培训资料
选择就业方向:
人工智能物联网
大数据开发/分析
人工智能Python
Java全栈开发
WEB前端+H5

请输入正确的手机号码

请输入正确的验证码

获取验证码

您今天的短信下发次数太多了,明天再试试吧!

提交

我们会在第一时间安排职业规划师联系您!

您也可以联系我们的职业规划师咨询:

小职老师的微信号:z_zhizuobiao
小职老师的微信号:z_zhizuobiao

版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
 沪公网安备 31011502005948号    

©2015 www.zhizuobiao.com All Rights Reserved

208小时内训课程