读取exchange邮件的未读数(转载)

protected void Page_Load(object sender, EventArgs e)
        {
            Response.Write("administrator的未读邮件数是:" + UnReadCount("administrator@domainname"));
        }
        int UnReadCount(string userMailAddress)
        {
            EwsConfig config = new EwsConfig();
            config.ExchangeVersion = ExchangeVersion.Exchange2010;
            //config.ExchangeVersion = ExchangeVersionType.Exchange2010_SP2;// ExchangeVersion.Exchange2010_SP3;
            config.EWSServiceUrl = "https://1.1.100.130/EWS/exchange.asmx";
            config.ExchangeAdministrator = "administrator";
            config.ExchangeAdministratorPassword = "password";
            config.DomainName = "domainname";
            config.OtherUserName = "";
            //下面这句屏蔽服务器证书验证,防止页面报“根据验证过程,远程证书无效”的错误
            ServicePointManager.ServerCertificateValidationCallback =
            delegate(Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; };
            ExchangeService service = new ExchangeService(config.ExchangeVersion);

            service.Credentials = new NetworkCredential(config.ExchangeAdministrator, config.ExchangeAdministratorPassword, config.DomainName);
            service.Url = new Uri(config.EWSServiceUrl);
            //前提打开Exchange 2010服务器在命令行中输入:
            //New-ManagementRoleAssignment -Name:impersonationAssignmentName -Role:ApplicationImpersonation -User:
            service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, config.OtherUserName);
            ImpersonatedUserId imperson = new ImpersonatedUserId();
            imperson.IdType = ConnectingIdType.SmtpAddress;
            imperson.Id = userMailAddress;
            service.ImpersonatedUserId = imperson;
            int unRead = Folder.Bind(service, WellKnownFolderName.Inbox).UnreadCount;
            return unRead;
            //HttpContext.Current.Response.Write(config.OtherUserName + "未读邮件数:" + unRead);
        }
        public struct EwsConfig
        {
            //ExchangeServiceBinding ser = new ExchangeServiceBinding();

            public ExchangeVersion ExchangeVersion;
            //public ExchangeVersionType ExchangeVersion;
            public string EWSServiceUrl;
            public string ExchangeAdministrator;
            public string ExchangeAdministratorPassword;
            public string DomainName;
            public string OtherUserName;

        }

 

以下是方法:

#region 给本人插入会议日程

