bdjhx 发表于 2015-9-10 13:26:17

wedav读取exchange(2003)邮件信息

  第一次做webdav方法读取excahnge邮件方面的东西,将网上查找到的代码改成了.ascx控件,后台代码如下:
  

代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Data;
using System.Xml;
namespace SharePoint.Exchange2003
{
    public class unreadmailcontrol : UserControl
    {
      GridView GridView1;
      protected void Page_Load(object sender, EventArgs e)
      {
            try
            {
                GridView1 = (GridView)this.FindControl("GridView1");
                GridView1.DataSource = GetUnReadMail();
                GridView1.DataBind();
            }
            catch (Exception ex)
            {
            }
      }
      private DataTable GetUnReadMail()
      {
            string url = "http://ip/exchange/"; //指定Exchange服务器地址
            System.Net.HttpWebRequest Request;
            System.Net.WebResponse Response;
            System.Net.CredentialCache MyCredentialCache;
            string strUserName = "administrator"; //指定登录的用户名
            string strRootURI = url + strUserName.Trim() + "/收件箱/"; //得到要访问邮箱的WebDAV地址
            string strPassword = "test"; //指定该用户的密码
            string strDomain = "test"; //指定域名
            string strQuery = "";
            byte[] bytes = null;
            System.IO.Stream RequestStream = null;
            System.IO.Stream ResponseStream = null;
            XmlDocument ResponseXmlDoc = null;
            XmlNodeList HrefNodes = null;
            XmlNodeList SizeNodes = null;
            int count = 0;
            try
            {
                // 用SQL查询WebDAV返回结果中的unreadcount节点.
                //strQuery = "<?xml version=\"1.0\"?><D:searchrequest xmlns:D = \"DAV:\" >"
                // + "<D:sql>SELECT \"DAV:displayname\",\"urn:schemas:httpmail:subject\",\"urn:schemas:httpmail:unreadcount\" FROM \"" + strRootURI + "\""
                // + "</D:sql></D:searchrequest>";
                strQuery = "<?xml version=\"1.0\"?><D:searchrequest xmlns:D = \"DAV:\" >"
                   + "<D:sql>SELECT \"urn:schemas:httpmail:importance\",\"urn:schemas:httpmail:from\",\"urn:schemas:httpmail:read\",\"urn:schemas:httpmail:datereceived\",\"urn:schemas:httpmail:subject\",\"urn:schemas:httpmail:hasattachment\","
                   + "\"DAV:contentclass\",\"DAV:getcontentlength\",\"DAV:displayname\""
                   + "FROM \"" + strRootURI + "\""
                   + "WHERE \"DAV:ishidden\" = false AND \"DAV:isfolder\" = false"
                   + "</D:sql></D:searchrequest>";

                // 创建新的CredentialCache对象,构建身份凭据
                MyCredentialCache = new System.Net.CredentialCache();
                MyCredentialCache.Add(new System.Uri(strRootURI),
               "NTLM",
               new System.Net.NetworkCredential(strUserName, strPassword, strDomain)
               );
                // Create the HttpWebRequest object.
                Request = (System.Net.HttpWebRequest)HttpWebRequest.Create(strRootURI);
                // 指定HttpWebRequest的身份凭据,此处为关键所在。如果使用之前
                // 创建的MyCredentialCache,则这个身份凭据是可以从Web服务器传递
                // 到Exchange服务器的,但是这样带来的问题也很明显,就是不能够自
                // 动获取当前登录到域的用户的身份。即便已经成功登录到域,那也只
                // 能通过form再次输入用户名密码。因此,我在这里用的是
                // Request.Credentials = CredentialCache.DefaultCredentials,
                // 这样便可以获得当前用户的凭据,但是这样带来的问题便是上面提到的
                // 身份凭据无法传递的问题,解决方法请关注下篇文章。
                Request.Credentials = MyCredentialCache;
                // 指定WebDAV的SEARCH方法
                Request.Method = "SEARCH";
                // Encode the body using UTF-8.
                bytes = Encoding.UTF8.GetBytes((string)strQuery);
                // Set the content header length. This must be
                // done before writing data to the request stream.
                Request.ContentLength = bytes.Length;
                // Get a reference to the request stream.
                RequestStream = Request.GetRequestStream();
                // Write the SQL query to the request stream.
                RequestStream.Write(bytes, 0, bytes.Length);
                // Close the Stream object to release the connection
                // for further use.
                RequestStream.Close();
                // Set the content type header.
                Request.ContentType = "text/xml";
                // Send the SEARCH method request and get the
                // response from the server.
                Response = (HttpWebResponse)Request.GetResponse();
                // Get the XML response stream.
                ResponseStream = Response.GetResponseStream();
                // 创建XmlDocument对象,并获取收件箱的unreadcount节点的值
                ResponseXmlDoc = new XmlDocument();
                ResponseXmlDoc.Load(ResponseStream);
                //HrefNodes = ResponseXmlDoc.GetElementsByTagName("a:displayname");
                //SizeNodes = ResponseXmlDoc.GetElementsByTagName("d:unreadcount");
                //for (int i = 0; i < HrefNodes.Count; i++)
                //{
                //    if (HrefNodes.InnerText == "收件箱")
                //      count = int.Parse(SizeNodes.InnerText);
                //}
                //ResponseStream.Close();
                //Response.Close();
                XmlNodeList idNodes = ResponseXmlDoc.GetElementsByTagName("a:displayname");
                XmlNodeList SenderNodes = ResponseXmlDoc.GetElementsByTagName("d:from");
                XmlNodeList importanceNodes = ResponseXmlDoc.GetElementsByTagName("d:importance");
                XmlNodeList contextclassNodes = ResponseXmlDoc.GetElementsByTagName("a:contentclass");
                XmlNodeList readNodes = ResponseXmlDoc.GetElementsByTagName("d:read");
                XmlNodeList datareceiveNodes = ResponseXmlDoc.GetElementsByTagName("d:datereceived");
                XmlNodeList subjectNodes = ResponseXmlDoc.GetElementsByTagName("d:subject");
                XmlNodeList getcontentlengthNodes = ResponseXmlDoc.GetElementsByTagName("a:getcontentlength");
                XmlNodeList hasattachmentNodes = ResponseXmlDoc.GetElementsByTagName("d:hasattachment");
                XmlNodeList hrefNodes = ResponseXmlDoc.GetElementsByTagName("a:href");

                DataTable dt = new DataTable();
                dt.Columns.Add("Subject");
                dt.Columns.Add("Href");
                dt.Columns.Add("Time");
                dt.Columns["Time"].DataType = Type.GetType("System.DateTime");
                for (int j = 0; j < readNodes.Count; j++)
                {
                  //if (readNodes.InnerText == "1")continue;//只取未读邮件


                  dt.Rows.Add(subjectNodes.InnerText, hrefNodes.InnerText, DateTime.Parse(datareceiveNodes.InnerText));
                }
                ResponseStream.Close();
                Response.Close();

                return dt;
            }
            catch
            {
                return null;
            }
      }
    }
}  
  前台展示页面(.ascx)如下:
  

