【.Net】.net获取exchange service用户日历会议数据或邮箱数据

前言

近期.net项目中,客户要求在定制化页面中展示指定用户的exchange日历会议数据以及邮箱内容数据,下面将详细来说一下实现过程

 实现过程

1、所需dll

Microsoft.Exchange.WebServices    15.0.0.0

2、配置文件描述

<add key="BindIP" value="ocs-dev-ax.ocs.com" />
<add key="BindPassword" value="123456!" />
<add key="BindUserName" value="administrator" />
<add key="BindDomain" value="OCS" />

3、获取exchange service代码(初始化)

/// <summary>
        /// 获取ExchangeService
        /// </summary>
        /// <returns></returns>
        public ExchangeService getservice()
        {
            string Host = System.Configuration.ConfigurationManager.AppSettings["BindIP"];
            string BindPassword = System.Configuration.ConfigurationManager.AppSettings["BindPassword"];
            string BindUserName = System.Configuration.ConfigurationManager.AppSettings["BindUserName"];
            string BindDomain = System.Configuration.ConfigurationManager.AppSettings["BindDomain"];
            ExchangeService service = new ExchangeService();
            try
            {
                service = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
                service.Credentials = new NetworkCredential(BindUserName, BindPassword, BindDomain);
                Uri uri = new Uri("https://" + Host + "/ews/exchange.asmx");
                service.Url = uri;
                service.TraceEnabled = true;
                service.UseDefaultCredentials = false;
                service.PreAuthenticate = false;

            }
            catch (Exception ex)
            {

            }
            return service;
        }

4、操作exchange用户日历数据(获取、新增、修改、删除用户日历会议数据)

重点:如果在获取时候报错误信息:The specified folder could not be found in the store需要调用方法runPowerShell ,请参考【.Net】在.net项目中执行power shell命令
string runPSResult = runPowerShell(userName + "@" + BindDomain + ".com");

  • 查询操作