using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using System.Net.Mail;
using System.Net.Mime;
using System.Net;
using System.Text;
using System.Data.SqlClient;
using System.IO;
using System.Xml;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;


        public void CreateAppointment(ExchangeServiceBinding esb, string sub, string roommail, string location, DateTime datefrom, DateTime dateto,string bodyvalue)
        {
            // Create the appointment.
            CalendarItemType appointment = new CalendarItemType();
            // Add item properties to the appointment.
            appointment.Body = new BodyType();
            appointment.Body.BodyType1 = BodyTypeType.Text;
            appointment.Body.Value = bodyvalue;//"Agenda Items.";
            //appointment.Categories = new string[] { "Category1", "Category2" };
            appointment.Importance = ImportanceChoicesType.High;
            appointment.ImportanceSpecified = true;
            appointment.ItemClass = "IPM.Appointment";
            appointment.Subject = sub;
            // Add an attendee

            MailAddressCollection mc = GetrMailAddressList();
            AttendeeType[] rAtt = new AttendeeType[mc.Count];
            for (int ii = 0; ii < rAtt.Length; ii++)
            {
                EmailAddressType eat = new EmailAddressType();
                eat.EmailAddress = mc[ii].Address;
                eat.Name = mc[ii].DisplayName;
                AttendeeType att = new AttendeeType();
                att.Mailbox = eat;
                rAtt[ii] = att;
            }
            //EmailAddressType eat1 = new EmailAddressType();
            //eat1.EmailAddress = "第一个与会者邮箱地址";
            //eat1.Name = "姓名";
            //AttendeeType at1 = new AttendeeType();
            //at1.Mailbox = eat1;

            //EmailAddressType eat2 = new EmailAddressType();
            //eat2.EmailAddress = "第一二个与会者邮箱地址";
            //eat2.Name = "姓名";
            //AttendeeType at2 = new AttendeeType();
            //at2.Mailbox = eat2;
          
            //AttendeeType[] rAtt = new AttendeeType[2];
            //rAtt[0] = at1;
            //rAtt[1] = at2;
            appointment.RequiredAttendees = rAtt;

            //add meeting room attendee
            EmailAddressType meetingRoom = new EmailAddressType();
            meetingRoom.EmailAddress = roommail ;// "会议室邮箱地址";
            meetingRoom.Name =  location ;
            AttendeeType meetingType = new AttendeeType();
            meetingType.Mailbox = meetingRoom;
            AttendeeType[] meetingTypeList = new AttendeeType[1];
            meetingTypeList[0] = meetingType;
            appointment.Resources = meetingTypeList;
            appointment.Location = location;
            // Add calendar properties to the appointment.
            appointment.Start = datefrom;
            appointment.StartSpecified = true;
            appointment.End = dateto;
            appointment.EndSpecified = true;

            // Identify the destination folder that will contain the appointment.
            DistinguishedFolderIdType folder = new DistinguishedFolderIdType();
            folder.Id = DistinguishedFolderIdNameType.calendar;

            // Create the array of items that will contain the appointment.
            NonEmptyArrayOfAllItemsType arrayOfItems = new NonEmptyArrayOfAllItemsType();
            arrayOfItems.Items = new ItemType[1];

            // Add the appointment to the array of items.
            arrayOfItems.Items[0] = appointment;

            // Create the CreateItem request.
            CreateItemType createItemRequest = new CreateItemType();
            // The SendMeetingInvitations attribute is required for calendar items.
            //createItemRequest.SendMeetingInvitations = CalendarItemCreateOrDeleteOperationType.SendToNone;
            createItemRequest.SendMeetingInvitations = CalendarItemCreateOrDeleteOperationType.SendToAllAndSaveCopy;
            createItemRequest.SendMeetingInvitationsSpecified = true;
            // Add the destination folder to the CreateItem request.
            createItemRequest.SavedItemFolderId = new TargetFolderIdType();
            createItemRequest.SavedItemFolderId.Item = folder;
            // Add the items to the CreateItem request.
            createItemRequest.Items = arrayOfItems;
            try
            {
                // Send the request and get the response.
                CreateItemResponseType createItemResponse = esb.CreateItem(createItemRequest);
                // Get the response messages.
                ResponseMessageType[] rmta = createItemResponse.ResponseMessages.Items;
                foreach (ResponseMessageType rmt in rmta)
                {
                    ArrayOfRealItemsType itemArray = ((ItemInfoResponseMessageType)rmt).Items;
                    ItemType[] items = itemArray.Items;

                    // Get the item identifier and change key for each item.
                    foreach (ItemType item in items)
                    {
                        Console.WriteLine("Item identifier: " + item.ItemId.Id);
                        Console.WriteLine("Item change key: " + item.ItemId.ChangeKey);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error Message: " + e.Message);
            }
        }
        //应答会议邀请:

        //应答会议邀请
        public static void AcceptItem(ExchangeServiceBinding esb, string meetingID)
        {
            // Create the request.
            CreateItemType request = new CreateItemType();

            // Set the message disposition on the request.
            request.MessageDisposition = MessageDispositionType.SendAndSaveCopy;
            request.MessageDispositionSpecified = true;

            // Create the AcceptItem response object.
            AcceptItemType acceptItem = new AcceptItemType();

            // Identify the meeting request to accept.
            acceptItem.ReferenceItemId = new ItemIdType();
            acceptItem.ReferenceItemId.Id = meetingID;

            // Add the AcceptItem response object to the request.
            request.Items = new NonEmptyArrayOfAllItemsType();
            request.Items.Items = new ItemType[1];
            request.Items.Items[0] = acceptItem;
            // Send the request and get the response.
            CreateItemResponseType response = esb.CreateItem(request);

            ArrayOfResponseMessagesType aormt = response.ResponseMessages;
            ResponseMessageType[] rmta = aormt.Items;
            foreach (ResponseMessageType rmt in rmta)
            {
                ItemInfoResponseMessageType iirmt = (rmt as ItemInfoResponseMessageType);
                if (iirmt.ResponseClass == ResponseClassType.Success)
                {
                    Console.WriteLine("Successfully accepted meeting");
                }
            }
        }

        private ExchangeServiceBinding esb;

        public static ExchangeServiceBinding GetExchangeService(ExchangeSession session)
        {
            ExchangeServiceBinding esb = new ExchangeServiceBinding();

            //esb.Credentials = session.GetNetworkCredential();
            string ocsuser = System.Configuration.ConfigurationManager.AppSettings["OcsUser"];
            string password = System.Configuration.ConfigurationManager.AppSettings["password"];
            string domain = System.Configuration.ConfigurationManager.AppSettings["Domain"];
            string ExchangeServer = System.Configuration.ConfigurationManager.AppSettings["ExchangeServer"];
            esb.Credentials = session.GetNetCS(ocsuser, password, domain );
            esb.Url = ExchangeServer; //session.Url;

            ServicePointManager.ServerCertificateValidationCallback += CheckCert;

            ExchangeImpersonationType imp = new ExchangeImpersonationType();
            imp.ConnectingSID = new ConnectingSIDType { PrimarySmtpAddress = session.Impersonation };
            esb.ExchangeImpersonation = imp;

            FindItemType fit = new FindItemType();
            fit.ItemShape = new ItemResponseShapeType { BaseShape = DefaultShapeNamesType.Default };
            fit.ParentFolderIds = new DistinguishedFolderIdType[]
            {
                new DistinguishedFolderIdType{ Id = DistinguishedFolderIdNameType.calendar }
            };

            fit.Traversal = ItemQueryTraversalType.Shallow;

            FindItemResponseType firt = esb.FindItem(fit);

            fit.Traversal = ItemQueryTraversalType.Shallow;

 

            return esb;
        }

        protected static bool CheckCert(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }

        public void ExchangeOperation(string userMail)
        {
            //string unUserName = ConfigurationManager.AppSettings["UserName"];
            //string pnPassWord = ConfigurationManager.AppSettings["Password"];
            //string dnDomain = ConfigurationManager.AppSettings["Domain"];
            //string url = ConfigurationManager.AppSettings["Url"];

            //ExchangeImpersonationType Impersonation = new ExchangeImpersonationType();
            //Impersonation.ConnectingSID = new ConnectingSIDType();

            //esb = new ExchangeServiceBinding();
            //esb.Credentials = new System.Net.NetworkCredential(unUserName, pnPassWord, dnDomain);
            //esb.Url = url;
            //esb.ExchangeImpersonation = Impersonation;

            ExchangeSession m_Session = new ExchangeSession(userMail);
            try
            {
                esb = GetExchangeService(m_Session);
            }
            catch (Exception ex)
            {
                string strError = ex.Message;
            }
        }
        #endregion

这样使用

    //给本人差日程 20110419解决自己发的会议邀请,自己的日历看不到日程的问题
            ExchangeOperation(organigerEmail);//发起者的邮箱
            CreateAppointment(esb, meeting.Subject, organigerEmail , roomAddress, startTime, endTime, content.Text.Trim() );

webconfig配置:

  <!-- exchange配置-->
    <add key="ExchangeServer" value="https://10.0.8.13/EWS/Exchange.asmx"/>
    <add key="OcsUser" value="ocsuser"/>
    <add key="Domain" value="sinooceanland.com"/>
    <add key="password" value="password"/>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/266975.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

嵌入式Linux下Qt的中文显示

一般情况下&#xff0c;嵌入式Qt界面需要中文显示&#xff0c;下面总结自己在项目中用到的可行的办法 1&#xff0c;下载一种中文简体字体&#xff0c;比如我用的是”方正准圆简体“&#xff0c;把字体文件放在ARM开发板系统的Qt字库中&#xff0c;即/usr/lib/fonts下 2&#x…

Robot Framework + Selenium library + IEDriver环境搭建

转载&#xff1a;https://www.cnblogs.com/Ming8006/p/4998492.html#c.d 目录&#xff1a; 1 安装文件准备2 Robot框架结构3 环境搭建 3.1 安装Python 3.2 安装Robot Framework 3.3 安装wxPython 3.4 安装RIDE 3.5 安装Selenium2Library 3.6 安装IEDriverServer 1 安装文…

php静态地图api,静态图API | 百度地图API SDK

百度地图静态图API&#xff0c;可实现将百度地图以图片形式嵌入到您的网页中。您只需发送HTTP请求访问百度地图静态图服务&#xff0c;便可在网页上以图片形式显示您的地图。静态图API较之JavaScript API载入的动态网站&#xff0c;既能满足基本的地图信息浏览&#xff0c;又能…

[XMOVE自主设计的体感方案] XMove Studio管理系统(二)应用开发API简要介绍

一. XMove的开放式应用开发框架简介 XMove4.0以开放式的结构满足扩展性的要求。所有无线协议&#xff0c;底层算法和控制逻辑全部上移到PC端。节点只根据接受的控制逻辑返回传感器数据。新的架构使得开发新应用非常方便。 本节将主要介绍XMove应用开发API及其使用。 二. 注册新…

搭建服务器Apache+PHP+MySql需要注意的问题

参见https://www.cnblogs.com/bytebull/p/7927542.html 一、软件下载的都是用zip压缩文件&#xff0c;三个软件均需手动配置&#xff0c;若想省事&#xff0c;可考虑phpstudy&#xff0c;一键安装。 我的服务器文件目录&#xff1a; 二、安装PHP时需注意&#xff0c;新版本的PH…

php行为日志,利用ThinkPHP的行为扩展做系统日志

1&#xff1a;模块配置&#xff1a;return array(action_end > array(Admin\\Behaviors\\LogBehavior),);2&#xff1a;数据库建表&#xff1a;create table logs(id int(11) primary key auto_increment,url char(30) not null,operator int(11) not null,description char…

nagios搭建(一):nagios3.2的搭建

此文章的大多地方采用的是elain的博客内容&#xff1a;http://elain.blog.51cto.com/3339379/711549小部分内容是自己的从别的文章总结过来的&#xff0c;已经试验过了1.需要的软件包&#xff1a;nagios-3.2.0.tar.gz nagios的主软件包nagios-cn-3.2.0.tar.…

0530JavaScript基础2

常用内置对象 所谓内置对象就是ECMAScript提供出来的一些对象&#xff0c;我们知道对象都是有相应的属性和方法 数组Array&#xff08;部分相当于列表&#xff09; 1.数组的创建方式 var colors [red,color,yellow]; 使用构造函数&#xff08;后面会讲&#xff09;的方式创建 …

html php获取post数据格式,html - php文件无法得到POST过来的数据

php文件无法得到POST过来的数据&#xff0c;通过$_SERVER得到如下Array([HOSTNAME] > localhost.localdomain[PATH] > /usr/local/bin:/usr/bin:/bin[TMP] > /tmp[TMPDIR] > /tmp[TEMP] > /tmp[OSTYPE] >[MACHTYPE] >[MALLOC_CHECK_] > 2[USER] > w…

.net mvc 超过了最大请求长度 限制文件上传大小

在我们的项目中遇到"超过了最大请求长度"如下图所示,是因为IIS默认请求长度4M,当请求长度大于这个值的时候报错,下面是解决方案. 解决方案:修改web.config文件 1、注意在mvc中有两个web.config文件&#xff0c;如下图&#xff0c;一个位于Views下&#xff0c;是用来控…

ubuntu php 树莓派,树莓派3 安装ROS环境(ubuntu mate 16.04+kinetic)

1.刷系统下载ubuntu-mate-16.04镜像下载页面 https://ubuntu-mate.org/download/点击下载64位ubuntu-mate-16.04-desktop-armhf-raspberry-pi2.安装镜像树莓派3-系统安装-Windows下利用Win32DiskImager进行系统安装3.设置网络连接网线&#xff0c;使用DHCP自动获取IP地址和DNS。…

Android AlertDialog学习

1. 有两个按钮的对话框 Builder buildernew AlertDialog.Builder(AlertDialogActivity.this); builder.setIcon(android.R.drawable.btn_plus); builder.setTitle("btnplus"); builder.setMessage("去不去&#xff1f;"); builder.setPositiveButton("…

分布式之缓存击穿

什么是缓存击穿 在谈论缓存击穿之前&#xff0c;我们先来回忆下从缓存中加载数据的逻辑&#xff0c;如下图所示 因此&#xff0c;如果黑客每次故意查询一个在缓存内必然不存在的数据&#xff0c;导致每次请求都要去存储层去查询&#xff0c;这样缓存就失去了意义。如果在大流量…

php为什么都不想去二次开发,php学习误区:不要盲目的去读程序

最近感到很郁闷&#xff0c;细数了一下自己读过的程序&#xff0c;真的是多之又多&#xff0c;比如比较流行的有&#xff1a;织梦系统(dedecms) php168phpcms ,论坛类的 discuz phpwind还有现在用的wordpress程序自己都读过&#xff0c;但是朋友问你一个关于这几个系统的几个函…

(转)VS2010 快捷键

之前写代码很少用到快捷键&#xff0c;感觉用鼠标也一样&#xff0c;但是还是觉得能熟练用快捷键的人很牛一样的&#xff0c;相信很多人也有我一样的想法的&#xff0c;现在我还是觉得记些快捷键还是很有必要的(或者是为了看起来更牛点吧 )&#xff0c; 所以这样转载下VS2010快…

Unity按钮禁用和变灰

this.GetComponent<Button>().enabled false;//禁用按钮 如果需要将按钮变灰&#xff0c;则需要另外处理最近才发现一个禁用和变灰的按钮&#xff0c;这几年的代码我踏马真是白写了 this.GetComponent<Button>().interactable false;//禁用和变灰转载于:https://…

yii2 php反射,Yii2.0-advanced-3—为yii2添加后台模板adminlte和权限组件yii2-adm

一、yii2-adminlte-assetadminlte一款基于bootstrap的响应模块。yii2-adminlte-asset更是一款基于yii2框架进行开发的后台主题模版。1、安装(安装前先运行composer self-update)composer require dmstr/yii2-adminlte-asset "2.*"等待几分钟完成后&#xff0c;拷贝 v…

Qt实现延时sleep函数功能

/*函数名&#xff1a;sleep()参 数&#xff1a; msec - 单位为毫秒描 述&#xff1a; 延时功能 */bool Test::sleep(unsigned int msec) {QTime dieTime QTime::currentTime().addMSecs(msec);while (QTime::currentTime() < dieTime){QCoreApplication::processEvents…

矩阵位移法matlab编程,矩阵位移法_MATLAB_GUI.doc

Matrix_Displacement_Method——by MATLAB GUIPAGE58 / NUMPAGES64yanfeng39zju.edu.cn《结构力学》课程设计之矩阵位移法——MATLAB GUI实现姓名&#xff1a;郑延丰学号&#xff1a;3061211039班级&#xff1a;土木0602指导老师&#xff1a;陈水福日期&#xff1a;2009年3月30…

centos 6.2 vnc

安装vncserver服务端和客户端端 yum install tigervnc tigervnc-server -y 安装fontforge&#xff08;如果不安装fontforge&#xff0c;vncviewer客户端连接上来时&#xff0c;文字会变成方块。&#xff09; yum install fontforge -y 安装桌面 yum groupinstall Desktop -y …