博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C#调用ExchangeWebService发送邮件、查询日程、查询用户已使用邮箱空间
阅读量:6002 次
发布时间:2019-06-20

本文共 12958 字,大约阅读时间需要 43 分钟。

using System;

using System.Net;
using System.Collections.Generic;
using EWS;
using MailClient;

namespace ExchangeWs {

public class ExchangeWs {
private ExchangeServiceBinding esb = null;
private GetExchangeSetting ExchangeSetting = new GetExchangeSetting();

public ExchangeWs(string userAccount, string password, string domain, string url) {

esb = new ExchangeServiceBinding();
esb.Credentials = new NetworkCredential(userAccount, password, domain);
if (esb.RequestServerVersionValue == null) {
esb.RequestServerVersionValue = new RequestServerVersion();
esb.RequestServerVersionValue.Version = ExchangeVersionType.Exchange2007_SP1;
}
esb.Url = url;
}

#region GetOWAId

public string GetOWAId(string EWSId, string mailAddress) {
// Create the request.
ConvertIdType request = new ConvertIdType();
request.SourceIds = new AlternateIdType[1];
request.SourceIds[0] = new AlternateIdType();

// Convert from the Exchange Web Services identifier to an Outlook Web Access identifier.

request.SourceIds[0].Format = IdFormatType.EwsId;
(request.SourceIds[0] as AlternateIdType).Id = EWSId;
(request.SourceIds[0] as AlternateIdType).Mailbox = mailAddress;// "TestUser1@cqyz.cn";
request.DestinationFormat = IdFormatType.OwaId;

 

string result = null;

try {

// Send the ConvertIdType request and get the response.
ConvertIdResponseType response = esb.ConvertId(request);
ArrayOfResponseMessagesType aormt = response.ResponseMessages;
ResponseMessageType[] rmta = aormt.Items;

// Check each response message.

if (rmta != null && rmta.Length > 0) {
ConvertIdResponseMessageType resp = (ConvertIdResponseMessageType)rmta[0];
if (resp != null) {
if (resp.ResponseClass == ResponseClassType.Success) {
ConvertIdResponseMessageType cirmt = (resp as ConvertIdResponseMessageType);
AlternateIdType myId = (cirmt.AlternateId as AlternateIdType);

string format = myId.Format.ToString();

string identifier = myId.Id;
string mailbox = myId.Mailbox;

result = identifier;

}
}
}
} catch {
}
return result;
}
#endregion

#region Restriction

private RestrictionType GetCalendarRestrictionByTime(DateTime? start, DateTime? end) {
if (start == null || end == null)
return null;

RestrictionType restriction = new RestrictionType();

AndType and = new AndType();

SearchExpressionType[] searchExpressions = new SearchExpressionType[2];

///

//设定IsGreaterThanOrEqualTo
///
IsGreaterThanOrEqualToType isGTOET = new IsGreaterThanOrEqualToType();

//define FieldURIOrConstant

FieldURIOrConstantType fieldURIOrConstantType = new FieldURIOrConstantType();
ConstantValueType constant = new ConstantValueType();
constant.Value = start.ToString();
fieldURIOrConstantType.Item = constant;

//define FieldURI

PathToUnindexedFieldType pathToUnindexedFieldType = new PathToUnindexedFieldType();
pathToUnindexedFieldType.FieldURI = UnindexedFieldURIType.calendarStart;

isGTOET.Item = pathToUnindexedFieldType;

isGTOET.FieldURIOrConstant = fieldURIOrConstantType;
searchExpressions[0] = isGTOET;

///

//设定IsLessThanOrEqualTo
///
IsLessThanOrEqualToType isLTOET = new IsLessThanOrEqualToType();

//define FieldURIOrConstant

FieldURIOrConstantType _fieldURIOrConstantType = new FieldURIOrConstantType();
ConstantValueType _constant = new ConstantValueType();
_constant.Value = end.ToString();
_fieldURIOrConstantType.Item = _constant;

//define FieldURI

PathToUnindexedFieldType _pathToUnindexedFieldType = new PathToUnindexedFieldType();
_pathToUnindexedFieldType.FieldURI = UnindexedFieldURIType.calendarEnd;

isLTOET.Item = _pathToUnindexedFieldType;

isLTOET.FieldURIOrConstant = _fieldURIOrConstantType;
searchExpressions[1] = isLTOET;

and.Items = searchExpressions;

restriction.Item = and;

return restriction;

}

private RestrictionType GetMailRestrictionByUnRead() {

RestrictionType restriction = new RestrictionType();
IsEqualToType isEqual = new IsEqualToType();

FieldURIOrConstantType _fieldURIOrConstantType = new FieldURIOrConstantType();

ConstantValueType _constant = new ConstantValueType();
_constant.Value = "0";
_fieldURIOrConstantType.Item = _constant;

PathToUnindexedFieldType _pathToUnindexedFieldType = new PathToUnindexedFieldType();

_pathToUnindexedFieldType.FieldURI = UnindexedFieldURIType.messageIsRead;

isEqual.FieldURIOrConstant = _fieldURIOrConstantType;

isEqual.Item = _pathToUnindexedFieldType;

restriction.Item = isEqual;

return restriction;

}
#endregion

#region GetCalendar

public List<CalendarItemType> GetCalendar(DateTime? start, DateTime? end) {
FindItemType findItemRequest = new FindItemType();
findItemRequest.Traversal = ItemQueryTraversalType.Shallow;

ItemResponseShapeType itemProperties = new ItemResponseShapeType();

itemProperties.BaseShape = DefaultShapeNamesType.AllProperties;

findItemRequest.ItemShape = itemProperties;

//查询条件

RestrictionType restriction = GetCalendarRestrictionByTime(start, end);

if (restriction != null)

findItemRequest.Restriction = restriction;

DistinguishedFolderIdType[] folderIDArray = new DistinguishedFolderIdType[1];

folderIDArray[0] = new DistinguishedFolderIdType();
folderIDArray[0].Id = DistinguishedFolderIdNameType.calendar;

findItemRequest.ParentFolderIds = folderIDArray;

try {

FindItemResponseType findItemResponse = esb.FindItem(findItemRequest);

ResponseMessageType[] rmta = findItemResponse.ResponseMessages.Items;

return getCalendar(ref rmta);

} catch (Exception e) {
throw (e);
}
}

private List<CalendarItemType> getCalendar(ref ResponseMessageType[] rmta) {

List<CalendarItemType> calendars = new List<CalendarItemType>(30);
if (rmta != null) {
foreach (ResponseMessageType rmt in rmta) {
if (rmt is FindItemResponseMessageType) {
FindItemResponseMessageType findItemResponse = (FindItemResponseMessageType)rmt;
if (findItemResponse.ResponseClass == ResponseClassType.Success) {
if (findItemResponse.RootFolder.Item is ArrayOfRealItemsType) {
ArrayOfRealItemsType obj = (ArrayOfRealItemsType)findItemResponse.RootFolder.Item;

if (obj != null && obj.Items != null) {

foreach (ItemType item in obj.Items) {
if (item is CalendarItemType) {
CalendarItemType calendarItem = (CalendarItemType)item;
if (calendarItem != null) {
calendars.Add(calendarItem);
}
}
}
}
}
}
}
}
}

return calendars;

}
#endregion

#region GetNewMail

public List<MessageType> GetNewMail() {
FindItemType findItemRequest = new FindItemType();
findItemRequest.Traversal = ItemQueryTraversalType.Shallow;

ItemResponseShapeType itemProperties = new ItemResponseShapeType();

itemProperties.BaseShape = DefaultShapeNamesType.AllProperties;

findItemRequest.ItemShape = itemProperties;

DistinguishedFolderIdType[] folderIDArray = new DistinguishedFolderIdType[1];

folderIDArray[0] = new DistinguishedFolderIdType();
folderIDArray[0].Id = DistinguishedFolderIdNameType.inbox;

findItemRequest.ParentFolderIds = folderIDArray;

//查询条件

RestrictionType restriction = GetMailRestrictionByUnRead();

if (restriction != null)

findItemRequest.Restriction = restriction;

try {

FindItemResponseType findItemResponse = esb.FindItem(findItemRequest);

ResponseMessageType[] rmta = findItemResponse.ResponseMessages.Items;

return getMail(ref rmta);

} catch (Exception e) {
throw (e);
}
}

private List<MessageType> getMail(ref ResponseMessageType[] rmta) {

List<MessageType> newMails = new List<MessageType>(30);
if (rmta != null) {
foreach (ResponseMessageType rmt in rmta) {
if (rmt is FindItemResponseMessageType) {
FindItemResponseMessageType findItemResponse = (FindItemResponseMessageType)rmt;
if (findItemResponse.ResponseClass == ResponseClassType.Success) {
if (findItemResponse.RootFolder.Item is ArrayOfRealItemsType) {
ArrayOfRealItemsType obj = (ArrayOfRealItemsType)findItemResponse.RootFolder.Item;

if (obj != null && obj.Items != null) {

foreach (ItemType item in obj.Items) {
if (item is MessageType) {
MessageType message = (MessageType)item;
if (message != null) {
newMails.Add(message);
}
}
}
}
}
}
}
}
}

return newMails;

}
#endregion

#region MailQuota

public MailQuota GetUsedMailboxSize() {
GetFolderType request = new GetFolderType();
PathToExtendedFieldType folderSizePath = new PathToExtendedFieldType();
folderSizePath.PropertyTag = "0x0e08";
folderSizePath.PropertyType = MapiPropertyTypeType.Integer;

FolderResponseShapeType folderResponseShapeType = new FolderResponseShapeType();

folderResponseShapeType.BaseShape = DefaultShapeNamesType.AllProperties;
folderResponseShapeType.AdditionalProperties = new BasePathToElementType[] { folderSizePath };

DistinguishedFolderIdType[] folderIDArray = new DistinguishedFolderIdType[13];

folderIDArray[0] = new DistinguishedFolderIdType();
folderIDArray[0].Id = DistinguishedFolderIdNameType.sentitems;

folderIDArray[1] = new DistinguishedFolderIdType();

folderIDArray[1].Id = DistinguishedFolderIdNameType.drafts;

folderIDArray[2] = new DistinguishedFolderIdType();

folderIDArray[2].Id = DistinguishedFolderIdNameType.voicemail;

folderIDArray[3] = new DistinguishedFolderIdType();

folderIDArray[3].Id = DistinguishedFolderIdNameType.calendar;

folderIDArray[4] = new DistinguishedFolderIdType();

folderIDArray[4].Id = DistinguishedFolderIdNameType.contacts;

folderIDArray[5] = new DistinguishedFolderIdType();

folderIDArray[5].Id = DistinguishedFolderIdNameType.tasks;

folderIDArray[6] = new DistinguishedFolderIdType();

folderIDArray[6].Id = DistinguishedFolderIdNameType.deleteditems;

folderIDArray[7] = new DistinguishedFolderIdType();

folderIDArray[7].Id = DistinguishedFolderIdNameType.inbox;

folderIDArray[8] = new DistinguishedFolderIdType();

folderIDArray[8].Id = DistinguishedFolderIdNameType.journal;

folderIDArray[9] = new DistinguishedFolderIdType();

folderIDArray[9].Id = DistinguishedFolderIdNameType.junkemail;

folderIDArray[10] = new DistinguishedFolderIdType();

folderIDArray[10].Id = DistinguishedFolderIdNameType.searchfolders;

folderIDArray[11] = new DistinguishedFolderIdType();

folderIDArray[11].Id = DistinguishedFolderIdNameType.notes;

folderIDArray[12] = new DistinguishedFolderIdType();

folderIDArray[12].Id = DistinguishedFolderIdNameType.outbox;

request.FolderIds = folderIDArray;

request.FolderShape = folderResponseShapeType;

GetFolderResponseType response = esb.GetFolder(request);

return parseQuota(response);

}

private MailQuota parseQuota(GetFolderResponseType response) {

MailQuota quota = null;
if (response == null)
return quota;

ArrayOfResponseMessagesType arrayOfResponseMessagesType = response.ResponseMessages;

if (arrayOfResponseMessagesType == null)
return quota;

ResponseMessageType[] responseMessageType = arrayOfResponseMessagesType.Items;

if (responseMessageType == null || responseMessageType.Length == 0)
return quota;

quota = new MailQuota();

for (int i = 0; i < responseMessageType.Length; i++) {

FolderInfoResponseMessageType folderInfoResponseMessage = responseMessageType[i] as FolderInfoResponseMessageType;
if (folderInfoResponseMessage == null)
continue;

BaseFolderType[] folders = folderInfoResponseMessage.Folders;

if (folders == null || folders.Length == 0)

continue;

BaseFolderType folder = null;

if (folders[0] is CalendarFolderType)
folder = folders[0] as CalendarFolderType;
else if (folders[0] is ContactsFolderType)
folder = folders[0] as ContactsFolderType;
else
folder = folders[0] as FolderType;

if (folder == null)

continue;

ExtendedPropertyType[] extendedPropertys = folder.ExtendedProperty;

if (extendedPropertys == null)
continue;
if (extendedPropertys.Length == 0)
continue;

ExtendedPropertyType extendedProperty = extendedPropertys[0];

if (extendedProperty == null)
continue;

int temp = 0;

int.TryParse(extendedProperty.Item.ToString(), out temp);
quota.UsedQuota += temp;

quota.MailCount += folder.TotalCount;

if (folder is FolderType)
quota.UnReadMailCount += ((EWS.FolderType)(folder)).UnreadCount;
}

return quota;

}
#endregion

#region SendMail

public bool SendMail(Mail m) {
EWS.CreateItemType createItem = new EWS.CreateItemType();
createItem.MessageDispositionSpecified = true;
createItem.MessageDisposition = EWS.MessageDispositionType.SendOnly;
EWS.MessageType message = new EWS.MessageType();
message.ItemClass = "IPM.Note";
message.Subject = m.Subject;
BodyType body = new BodyType();
body.BodyType1 = BodyTypeType.Text;
body.Value = m.Content;
message.Body = body;
message.IsRead = false;

message.ToRecipients = splitAddress(m.Address.To);

message.CcRecipients = splitAddress(m.Address.Cc);

message.BccRecipients = splitAddress(m.Address.Bcc);

createItem.Items = new NonEmptyArrayOfAllItemsType();

createItem.Items.Items = new EWS.ItemType[] { message };
CreateItemResponseType response = esb.CreateItem(createItem);
return response.ResponseMessages.Items[0].ResponseCode == ResponseCodeType.NoError;
}

private EWS.EmailAddressType[] splitAddress(string addr) {

if (String.IsNullOrEmpty(addr))
return null;

string[] arr = addr.Split(",;".ToCharArray());

List<EWS.EmailAddressType> list = new List<EmailAddressType>(arr.Length);
foreach (string str in arr) {
if (!String.IsNullOrEmpty(str)) {
EmailAddressType address = new EmailAddressType();
address.EmailAddress = str;

list.Add(address);

}
}
return list.ToArray();
}
#endregion
}
}

转载地址:http://zibmx.baihongyu.com/

你可能感兴趣的文章
Android : 如何在WebView显示的页面中查找内容
查看>>
数字信号处理 基础知识 对比回顾
查看>>
分享个人Vim型材
查看>>
配置算法(第4版)的Java编译环境
查看>>
本学习笔记TCP/IP传输协议
查看>>
配置 Windows 下的 nodejs C++ 模块编译环境 安装 node-gyp
查看>>
201215-03-19---cocos2dx内存管理--具体解释
查看>>
swift菜鸟入门视频教程-12-21讲
查看>>
CSharpGL(11)用C#直接编写GLSL程序
查看>>
仰视源代码,实现memcpy
查看>>
HTTP gzip和deflate的几点区别
查看>>
{Repeater控件} Repeater控件的用法流程及实例
查看>>
AD账号解锁
查看>>
English - in the light of(按照,根据)与according to的区别是什么
查看>>
浅析linux内核中的idr机制
查看>>
【转】.so兼容32位和64位
查看>>
PowerDesigner跟表的字段加注释
查看>>
w !sudo tee %
查看>>
javascript面试题:如何把一句英文每个单词首字母大写?
查看>>
URAL 1962 In Chinese Restaurant 数学
查看>>