代码

<%@ Control Language="C#"Inherits="SharePoint.Exchange2003.unreadmailcontrol, SharePoint.Exchange2003, Version=1.0.0.0, Culture=neutral, PublicKeyToken=7da4c70ffa3a2438" %>
<style type="text/css">
      img
      {
            border-style: none;
      }
      body
      {
            font-size: 12px;
      }
      .td
      {
      }
      a
      {
            text-decoration: none;
            color: #616161;
      }
      #header
      {
            width: 225px;
            height: 20px;
            background-repeat: no-repeat;
            background-image: url(/_layouts/images/header.png);
            padding-left: 180px;
            padding-top: 4px;
      }
      #header a
      {
            color: #B88A00;
      }
      #dataTable
      {
            height: 259px;
            width: 223px;
            border-style: solid;
            border-width: 1px;
            border-color: Gray;
      }
      #mainDiv
      {
            
      }
    </style>
   
<div id="mainDiv">
      <div id="header">
            <a href="http://ip/exchange/" target="_blank">更多...</a></div>
      <div id="dataTable">
            <asp:GridView ID="GridView1" runat="server" ShowHeader="False" AutoGenerateColumns="False"
                Width="223px" RowStyle-Height="23px" RowStyle-CssClass="td" AllowPaging="True"
                BorderColor="#CCCCCC" BorderStyle="Groove">
                <PagerSettings Visible="False" />
                <RowStyle CssClass="td" Height="23px"></RowStyle>
                <Columns>
                  <asp:TemplateField ShowHeader="False">
                        <ItemTemplate>
                            <img alt="" src="/_layouts/images/email.jpg" />
                        </ItemTemplate>
                        
                  </asp:TemplateField>
                  <asp:TemplateField ShowHeader="False" ItemStyle-Height="23">
                        <ItemTemplate>
                            <div style="text-overflow: ellipsis; white-space: nowrap; overflow: hidden; width: 145px;
                              padding-left: 3px;">
                              <a id="LinkButton1" runat="server" href='<%# DataBinder.Eval(Container.DataItem, "Href") %> '
                                    target="_blank">
                                    <%# DataBinder.Eval(Container.DataItem, "Subject") %>
                              </a>
                            </div>
                        </ItemTemplate>
                        <ItemStyle Height="23px"></ItemStyle>
                  </asp:TemplateField>
                  <asp:BoundField DataField="Time" DataFormatString="{0:MM-dd}">
                        <ItemStyle Width="45px" ForeColor="Gray" Font-Names="Verdana" HorizontalAlign=" Center"
                            Font-Size="10px"></ItemStyle>
                  </asp:BoundField>
                </Columns>
            </asp:GridView>
      </div>
    </div>
  
  可以方便的以上代码封装成webpart或者扩张其功能。
  
页: [1]
查看完整版本: wedav读取exchange(2003)邮件信息