net读取exchange数据
大部分的参考是来自MSDN:
http://msdn.microsoft.com/en-us/library/exchangewebservices(EXCHG.80).aspx
2007版的Exchange服务器提供了webservice,我们可以方便的在.NET程序中添加该引用,然后就可以方便的实现邮件的抓取,发送,删除等功能。我测试是在控制台程序中使用该webservice,步骤如下:
1 新建一个站点,然后添加 exchange webservice 的引用, 输入邮件服务器的 OWA 地址:http://yourmailserver/EWS/Services.wsdl ,如果是在公司的内部域中,添加的过程中要求输入你的域帐号和密码。
2 添加成功以后再项目中导入该命名空间以其他必须的命名空间 ;
3 下面就是具体的代码,具体的请看注释:
发送邮件:
1 public static void CreateEmail( string userName, string passWord, string domain, string url, string mailFrom, string mailTo)
2 {
3 // Create service binding.
4 // 建立service绑定
5 ExchangeServiceBinding esb = new ExchangeServiceBinding();
6 esb.Credentials = new NetworkCredential(userName, passWord, domain);
7 esb.Url = url;
8
9 // Create the CreateItem request.
10 CreateItemType createItemRequest = new CreateItemType();
11
12 // Specifiy how the created items are handled
13 // 如何处理邮件
14 createItemRequest.MessageDisposition = MessageDispositionType.SendAndSaveCopy;
15 createItemRequest.MessageDispositionSpecified = true ;
16
17 // Specify the location of sent items.
18 createItemRequest.SavedItemFolderId = new TargetFolderIdType();
19 DistinguishedFolderIdType sentitems = new DistinguishedFolderIdType();
20 sentitems.Id = DistinguishedFolderIdNameType.sentitems;
21 createItemRequest.SavedItemFolderId.Item = sentitems;
22
23 // Create the array of items.
24 createItemRequest.Items = new NonEmptyArrayOfAllItemsType();
25
26 // Create a single e-mail message.
27 // 新建一封邮件message对象
28 MessageType message = new MessageType();
29 message.Subject = " Tommy Test " ;
30 message.Body = new BodyType();
31 message.Body.BodyType1 = BodyTypeType.Text;
32 message.Body.Value = " This is tommy's test use exchange webservice " ;
33 message.ItemClass = " IPM.Note " ;
34 message.Sender = new SingleRecipientType();
35 message.Sender.Item = new EmailAddressType();
36 message.Sender.Item.EmailAddress = mailFrom;
37 message.ToRecipients = new EmailAddressType[ 1 ];
38 message.ToRecipients[ 0 ] = new EmailAddressType();
39 message.ToRecipients[ 0 ].EmailAddress = mailTo;
40 message.Sensitivity = SensitivityChoicesType.Normal;
41
42 // Add the message to the array of items to be created.
43 createItemRequest.Items.Items = new ItemType[ 1 ];
44 createItemRequest.Items.Items[ 0 ] = message;
45
46 try
47 {
48 // Send the request to create and send the e-mail item, and get the response.
49 CreateItemResponseType createItemResponse = esb.CreateItem(createItemRequest);
50
51 // Determine whether the request was a success.
52 if (createItemResponse.ResponseMessages.Items[ 0 ].ResponseClass == ResponseClassType.Error)
53 {
54 throw new Exception(createItemResponse.ResponseMessages.Items[ 0 ].MessageText);
55 }
56 else
57 {
58 Console.WriteLine( " Item was created " );
59 Console.ReadLine();
60 }
61 }
62 catch (Exception e)
63 {
64 Console.WriteLine(e.Message);
65 Console.ReadLine();
66 }
67 }
抓取以及删除邮件:
1 public static void GetMailMessage( string userName, string passWord, string domain, string url)
2 {
3 // 绑定exchange服务器
4 ExchangeServiceBinding exchangeServer = new ExchangeServiceBinding();
5 ICredentials creds = new NetworkCredential(userName, passWord, domain);
6
7 // 建立信任连接
8 exchangeServer.Credentials = creds;
9 exchangeServer.Url = url;
10
11 // 定义邮件的收件箱
12 DistinguishedFolderIdType[] folderIDArray = new DistinguishedFolderIdType[ 1 ];
13 folderIDArray[ 0 ] = new DistinguishedFolderIdType();
14 folderIDArray[ 0 ].Id = DistinguishedFolderIdNameType.inbox;
15
16 PathToUnindexedFieldType ptuftDisplayName = new PathToUnindexedFieldType();
17 ptuftDisplayName.FieldURI = UnindexedFieldURIType.folderDisplayName;
18
19 PathToExtendedFieldType pteftComment = new PathToExtendedFieldType();
20 pteftComment.PropertyTag = " 0x3004 " ; // PR_COMMENT
21 pteftComment.PropertyType = MapiPropertyTypeType.String;
22
23 // 定义GetFolderType对象,设置相应属性
24 GetFolderType myfoldertype = new GetFolderType();
25 myfoldertype.FolderIds = folderIDArray;
26 myfoldertype.FolderShape = new FolderResponseShapeType();
27 myfoldertype.FolderShape.BaseShape = DefaultShapeNamesType.IdOnly;
28 myfoldertype.FolderShape.AdditionalProperties = new BasePathToElementType[ 2 ];
29 myfoldertype.FolderShape.AdditionalProperties[ 0 ] = ptuftDisplayName;
30 myfoldertype.FolderShape.AdditionalProperties[ 1 ] = pteftComment;
31
32 // 获取服务器中的文件夹的集合
33 GetFolderResponseType myFolder = exchangeServer.GetFolder(myfoldertype);
34
35 // 获取收件箱
36 FolderInfoResponseMessageType firmtInbox =
37 (FolderInfoResponseMessageType)myFolder.ResponseMessages.Items[ 0 ];
38
39 // 显示收件箱
40 Console.WriteLine( string .Format( " got folder: {0} " , firmtInbox.Folders[ 0 ].DisplayName));
41
42
43 PathToUnindexedFieldType ptuftSubject = new PathToUnindexedFieldType();
44 ptuftSubject.FieldURI = UnindexedFieldURIType.itemSubject;
45
46 PathToUnindexedFieldType ptuftBody = new PathToUnindexedFieldType();
47 ptuftBody.FieldURI = UnindexedFieldURIType.itemAttachments;
48
49 PathToExtendedFieldType pteftFlagStatus = new PathToExtendedFieldType();
50 pteftFlagStatus.PropertyTag = " 0x1090 " ; // PR_FLAG_STATUS
51 pteftFlagStatus.PropertyType = MapiPropertyTypeType.Integer;
52
53 // 定义FindItemType对象,准备获取收件箱中的集合
54 FindItemType findItemRequest = new FindItemType();
55 findItemRequest.Traversal = ItemQueryTraversalType.Shallow;
56 findItemRequest.ItemShape = new ItemResponseShapeType();
57 findItemRequest.ItemShape.BaseShape = DefaultShapeNamesType.AllProperties;
58
59
60 findItemRequest.ParentFolderIds = new FolderIdType[ 1 ];
61 findItemRequest.ParentFolderIds[ 0 ] = firmtInbox.Folders[ 0 ].FolderId;
62
63 // 获取邮件
64 FindItemResponseType firt = exchangeServer.FindItem(findItemRequest);
65
66 // 循环迭代每一封邮件
67 foreach (FindItemResponseMessageType firmtMessage in firt.ResponseMessages.Items)
68 {
69 // 如果包含邮件,显示出来
70 if (firmtMessage.RootFolder.TotalItemsInView > 0 )
71 {
72 // 循环迭代每一封邮件详细信息
73 foreach (ItemType it in ((ArrayOfRealItemsType)firmtMessage.RootFolder.Item).Items)
74 {
75 Console.WriteLine( string .Format( " 邮件标题: {0} " , it.Subject));
76 Console.WriteLine( string .Format( " 发件人: {0} " ,((MessageType)(it)).From.Item.Name));
77 Console.WriteLine( string .Format( " 收件人: {0} " , it.DisplayTo));
78 Console.WriteLine( string .Format( " 抄送: {0} " , it.DisplayCc));
79 Console.WriteLine( string .Format( " 大小: {0} " , it.Size.ToString()));
80 Console.WriteLine( string .Format( " 重要性: {0} " , it.Importance.ToString()));
81 Console.WriteLine( string .Format( " 是否已读: {0} " , ((MessageType)(it)).IsRead.ToString()));
82 Console.WriteLine( string .Format( " 是否有附件: {0} " , it.HasAttachments.ToString()));
83 // Console.WriteLine(string.Format("发送时间:{0}", it.DateTimeSent.ToString()));
84 Console.WriteLine( string .Format( " 接收时间: {0} " , it.DateTimeReceived.ToString()));
85
86
87 // 通过GetItemType对象来得到邮件的正文
88 GetItemType getItemRequest = new GetItemType();
89 // 设置必要的属性
90 getItemRequest.ItemIds = new BaseItemIdType[ 1 ];
91 getItemRequest.ItemIds[ 0 ] = (BaseItemIdType)it.ItemId;
92 getItemRequest.ItemShape = new ItemResponseShapeType();
93 getItemRequest.ItemShape.BaseShape = DefaultShapeNamesType.AllProperties;
94 getItemRequest.ItemShape.IncludeMimeContent = true ;
95
96 // 获得服务器的相应
97 GetItemResponseType getItemResponse = exchangeServer.GetItem(getItemRequest);
98
99 // 得到邮件体
100 ItemInfoResponseMessageType getItemResponseMessage =
101 getItemResponse.ResponseMessages.Items[ 0 ] as
102 ItemInfoResponseMessageType;
103
104 // 显示邮件正文
105 Console.WriteLine( " 邮件格式:{0} " , getItemResponseMessage.Items.Items[ 0 ].Body.BodyType1);
106 Console.WriteLine( string .Format( " 正文:{0} " , getItemResponseMessage.Items.Items[ 0 ].Body.Value));
107
108 // 获取当前邮件的附件集合
109 if (getItemResponseMessage.Items.Items[ 0 ].HasAttachments)
110 {
111 AttachmentType[] attachments = getItemResponseMessage.Items.Items[ 0 ].Attachments;
112
113 // 循环获取当前邮件的每一个附件
114 for ( int i = 0 ; i <= attachments.Length - 1 ;i ++ )
115 {
116 // 定义GetAttachmentType,设置相应的属性,进行模式验证来获取附件
117 GetAttachmentType getAttachment = new GetAttachmentType();
118 RequestAttachmentIdType[] attachmentIDArry = new RequestAttachmentIdType[ 1 ];
119 attachmentIDArry[ 0 ] = new RequestAttachmentIdType();
120 attachmentIDArry[ 0 ].Id = attachments[i].AttachmentId.Id;
121 getAttachment.AttachmentIds = attachmentIDArry;
122 getAttachment.AttachmentShape = new AttachmentResponseShapeType();
123
124 // 获取附件
125 GetAttachmentResponseType getAttachmentResponse = exchangeServer.GetAttachment(getAttachment);
126
127 // 返回服务器的响应对象
128 AttachmentInfoResponseMessageType responseMessage = getAttachmentResponse.ResponseMessages.Items[ 0 ] as AttachmentInfoResponseMessageType;
129 if (responseMessage != null )
130 {
131 // 没有异常,显示附件信息
132 if (responseMessage.ResponseClass == ResponseClassType.Success && responseMessage.Attachments != null
133 && responseMessage.Attachments.Length > 0 )
134 {
135 AttachmentType attachment = responseMessage.Attachments[ 0 ];
136 Console.WriteLine( " 附件名:{0}\n " , attachment.Name);
137 // Console.WriteLine("附件类型:{0}\n", attachment.ContentId);
138 }
139 }
140 }
141 }
142
143 // 删除当前邮件
144 DeleteItemType deleteItem = new DeleteItemType();
145 deleteItem.ItemIds = new BaseItemIdType[ 1 ];
146
147 // 将要删除邮件的ID,changekey赋值给ItemIdType对象
148 ItemIdType itemIDType = new ItemIdType();
149 itemIDType.Id = it.ItemId.Id;
150 itemIDType.ChangeKey = it.ItemId.ChangeKey;
151
152 deleteItem.ItemIds[ 0 ] = itemIDType;
153
154 // 执行删除
155 DeleteItemResponseType deleteResponse = exchangeServer.DeleteItem(deleteItem);
156
157 // 删除成功
158 if (deleteResponse.ResponseMessages.Items.Length > 0 && deleteResponse.ResponseMessages.Items[ 0 ].ResponseClass == ResponseClassType.Success)
159 {
160 Console.WriteLine( " 删除成功 " );
161 }
162
163 }
164 }
165
166 }
167 }
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/thy822/archive/2010/09/09/5873244.aspx
第一次做webdav方法读取excahnge邮件方面的东西,将网上查找到的代码改成了.ascx控件,后台代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
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[i].InnerText == "收件箱")
// count = int.Parse(SizeNodes[i].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[j].InnerText == "1")continue;//只取未读邮件
dt.Rows.Add(subjectNodes[j].InnerText, hrefNodes[j].InnerText, DateTime.Parse(datareceiveNodes[j].InnerText));
}
ResponseStream.Close();
Response.Close();
return dt;
}
catch
{
return null;
}
}
}
}
前台展示页面(.ascx)如下:
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
<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>