public List<AppointmentModel> SearchCalendar(string userName, DateTime StartDate, DateTime EndDate)
        {
            string BindDomain = System.Configuration.ConfigurationManager.AppSettings["BindDomain"];
            ExchangeService service = getservice();

            List<AppointmentModel> appList = new List<AppointmentModel>();
            //如果在获取时候报错误信息:The specified folder could not be found in the store需要调用方法runPowerShell
            string runPSResult = runPowerShell(userName + "@" + BindDomain + ".com");
            if (runPSResult == "")
            {

                //验证服务器证书回调自动验证
                service.TraceEnabled = true;
                ServicePointManager.ServerCertificateValidationCallback += CheckValidationResult;
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                const int NUM_APPTS = 5;
                // Initialize the calendar folder object with only the folder ID. 
                Mailbox mb = new Mailbox(userName + "@OCS.com");
                FolderId folderIdFromCalendar = new FolderId(WellKnownFolderName.Calendar, mb);
                CalendarFolder calendar = CalendarFolder.Bind(service, folderIdFromCalendar);
                // Set the start and end time and number of appointments to retrieve.
                CalendarView cView = new CalendarView(StartDate, EndDate, NUM_APPTS);
                // Limit the properties returned to the appointment's subject, start time, and end time.
                cView.PropertySet = new PropertySet(AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.End);
                // Retrieve a collection of appointments by using the calendar view.
                FindItemsResults<Appointment> appointments = calendar.FindAppointments(cView);
                foreach (Appointment app in appointments)
                {
                    AppointmentModel appointmentModel = new AppointmentModel();
                    Appointment a = Appointment.Bind(service, new ItemId(app.Id.UniqueId));
                    appointmentModel.Id = a.Id.UniqueId;
                    appointmentModel.Body = a.Body;
                    appointmentModel.Subject = a.Subject;
                    appointmentModel.StartDate = a.Start;
                    appointmentModel.EndDate = a.End;
                    appointmentModel.IsAllDayEvent = a.IsAllDayEvent;
                    appointmentModel.IsPrivate = (((Item)a).Sensitivity == Sensitivity.Private) ? true : false;
                    appointmentModel.RequiredAttendees = new List<string>();
                    foreach (Attendee required in a.RequiredAttendees)
                    {
                        appointmentModel.RequiredAttendees.Add(required.Address);
                    }
                    appointmentModel.OptionalAttendees = new List<string>();
                    foreach (Attendee optional in a.OptionalAttendees)
                    {
                        appointmentModel.OptionalAttendees.Add(optional.Address);
                    }
                    appointmentModel.IsMeeting = a.IsMeeting;
                    appointmentModel.Id = app.Id.UniqueId;
                    appointmentModel.Subject = app.Subject;
                    appointmentModel.StartDate = app.Start;
                    appointmentModel.EndDate = app.End;
                    appList.Add(appointmentModel);
                }
            }
            return appList;
        }

     
  • 添加日历会议
 private bool AddNewInviteCalendar(string userName, AppointmentModel appointmentModel, ref string id)
        {

            ExchangeService service = getservice();
            //如果在获取时候报错误信息:The specified folder could not be found in the store需要调用方法runPowerShell
            string runPSResult = runPowerShell(userName + "@" + BindDomain + ".com");

            //验证服务器证书回调自动验证
            ServicePointManager.ServerCertificateValidationCallback += CheckValidationResult;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            try
            {
                Appointment appointment = new Appointment(service);
                appointment.Subject = appointmentModel.Subject;
                appointment.Body = appointmentModel.Body;
                appointment.Start = appointmentModel.StartDate;
                appointment.End = appointmentModel.EndDate;
                appointment.IsAllDayEvent = appointmentModel.IsAllDayEvent;//全天事件
                appointment.Sensitivity = (appointmentModel.IsPrivate) ? Sensitivity.Private : Sensitivity.Normal;//是否私人,去掉是Sensitivity.Normal
                appointment.Location = appointmentModel.Location; //会议地点//20201225
                if (appointmentModel.RequiredAttendees != null && appointmentModel.RequiredAttendees.Count > 0)
                {
                    foreach (String rAttendee in appointmentModel.RequiredAttendees)
                    {
                        appointment.RequiredAttendees.Add(rAttendee);
                    }
                }
                if (appointmentModel.OptionalAttendees != null && appointmentModel.OptionalAttendees.Count > 0)
                {
                    foreach (String oAttendee in appointmentModel.OptionalAttendees)
                    {
                        appointment.OptionalAttendees.Add(oAttendee);
                    }
                }

                appointment.Save(new FolderId(WellKnownFolderName.Calendar, userName + "@OMS.com"), SendInvitationsMode.SendToAllAndSaveCopy);
                appointmentModel.Id = appointment.Id.UniqueId;
                id = appointmentModel.Id;
                return true;
            }
            catch (Exception ex)
            {
                //WriteLog("add error,subject:[" + appointmentModel.Subject + "] body:[" + appointmentModel.Body + "]msg:" + ex.ToString(), true);
                return false;
            }
        }
        
  • 修改日历会议
 private bool ModifyInviteCalendar(AppointmentModel appointmentModel)
        {
            ExchangeService service = getservice();

            ServicePointManager.ServerCertificateValidationCallback += CheckValidationResult;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            try
            {
                Appointment appointment = Appointment.Bind(service, new ItemId(appointmentModel.Id));
                if (appointment != null)
                {
                    appointment.Subject = appointmentModel.Subject;
                    appointment.Body = appointmentModel.Body;
                    appointment.StartTimeZone = TimeZoneInfo.FindSystemTimeZoneById("China Standard Time");
                    //appointment.EndTimeZone = TimeZoneInfo.FindSystemTimeZoneById("China Standard Time");
                    appointment.Start = appointmentModel.StartDate;
                    appointment.End = appointmentModel.EndDate;
                    appointment.IsAllDayEvent = appointmentModel.IsAllDayEvent;
                    appointment.Sensitivity = (appointmentModel.IsPrivate) ? Sensitivity.Private : Sensitivity.Normal;//是否私人,去掉是Sensitivity.Normal
                    appointment.Location = appointmentModel.Location;   //修改地点//20201225
                    if (appointmentModel.RequiredAttendees != null && appointmentModel.RequiredAttendees.Count > 0)
                    {
                        appointment.RequiredAttendees.Clear();
                        foreach (String rAttendee in appointmentModel.RequiredAttendees)
                        {
                            appointment.RequiredAttendees.Add(rAttendee);
                        }
                    }
                    else
                        appointment.RequiredAttendees.Clear();

                    if (appointmentModel.OptionalAttendees != null && appointmentModel.OptionalAttendees.Count > 0)
                    {
                        appointment.OptionalAttendees.Clear();
                        foreach (String oAttendee in appointmentModel.OptionalAttendees)
                        {
                            appointment.OptionalAttendees.Add(oAttendee);
                        }
                    }
                    else
                        appointment.OptionalAttendees.Clear();

                    //appointment.Sensitivity = (appointmentModel.IsPrivate) ? Sensitivity.Private : Sensitivity.Normal;//是否私人,去掉是Sensitivity.Normal
                    appointment.Update(ConflictResolutionMode.AlwaysOverwrite);
                    DateTime dt = appointment.LastModifiedTime;
                    return true;
                }
                else
                {
                    //errmsgid = "not find calendar schedule";
                    return false;
                }
            }
            catch (Exception ex)
            {

                // WriteLog("edit error,id:[" + appointmentModel.Id + "] msg:" + ex.ToString(), true);
                //errmsgid = "edit error";
                return false;
            }
        }
        
  • 删除日历会议
private bool DeleteCalendar(String id, ref string errmsgid)
        {

            ExchangeService service = getservice();

            //验证服务器证书回调自动验证
            ServicePointManager.ServerCertificateValidationCallback += CheckValidationResult;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            try
            {
                Appointment appointment = Appointment.Bind(service, new ItemId(id));
                if (appointment != null)
                {
                    appointment.Subject = appointment.Subject + "(已删除)";
                    //appointment.Body = appointment.Body.Text.Replace(appointment.Body.Text.Substring(appointment.Body.Text.IndexOf("</body>")), "(已删除)" + appointment.Body.Text.Substring(appointment.Body.Text.IndexOf("</body>")));

                    if (!String.IsNullOrEmpty(appointment.Body) && !String.IsNullOrEmpty(appointment.Body.Text))
                    {
                        appointment.Body = appointment.Body.Text.Replace(appointment.Body.Text.Substring(appointment.Body.Text.IndexOf("</body>")), "(已删除)" + appointment.Body.Text.Substring(appointment.Body.Text.IndexOf("</body>")));
                    }

                    appointment.Update(ConflictResolutionMode.AlwaysOverwrite);

                    appointment.Delete(DeleteMode.MoveToDeletedItems);
                    return true;
                }
                else
                {
                    errmsgid = "not find calendar schedule";
                    return false;
                }
            }
            catch (Exception ex)
            {
                //WriteLog("delete error,id:[" + id + "] msg:" + ex.ToString(), true);
                errmsgid = "del error";
                return false;
            }
        }
        

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一起来学吧

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值