using Microsoft.Exchange.WebServices.Data;
using Model;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using EasyLinkMobile.WebService.Common;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
namespace DAL.EWS
{
public class ExchangeProvider
{
#region construct
///
/// 隐藏构造函数,禁止通过 new 创建新对象
///
protected ExchangeProvider()
{
//
}
private static ExchangeProvider _Instance = null;
private static object _InstanceLock = new object();
///
/// 获取该类的唯一实例对象
///
public static ExchangeProvider Instance
{
get
{
if (_Instance == null)
{
lock (_InstanceLock)
{
if (_Instance == null)
{
_Instance = new ExchangeProvider();
}
}
}
return _Instance;
}
}
private static ExchangeService _ExchService = null;
private static object _ExchServiceLock = new object();
///
/// 获取该类的唯一实例对象
///
private static ExchangeService ExchService
{
get
{
if (_ExchService == null)
{
lock (_ExchServiceLock)
{
if (_ExchService == null)
{
EwsConfig _config = new EwsConfig();
_config.ExchangeVersion = GetCurrentExchangeVersion(); //ExchangeVersion.Exchange2010;
_config.EWSServiceUrl = ServiceUrl;
_config.ExchangeAdministrator = ADUser;
_config.ExchangeAdministratorPassword = ADPassword;
_config.DomainName = DomainName;
// _config.OtherUserName = accountName;
ServicePointManager.ServerCertificateValidationCallback =
delegate(Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; };
_ExchService = new ExchangeService(_config.ExchangeVersion);
_ExchService.Credentials = new NetworkCredential(_config.ExchangeAdministrator, _config.ExchangeAdministratorPassword, _config.DomainName);
_ExchService.Url = new Uri(_config.EWSServiceUrl);
// ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, _config.OtherUserName);
}
}
}
return _ExchService;
}
}
#endregion
#region 全局变量
///
/// Domain,如:aaa
///
private static string DomainName = System.Configuration.ConfigurationManager.AppSettings["ExchSvrDomain"];
///
/// 服务器地址,如:https://aaa.com/Exchange.asmx
///
private static string ServiceUrl = System.Configuration.ConfigurationManager.AppSettings["ExchWebServicesUrl"];
///
/// OWA地址
///
private static string OwaUrl = System.Configuration.ConfigurationManager.AppSettings["ExchOwaUrl"];
///
/// 代理账号
///
private static string ADUser = System.Configuration.ConfigurationManager.AppSettings["ExchProxyUser"];
///
/// 代理账号密码
///
private static string ADPassword = System.Configuration.ConfigurationManager.AppSettings["ExchProxyPwd"];
///
/// 个人邮箱账号
///
private string EmailAccountName { get; set; }
#endregion
///
/// Exchange WebServices配置信息实体
///
private struct EwsConfig
{
public ExchangeVersion ExchangeVersion;
public string EWSServiceUrl;
public string ExchangeAdministrator;
public string ExchangeAdministratorPassword;
public string DomainName;
//public string OtherUserName;
}
#region 辅助
///
/// 获取当前Exchange的版本
/// 在配置文件里可以配置节点:ExchangeVersion
///
///
private static ExchangeVersion GetCurrentExchangeVersion()
{
ExchangeVersion _ver = ExchangeVersion.Exchange2010;
string _exchVersion = "2010";
try
{
_exchVersion = System.Configuration.ConfigurationManager.AppSettings["ExchVersion"];
}
catch
{
//
}
switch (_exchVersion)
{
case "2007SP1":
_ver = ExchangeVersion.Exchange2007_SP1;
break;
case "2010":
_ver = ExchangeVersion.Exchange2010;
break;
case "2010SP1":
_ver = ExchangeVersion.Exchange2010_SP1;
break;
default: break;
}
return _ver;
}
#endregion
#region 2017-3-1开始更新的接口,老接口要测试后逐渐换掉
#region 未读邮件/数量
///
/// 同时获取多个目录的未读数量 2017-11-9
///
///
邮箱账号
///
目录ID,多个用|分开
///
public List
GetNoReadNumList(string accountName, string folderIdList)
{
EmailAccountName = accountName;
List listNoReadNum = new List();
if (!string.IsNullOrEmpty(folderIdList))
{
foreach (string folderid in folderIdList.Split('|'))
{
FoldInfo entity = new FoldInfo();
entity.ID = folderid;
if (folderid == "3")
{//草稿
List listFoldInfo = GetChildFolderList(accountName, "10", "1");//增加一个参数值 2017-12-11
foreach (FoldInfo folder in listFoldInfo)
{
if (folder.ID == folderid)
{
entity.NoRead = folder.NoRead;
break;
}
}
}
else
{
entity.NoRead = GetNoReadNum(accountName, folderid);
}
listNoReadNum.Add(entity);
}
}
return listNoReadNum;
}
///
/// 获取指定ID对应目录下的未读邮件数量
///
///
///
///
public int GetNoReadNum(string accountName, string folderid)
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
try
{
EmailAccountName = accountName;
if (string.IsNullOrEmpty(folderid))
{ return 0; }
if (folderid.Length < 3)
{ return _getNoReadNum((WellKnownFolderName)Convert.ToInt32(folderid)); }
else
{ return _getNoReadNum(folderid); }
}
catch { return 0; }
}
///
/// 设置邮件只读或未读 2017-11-14
///
///
///
///
public void SetIsRead(string accountName, string emid, bool isread)
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
EmailMessage em = EmailMessage.Bind(ExchService, emid);
if (em != null && em.IsRead != isread)
{ _setIsRead(em, isread); }
}
private void _setIsRead(string emid, bool isread)
{
EmailMessage em = EmailMessage.Bind(ExchService, emid);
if (em != null && em.IsRead != isread)
{ _setIsRead(em, isread); }
}
private void _setIsRead(EmailMessage em, bool isread)
{
if (em.IsRead != isread)
{
em.IsRead = isread;
em.Update(ConflictResolutionMode.NeverOverwrite);
}
}
private int _getNoReadNum(WellKnownFolderName foldername)
{
SearchFilter sf = new SearchFilter.SearchFilterCollection(
LogicalOperator.And
, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false)
);
ItemView iv = new ItemView(int.MaxValue);
FolderView folderViews = new FolderView(int.MaxValue);
FindItemsResults- list = ExchService.FindItems(foldername, sf, iv);
int noReadNum = 0;//只统计未邮件的数量
foreach (Item item in list)
{
if (item.GetType().Name == "EmailMessage")
{
noReadNum++;
}
}
return noReadNum;
//return list.Count();
}
private int _getNoReadNum(string folderid)
{
SearchFilter sf = new SearchFilter.SearchFilterCollection(
LogicalOperator.And
, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false)
);
ItemView iv = new ItemView(int.MaxValue);
FolderView folderViews = new FolderView(int.MaxValue);
FindItemsResults- list = ExchService.FindItems(folderid, sf, iv);
int noReadNum = 0;//只统计未邮件的数量
foreach (Item item in list)
{
if (item.GetType().Name == "EmailMessage")
{
noReadNum++;
}
}
return noReadNum;
//return list.Count();
}
public List GetNoReadMailList(string accountName, string folderid)
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
try
{
if (string.IsNullOrEmpty(folderid))
{ return null; }
if (folderid.Length < 3)
{ return GetNoReadMailList((WellKnownFolderName)Convert.ToInt32(folderid)); }
else
{ return GetNoReadMailList(folderid); }
}
catch { return null; }
}
///
/// 读取未读的邮件 2017-8-28
///
///
///
private List GetNoReadMailList(WellKnownFolderName foldername)
{
SearchFilter sf = new SearchFilter.SearchFilterCollection(
LogicalOperator.And
, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false)
);
ItemView iv = new ItemView(int.MaxValue);
FolderView folderViews = new FolderView(int.MaxValue);
FindItemsResults- list = ExchService.FindItems(foldername, sf, iv);
return ItemsResult2MailInfoList(list, false);
}
///
/// 读取未读的邮件 2017-8-28
///
///
///
private List GetNoReadMailList(string folderid)
{
SearchFilter sf = new SearchFilter.SearchFilterCollection(
LogicalOperator.And
, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false)
);
ItemView iv = new ItemView(int.MaxValue);
FolderView folderViews = new FolderView(int.MaxValue);
FindItemsResults- list = ExchService.FindItems(folderid, sf, iv);
return ItemsResult2MailInfoList(list, false);
}
public MailInfo GetNoReadMail(string accountName, string folderid, string emailId)
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
try
{
if (string.IsNullOrEmpty(folderid) || string.IsNullOrEmpty(emailId))
{ return null; }
if (folderid.Length < 3)
{ return GetNoReadMail((WellKnownFolderName)Convert.ToInt32(folderid), emailId); }
else
{ return GetNoReadMail(folderid, emailId); }
}
catch { return null; }
}
///
/// 读取未读的邮件 2017-8-28
///
///
///
private MailInfo GetNoReadMail(WellKnownFolderName foldername, string emailId)
{
SearchFilter sf = new SearchFilter.SearchFilterCollection(
LogicalOperator.And
, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false)
);
ItemView iv = new ItemView(int.MaxValue);
FolderView folderViews = new FolderView(int.MaxValue);
FindItemsResults- list = ExchService.FindItems(foldername, sf, iv);
return ItemsResult2MailInfo(list, emailId);
}
///
/// 读取未读的邮件 2017-8-28
///
///
///
private MailInfo GetNoReadMail(string folderid, string emailId)
{
SearchFilter sf = new SearchFilter.SearchFilterCollection(
LogicalOperator.And
, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false)
);
ItemView iv = new ItemView(int.MaxValue);
FolderView folderViews = new FolderView(int.MaxValue);
FindItemsResults- list = ExchService.FindItems(folderid, sf, iv);
return ItemsResult2MailInfo(list, emailId);
}
///
/// 把Exchange对象转成MailInfo对象 2017-8-28
///
/// FindItemsResults
///
private MailInfo ItemsResult2MailInfo(FindItemsResults- list, string emailId)
{
MailInfo info = null;
List result = new List();
for (int i = 0; i < list.Count(); i++)
{
EmailMessage message = EmailMessage.Bind(_ExchService, list.ElementAt(i).Id);
if (message.Id.UniqueId == emailId)
{
info = new MailInfo();
info.ID = message.Id.UniqueId;
//info.StartTime = message.DateTimeCreated;
//info.EndTime = message.LastModifiedTime;
info.IsRead = message.IsRead;
//info.Importance = message.Importance;
info.Descript = message.Body.Text;
//info.Descript = "";
//info.Subject = message.Subject;
//info.IsDraft = message.IsDraft;
//info.From = "";
info.BodyText = message.Body.Text;// 2017-8-25
//if (message.From != null && message.From.Name != null)
//{ info.From = message.From.Name + "[" + message.From.Address + "]"; }
//info.To = "";
//if (message.ToRecipients != null && message.ToRecipients.Count() > 0)
//{
// for (int k = 0; k < message.ToRecipients.Count(); k++)
// {
// info.To = _getMailAddressList(message.ToRecipients);
// }
//}
//info.AttachmentName = new List();
//if (message.Attachments.Count() > 0)
//{
// for (int j = 0; j < message.Attachments.Count(); j++)
// {
// if (message.Attachments.ElementAt(j).IsInline == true)
// { continue; }
// info.AttachmentName.Add(message.Attachments.ElementAt(j).Name);
// }
//}
break;
}
}
return info;
}
///
/// 把Exchange对象转成MailInfo对象 2017-8-28
///
/// FindItemsResults
///
private List ItemsResult2MailInfoList(FindItemsResults- list, bool addAttachemnt)
{
List result = new List();
for (int i = 0; i < list.Count(); i++)
{
EmailMessage message = EmailMessage.Bind(_ExchService, list.ElementAt(i).Id);
MailInfo info = new MailInfo();
info.ID = message.Id.UniqueId;
info.StartTime = message.DateTimeCreated;
info.EndTime = message.LastModifiedTime;
info.IsRead = message.IsRead;
info.Importance = message.Importance;
if (addAttachemnt)
{
info.Descript = message.Body.Text;
}
info.Subject = message.Subject;
info.IsDraft = message.IsDraft;
info.From = "";
//info.BodyText = message.Body.Text;// 2017-8-25
info.CreatedDateTime = message.DateTimeCreated;
info.ReceivedDateTime = message.DateTimeReceived;
if (message.From != null && message.From.Name != null)
{ info.From = message.From.Name + "[" + message.From.Address + "]"; }
info.To = "";
if (message.ToRecipients != null && message.ToRecipients.Count() > 0)
{
for (int k = 0; k < message.ToRecipients.Count(); k++)
{
info.To = _getMailAddressList(message.ToRecipients);
}
}
info.AttachmentName = new List();
info.HasAttachment = message.HasAttachments;
if (message.Attachments.Count() > 0)
{
int inlinenum = 0;
for (int j = 0; j < message.Attachments.Count(); j++)
{
Attachment ea = message.Attachments.ElementAt(j);
//FileAttachment ea = (FileAttachment)message.Attachments.ElementAt(j);
if (ea.IsInline == true)
{
if (addAttachemnt)
{
info.Descript = info.Descript.Replace("cid:" + ea.ContentId, "ShowInLineFile?id=" + info.ID + "&fileindex=" + inlinenum);
inlinenum++;
}
continue;
}
info.AttachmentName.Add(ea.Name);
}
}
result.Add(info);
}
return result;
}
#endregion
///
/// 获取指定目录下按指定关键词搜索到的指定时间之前的指定数量的邮件
///
///
///
///
///
///
///
///
public List GetPageMail(string accountName, string filterStr, string folderid, int pageSize, DateTime lasttime, int lastnum)
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
try
{
if (string.IsNullOrEmpty(folderid))
{ return new List(); }
if (folderid.Length < 3)
{ return _getPageMail(filterStr, (WellKnownFolderName)Convert.ToInt32(folderid), pageSize, lasttime, lastnum); }
else
{ return _getPageMail(filterStr, folderid, pageSize, lasttime, lastnum); }
}
catch { return new List(); }
}
///
/// 在指定目录中使用指定关键字搜索指定日期之后的所有新邮件
///
///
///
///
///
///
public List GetNewMail(string accountName, string filterStr, string folderid, DateTime lasttime)
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
try
{
if (string.IsNullOrEmpty(folderid))
{ return new List(); }
if (folderid.Length < 3)
{ return _getNewMail(filterStr, (WellKnownFolderName)Convert.ToInt32(folderid), lasttime); }
else
{ return _getNewMail(filterStr, folderid, lasttime); }
}
catch { return new List(); }
}
///
/// 获取指定用户指定ID对应的邮件信息,并且将其未读状态更新为已读,為加快讀取速度,此接口不獲取附件內容
///
///
///
/// true读取附件内容
///
public MailInfo GetEmailInfo(string accountName, string Id, bool isReadAttachContent)
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
EmailMessage tmpInfo = EmailMessage.Bind(ExchService, Id);
if (tmpInfo == null || tmpInfo.Id == null || tmpInfo.Id.UniqueId != Id)
{ return null; }
_setIsRead(tmpInfo, true);// 将邮件置为已读
MailInfo mailInfo = new MailInfo();
#region 基本信息
if (tmpInfo.IsDraft)
{ mailInfo.BCc = _getMailAddressList(tmpInfo.BccRecipients); }
mailInfo.Cc = _getMailAddressList(tmpInfo.CcRecipients);
mailInfo.Descript = tmpInfo.Body == null ? "" : tmpInfo.Body.Text;
mailInfo.EndTime = tmpInfo.LastModifiedTime;
//mailInfo.From = tmpInfo.From == null ? "" : (tmpInfo.From.Name + "[" + tmpInfo.From.Address + "]");
mailInfo.From = tmpInfo.From == null ? "" : tmpInfo.From.Address;//只需要email address
mailInfo.ID = tmpInfo.Id.UniqueId; //.ToString();
mailInfo.StartTime = tmpInfo.DateTimeCreated;
mailInfo.CreatedDateTime = tmpInfo.DateTimeCreated;
mailInfo.ReceivedDateTime = tmpInfo.DateTimeReceived;
mailInfo.Subject = tmpInfo.Subject;
mailInfo.To = _getMailAddressList(tmpInfo.ToRecipients);
mailInfo.WebClientEditFormQueryString = tmpInfo.WebClientEditFormQueryString;
mailInfo.WebClientReadFormQueryString = tmpInfo.WebClientReadFormQueryString;
mailInfo.IsDraft = tmpInfo.IsDraft;
mailInfo.IsRead = tmpInfo.IsRead;
mailInfo.Importance = tmpInfo.Importance;
mailInfo.BodyType = tmpInfo.Body.BodyType;// 2017-10-11
#endregion
#region 附件相關數據聲明
int inlinenum = 0;
mailInfo.AttachmentId = new List();
mailInfo.AttachmentName = new List();
mailInfo.AttachmentType = new List();
mailInfo.AttachmentSize = new List();
mailInfo.AttachmentByte = new List();
mailInfo.AttachmentIsInLine = new List();
mailInfo.AttachmentContentID = new List();
mailInfo.HasAttachment = tmpInfo.HasAttachments;
mailInfo.ItemTypeList = new List();
#endregion
string attachTypeName = string.Empty;
for (int i = 0; i < tmpInfo.Attachments.Count(); i++)
{
attachTypeName = tmpInfo.Attachments.ElementAt(i).GetType().Name;
mailInfo.ItemTypeList.Add(attachTypeName);
switch (attachTypeName)
{
case "FileAttachment":
#region FileAttachment
Attachment ea = tmpInfo.Attachments.ElementAt(i);
mailInfo.AttachmentId.Add(ea.Id);
mailInfo.AttachmentName.Add(ea.Name);
mailInfo.AttachmentType.Add(ea.ContentType);
mailInfo.AttachmentSize.Add(ea.Size);
mailInfo.AttachmentIsInLine.Add(tmpInfo.Attachments.ElementAt(i).IsInline);
mailInfo.AttachmentContentID.Add(tmpInfo.Attachments.ElementAt(i).ContentId);
//读取附件内容 2017-9-29
if (isReadAttachContent)
{
FileAttachment fa = (FileAttachment)ea;
fa.Load();
mailInfo.AttachmentByte.Add(fa.Content);
}
// 如果是内嵌图片,直接处理其显示代码,不出现到附件中
if (tmpInfo.Attachments.ElementAt(i).IsInline)
{
mailInfo.Descript = mailInfo.Descript.Replace("cid:" + ea.ContentId, "ShowInLineFile?id=" + Id + "&fileindex=" + inlinenum + "&cid=" + ea.ContentId + "&end");
}
#endregion
break;
case "ItemAttachment"://解决之前只转换为FileAttachment的BUG
#region ItemAttachment
ItemAttachment ia = (ItemAttachment)tmpInfo.Attachments.ElementAt(i);
mailInfo.AttachmentId.Add(ia.Id);
mailInfo.AttachmentIsInLine.Add(tmpInfo.Attachments.ElementAt(i).IsInline);
mailInfo.AttachmentName.Add(ia.Name);
mailInfo.AttachmentType.Add(ia.ContentType);
mailInfo.AttachmentSize.Add(ia.Size);
mailInfo.AttachmentContentID.Add(ia.ContentId);
//读取附件内容 2017-11-27
if (isReadAttachContent)
{
ia.Load(ItemSchema.MimeContent);
mailInfo.AttachmentByte.Add(ia.Item.MimeContent.Content);
}
mailInfo.AttachmentMsgAmount++;
#endregion
break;
}
inlinenum++;
}
return mailInfo;
}
///
/// 获取指定用户指定ID对应的邮件信息,并且将其未读状态更新为已读,此接口獲取所有附件內容
///
///
///
///
public MailInfo GetEmailAllInfo(string accountName, string Id)
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
EmailMessage tmpInfo = EmailMessage.Bind(ExchService, Id);
if (tmpInfo == null || tmpInfo.Id == null || tmpInfo.Id.UniqueId != Id)
{ return null; }
_setIsRead(tmpInfo, true);// 将邮件置为已读
MailInfo mailInfo = new MailInfo();
#region 基本信息
if (tmpInfo.IsDraft)
{ mailInfo.BCc = _getMailAddressList(tmpInfo.BccRecipients); }
mailInfo.Cc = _getMailAddressList(tmpInfo.CcRecipients);
mailInfo.Descript = tmpInfo.Body == null ? "" : tmpInfo.Body.Text;
mailInfo.EndTime = tmpInfo.LastModifiedTime;
//mailInfo.From = tmpInfo.From == null ? "" : (tmpInfo.From.Name + "[" + tmpInfo.From.Address + "]");
mailInfo.From = tmpInfo.From == null ? "" : tmpInfo.From.Address;//只需要email address
mailInfo.ID = tmpInfo.Id.UniqueId; //.ToString();
mailInfo.StartTime = tmpInfo.DateTimeCreated;
mailInfo.Subject = tmpInfo.Subject;
mailInfo.To = _getMailAddressList(tmpInfo.ToRecipients);
mailInfo.WebClientEditFormQueryString = tmpInfo.WebClientEditFormQueryString;
mailInfo.WebClientReadFormQueryString = tmpInfo.WebClientReadFormQueryString;
mailInfo.IsDraft = tmpInfo.IsDraft;
mailInfo.HasAttachment = tmpInfo.HasAttachments;
#endregion
#region 附件相關數據聲明
mailInfo.AttachmentId = new List();
mailInfo.AttachmentName = new List();
mailInfo.AttachmentType = new List();
mailInfo.AttachmentSize = new List();
mailInfo.AttachmentByte = new List();
mailInfo.AttachmentIsInLine = new List();
mailInfo.AttachmentContentID = new List();
mailInfo.ItemTypeList = new List();
//mailInfo.SubEmailList = new List();
#endregion
string attachTypeName = string.Empty;
for (int i = 0; i < tmpInfo.Attachments.Count(); i++)
{
attachTypeName = tmpInfo.Attachments.ElementAt(i).GetType().Name;
mailInfo.ItemTypeList.Add(attachTypeName);
switch (attachTypeName)
{
case "FileAttachment":
#region ItemAttachment
FileAttachment ea = (FileAttachment)tmpInfo.Attachments.ElementAt(i);
mailInfo.AttachmentId.Add(ea.Id);
mailInfo.AttachmentIsInLine.Add(tmpInfo.Attachments.ElementAt(i).IsInline);
#region 已註釋
// 如果是内嵌图片,直接处理其显示代码,不出现到附件中
//发送的邮件,要在不同的终端显示,所以此处不需要处理,所以注释以下代码 2017-9-28
//if (tmpInfo.Attachments.ElementAt(i).IsInline == true)
//{
// mailInfo.Descript = mailInfo.Descript.Replace("cid:" + ea.ContentId, "ShowInLineFile?id=" + Id + "&fileindex=" + inlinenum);
// inlinenum++;
// continue;
//}
#endregion
mailInfo.AttachmentName.Add(ea.Name);
mailInfo.AttachmentType.Add(ea.ContentType);
mailInfo.AttachmentSize.Add(ea.Size);
mailInfo.AttachmentContentID.Add(ea.ContentId);
ea.Load();
byte[] getbyte = ea.Content;
mailInfo.AttachmentByte.Add(getbyte);
#endregion
break;
case "ItemAttachment"://解决之前只转换为FileAttachment的BUG
#region ItemAttachment
ItemAttachment ia = (ItemAttachment)tmpInfo.Attachments.ElementAt(i);
ia.Load(ItemSchema.MimeContent);
mailInfo.AttachmentId.Add(ia.Id);
mailInfo.AttachmentIsInLine.Add(tmpInfo.Attachments.ElementAt(i).IsInline);
mailInfo.AttachmentName.Add(ia.Name);
mailInfo.AttachmentType.Add(ia.ContentType);
mailInfo.AttachmentSize.Add(ia.Size);
mailInfo.AttachmentContentID.Add(ia.ContentId);
mailInfo.AttachmentMsgAmount++;
byte[] iaByte = ia.Item.MimeContent.Content;
mailInfo.AttachmentByte.Add(iaByte);
mailInfo.SubEmailList.Add(GetEmailFromItemAttachment(ia.Item));
#endregion
break;
}
}
mailInfo.IsRead = tmpInfo.IsRead;
mailInfo.Importance = tmpInfo.Importance;
return mailInfo;
}
///
/// 获取指定用户指定ID对应的邮件信息中的指定附件信息
///
///
///
/// 第幾個附件
///
public MailInfo GetAttachData(string accountName, string Id, int fileindex)
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
EmailMessage tmpInfo = EmailMessage.Bind(ExchService, Id);
if (tmpInfo == null || tmpInfo.Id == null || tmpInfo.Id.UniqueId != Id.ToString())
{ return null; }
MailInfo mailInfo = new MailInfo();
mailInfo.ID = tmpInfo.Id.ToString();
mailInfo.HasAttachment = tmpInfo.HasAttachments;
mailInfo.AttachmentName = new List();
mailInfo.AttachmentByte = new List();
mailInfo.AttachmentType = new List();
mailInfo.AttachmentSize = new List();
string attachTypeName = string.Empty;
for (int i = 0; i < tmpInfo.Attachments.Count(); i++)
{
if (tmpInfo.Attachments.ElementAt(i).IsInline)
{
continue;
}
if (i == fileindex)
{
attachTypeName = tmpInfo.Attachments.ElementAt(i).GetType().Name;
switch (attachTypeName)
{
case "FileAttachment":
#region ItemAttachment
FileAttachment ea = (FileAttachment)tmpInfo.Attachments.ElementAt(i);
mailInfo.AttachmentType.Add(ea.ContentType);
mailInfo.AttachmentName.Add(ea.Name);
mailInfo.AttachmentSize.Add(ea.Size);
ea.Load();
byte[] readbyte = ea.Content;
mailInfo.AttachmentByte.Add(readbyte);
#endregion
break;
case "ItemAttachment"://解决之前只转换为FileAttachment的BUG
#region ItemAttachment
ItemAttachment ia = (ItemAttachment)tmpInfo.Attachments.ElementAt(i);
ia.Load(ItemSchema.MimeContent);
mailInfo.AttachmentName.Add(ia.Name);
mailInfo.AttachmentType.Add(ia.ContentType);
mailInfo.AttachmentSize.Add(ia.Size);
mailInfo.AttachmentMsgAmount++;
byte[] iaByte = ia.Item.MimeContent.Content;
mailInfo.AttachmentByte.Add(iaByte);
#endregion
break;
}
break;
}
}
return mailInfo;
}
///
/// 获取指定用户指定ID对应的邮件信息中的指定内嵌图片信息
///
///
///
///
///
public MailInfo GetInLineData(string accountName, string Id, int fileindex)
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
EmailMessage tmpInfo = EmailMessage.Bind(ExchService, Id);
if (tmpInfo == null || tmpInfo.Id == null || tmpInfo.Id.UniqueId != Id.ToString())
{ return null; }
MailInfo mailInfo = new MailInfo();
mailInfo.ID = tmpInfo.Id.ToString();
mailInfo.Cc = _getMailAddressList(tmpInfo.CcRecipients);
mailInfo.Descript = "";
mailInfo.EndTime = tmpInfo.LastModifiedTime;
mailInfo.From = tmpInfo.From == null ? "" : (tmpInfo.From.Name + "[" + tmpInfo.From.Address + "]");
mailInfo.StartTime = tmpInfo.DateTimeCreated;
mailInfo.Subject = tmpInfo.Subject;
mailInfo.To = _getMailAddressList(tmpInfo.ToRecipients);
mailInfo.WebClientEditFormQueryString = tmpInfo.WebClientEditFormQueryString;
mailInfo.WebClientReadFormQueryString = tmpInfo.WebClientReadFormQueryString;
mailInfo.IsDraft = tmpInfo.IsDraft;
mailInfo.IsRead = tmpInfo.IsRead;
mailInfo.Importance = tmpInfo.Importance;
mailInfo.AttachmentName = new List();
mailInfo.AttachmentByte = new List();
mailInfo.AttachmentType = new List();
mailInfo.AttachmentSize = new List();
for (int i = 0; i < tmpInfo.Attachments.Count(); i++)
{
if (i == fileindex)
{
//if (tmpInfo.Attachments.ElementAt(i).IsInline == false)
//{ continue; }
FileAttachment ea = (FileAttachment)tmpInfo.Attachments.ElementAt(i);
mailInfo.AttachmentType.Add(ea.ContentType);
mailInfo.AttachmentName.Add(ea.Name);
mailInfo.AttachmentSize.Add(ea.Size);
//if (mailInfo.AttachmentByte.Count() == fileindex)
//{
ea.Load();
byte[] readbyte = ea.Content;
mailInfo.AttachmentByte.Add(readbyte);
break;
//}
//else
//{
// mailInfo.AttachmentByte.Add(new byte[] { });
//}
}
}
return mailInfo;
}
///
/// 根据指定标题查找指定用户的邮件,并将查找到的邮件主题更新
/// 此方法用于保存草稿时,获取被保存的邮件id,指定标题为添加时手动设置
///
///
///
///
///
public string GetMailID(string accountName, string signsubject, string realsubject)
{
string result = "";
List tempmaillist = _getPageMail(signsubject, WellKnownFolderName.Drafts, 10, DateTime.Now.AddMinutes(1.0), 0);
for (int i = 0; tempmaillist != null && i < tempmaillist.Count; i++)
{
if (tempmaillist[i].Subject == signsubject)
{
EmailMessage em = EmailMessage.Bind(ExchService, tempmaillist[i].ID);
em.Subject = realsubject;
em.Update(ConflictResolutionMode.NeverOverwrite);
result = em.Id.UniqueId;
break;
}
}
return result;
}
///
/// 将指定用户的指定邮件保存到草稿箱
///
///
///
///
public void SaveDraftMail(string accountName, MailInfo mi)
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
EmailMessage em = new EmailMessage(ExchService);
if (!string.IsNullOrEmpty(mi.ID))
{
try
{ em = EmailMessage.Bind(ExchService, mi.ID); }
catch (Exception ex)
{
em = new EmailMessage(ExchService);
mi.ID = "";
SendMail(accountName, "", "error msg", new MessageBody() { BodyType = BodyType.HTML, Text = ex.ToString() }
, new string[][] { }, new string[][] { }, new string[][] { }
, new List(), new List(), new List(), new List(), new List(), new List(), Importance.High);
}
}
em.Subject = mi.Subject;
em.Body = new MessageBody() { Text = mi.Descript };
em.ToRecipients.Clear();
List tmpaddresslist = _getMailAddressList(mi.To);
for (int i = 0; i < tmpaddresslist.Count; i++)
{ em.ToRecipients.Add(tmpaddresslist[i]); }
em.CcRecipients.Clear();
tmpaddresslist = _getMailAddressList(mi.Cc);
for (int j = 0; j < tmpaddresslist.Count; j++)
{ em.CcRecipients.Add(tmpaddresslist[j]); }
em.BccRecipients.Clear();
tmpaddresslist = _getMailAddressList(mi.BCc);
for (int k = 0; k < tmpaddresslist.Count; k++)
{ em.BccRecipients.Add(tmpaddresslist[k]); }
em.IsRead = true;
em.Importance = mi.Importance;
em.Attachments.Clear();
if (mi.AttachmentName != null && mi.AttachmentName.Count > 0)
{
for (int l = 0; l < mi.AttachmentName.Count; l++)
{
em.Attachments.AddFileAttachment(mi.AttachmentName[l], mi.AttachmentByte[l]);
em.Attachments.ElementAt(l).ContentType = mi.AttachmentType[l];
}
}
if (string.IsNullOrEmpty(mi.ID))
{ em.Save(WellKnownFolderName.Drafts); }
else
{ em.Update(ConflictResolutionMode.NeverOverwrite); }
}
///
/// 删除指定邮件
///
///
///
public void DeleteEmail(string accountName, string Id)
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
EmailMessage tmpInfo = EmailMessage.Bind(ExchService, Id);
if (tmpInfo == null)
{ return; }
tmpInfo.Delete(DeleteMode.MoveToDeletedItems);
// 先使用软删除,如果是未删除邮件,则通过id查不到邮件,还能查到的话,说明是已删除邮件,再做一次硬删除
try
{
tmpInfo = EmailMessage.Bind(ExchService, Id);
if (tmpInfo == null)
{ return; }
tmpInfo.Delete(DeleteMode.HardDelete);
}
catch { ;}
}
///
/// 彻底删除指定邮件
///
///
///
public void HardDeleteEmail(string accountName, string Id)
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
EmailMessage tmpInfo = EmailMessage.Bind(ExchService, Id);
if (tmpInfo == null)
{ return; }
tmpInfo.Delete(DeleteMode.HardDelete);
}
#region 邮件目录相关
#region 邮件目录列表
///
/// 获取指定目录下的一级子目录列表
///
///
///
/// 是否讀取系統目錄ID對應的索引( 2017-12-11)
///
public List GetChildFolderList(string accountName, string folderid, string isReadSytemFolderId)
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
try
{
EmailAccountName = accountName;
if (string.IsNullOrEmpty(folderid))
{ return new List(); }
if (folderid.Length < 3)
{ return _getChildFolderList((WellKnownFolderName)Convert.ToInt32(folderid), isReadSytemFolderId); }
else
{ return _getChildFolderList(folderid, isReadSytemFolderId); }
}
catch { return new List(); }
}
private List _getChildFolderList(WellKnownFolderName foldername, string isReadSytemFolderId)
{
FolderView folderViews = new FolderView(int.MaxValue);
FindFoldersResults folders = ExchService.FindFolders(foldername, folderViews);
return _getFolderList(folders, isReadSytemFolderId);
}
private List _getChildFolderList(string folderid, string isReadSytemFolderId)
{
FolderView folderViews = new FolderView(int.MaxValue);
FindFoldersResults folders = ExchService.FindFolders(folderid, folderViews);
return _getFolderList(folders, isReadSytemFolderId);
}
private List _getFolderList(FindFoldersResults folders, string isReadSytemFolderId)
{
//DateTime now = DateTime.Now;
//string tmp = "开始:" + now.ToString("HH:mm:ss") + "_" + now.Millisecond.ToString();
List foldnamelist = new List() {
WellKnownFolderName.Drafts// 这个位置不要随便动,后面有单独针对草稿箱的操作
,WellKnownFolderName.DeletedItems
,WellKnownFolderName.Inbox
,WellKnownFolderName.Outbox
,WellKnownFolderName.SentItems
,WellKnownFolderName.JunkEmail
};
List foldidlist = new List();
if (isReadSytemFolderId == "1")
{
for (int fi = 0; fi < foldnamelist.Count(); fi++)
{ foldidlist.Add(_getFolderID(foldnamelist[fi])); }
}
List result = new List();
for (int i = 0; i < folders.Count(); i++)
{
// 此值是标示其是否为邮件目录
if (folders.ElementAt(i).FolderClass != "IPF.Note")
{ continue; }
FoldInfo childfold = new FoldInfo();
childfold.ID = folders.ElementAt(i).Id.UniqueId;
if (foldidlist.Contains(childfold.ID))
{ childfold.ID = ((int)foldnamelist[foldidlist.FindIndex(p => p == childfold.ID)]).ToString(); }
childfold.Name = folders.ElementAt(i).DisplayName;
childfold.ChildNum = folders.ElementAt(i).ChildFolderCount;
if (childfold.ID == "4")
{//解决收件箱中包含了不是邮件的未读数量BUG(日后能显示所有类型的数据时,再把此IF去掉 2017-11-13
childfold.NoRead = this.GetNoReadNum(EmailAccountName, childfold.ID);
}
else
{
childfold.NoRead = folders.ElementAt(i).UnreadCount;
}
// 如果是草稿箱,未读邮件置为所有邮件數量
if (foldidlist.Count() > 0 && folders.ElementAt(i).Id.UniqueId == foldidlist[0])
{ childfold.NoRead = folders.ElementAt(i).TotalCount; }
result.Add(childfold);
}
//now = DateTime.Now;
//tmp += " 结束:" + now.ToString("HH:mm:ss") + "_" + now.Millisecond.ToString();
return result;
}
#endregion
#region 读取目录名
public string GetFoldName(string accountName, string folderid)
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
try
{
if (string.IsNullOrEmpty(folderid))
{ return ""; }
if (folderid.Length < 3)
{ return _getFoldName((WellKnownFolderName)Convert.ToInt32(folderid)); }
else
{ return _getFoldName(folderid); }
}
catch { return ""; }
}
private string _getFoldName(string folderid)
{
Folder foldinfo = Folder.Bind(ExchService, folderid);
return foldinfo.DisplayName;
}
private string _getFoldName(WellKnownFolderName folderid)
{
Folder foldinfo = Folder.Bind(ExchService, folderid);
return foldinfo.DisplayName;
}
#endregion
///
/// 获取指定WellKnownFolderName对应的UniqueId
///
///
///
private string _getFolderID(WellKnownFolderName foldname)
{
Folder folder = Folder.Bind(ExchService, foldname);
return folder.Id.UniqueId;
}
#endregion
///
/// 返回当前用户的草稿箱UniqueId,用于获取目录列表时,比对查找草稿箱
///
///
private string _getDraftID()
{
Folder folder_draft = Folder.Bind(ExchService, WellKnownFolderName.Drafts);
return folder_draft.Id.UniqueId;
}
//获取指定目录下按指定关键词在指定偏移量后搜索到的指定时间之后的指定数量的邮件
private List _getPageMail(string filterStr, WellKnownFolderName foldername, int pageSize, DateTime lasttime, int lastnum)
{
int mailnum = pageSize + pageSize;
lastnum = lastnum < (pageSize / 2) ? 0 : (lastnum - pageSize / 2);
FindItemsResults- maillist = _getItemsList(filterStr, foldername, mailnum, lastnum);
if (maillist == null || maillist.Count() < 1 || maillist.ElementAt(0).DateTimeReceived < lasttime)
{
if (lastnum > 0)
{
lastnum = lastnum < pageSize ? 0 : (lastnum - pageSize);
return _getPageMail(filterStr, foldername, pageSize, lasttime, lastnum);
}
}
else if (maillist.Count() == mailnum && maillist.ElementAt(mailnum - pageSize).DateTimeReceived >= lasttime)
{
lastnum += pageSize;
if (maillist.ElementAt(mailnum - 1).DateTimeReceived >= lasttime)
{ lastnum += pageSize - 1; }
return _getPageMail(filterStr, foldername, pageSize, lasttime, lastnum);
}
int num = -1;
for (int i = 0; maillist != null && i < maillist.Count(); i++)
{
if (maillist.ElementAt(i).DateTimeReceived < lasttime)
{ num = i; break; }
}
List result = new List();
if (num < 0)
{ return result; }
return _getMailList(maillist, num, pageSize);
}
// 获取指定目录下按指定关键词在指定偏移量后搜索到的指定时间之后的指定数量的邮件
private List _getPageMail(string filterStr, string folderid, int pageSize, DateTime lasttime, int lastnum)
{
int mailnum = pageSize + pageSize;
lastnum = lastnum < (pageSize / 2) ? 0 : (lastnum - pageSize / 2);
FindItemsResults- maillist = _getItemsList(filterStr, folderid, mailnum, lastnum);
if (maillist == null || maillist.Count() < 1 || maillist.ElementAt(0).DateTimeReceived < lasttime)
{
if (lastnum > 0)
{
lastnum = lastnum < pageSize ? 0 : (lastnum - pageSize);
return _getPageMail(filterStr, folderid, pageSize, lasttime, lastnum);
}
}
else if (maillist.Count() == mailnum && maillist.ElementAt(mailnum - pageSize).DateTimeReceived >= lasttime)
{
lastnum += pageSize;
if (maillist.ElementAt(mailnum - 1).DateTimeReceived >= lasttime)
{ lastnum += pageSize - 1; }
return _getPageMail(filterStr, folderid, pageSize, lasttime, lastnum);
}
int num = -1;
for (int i = 0; maillist != null && i < maillist.Count(); i++)
{
if (maillist.ElementAt(i).DateTimeReceived < lasttime)
{ num = i; break; }
}
List result = new List();
if (num < 0)
{ return result; }
return _getMailList(maillist, num, pageSize);
}
// 在指定目录中使用指定关键字搜索指定日期之后的所有邮件
private List _getNewMail(string filterStr, WellKnownFolderName foldername, DateTime lasttime)
{
int mailnum = 20;
FindItemsResults- maillist = _getItemsList(filterStr, foldername, mailnum, 0);
// 如果最后一封邮件的时间还早于lasttime,说明没取到所有新邮件,要加数量再取
while (maillist.Count() == mailnum && maillist.ElementAt(mailnum - 1).LastModifiedTime > lasttime)
{
mailnum += 20;
maillist = _getItemsList(filterStr, foldername, mailnum, 0);
}
int num = 0;
for (int i = 0; i < maillist.Count(); i++)
{
if (maillist.ElementAt(i).DateTimeReceived <= lasttime)
{ num = i; break; }
}
List result = new List();
if (num < 0)
{ return result; }
return _getMailList(maillist, 0, num);
}
// 在指定目录中使用指定关键字搜索指定日期之后的所有邮件
private List _getNewMail(string filterStr, string folderid, DateTime lasttime)
{
int mailnum = 20;
FindItemsResults- maillist = _getItemsList(filterStr, folderid, mailnum, 0);
// 如果最后一封邮件的时间还早于lasttime,说明没取到所有新邮件,要加数量再取
while (maillist.Count() == mailnum && maillist.ElementAt(mailnum - 1).LastModifiedTime > lasttime)
{
mailnum += 20;
maillist = _getItemsList(filterStr, folderid, mailnum, 0);
}
int num = 0;
for (int i = 0; i < maillist.Count(); i++)
{
if (maillist.ElementAt(i).DateTimeReceived <= lasttime)
{ num = i; break; }
}
List result = new List();
if (num < 0)
{ return result; }
return _getMailList(maillist, 0, num);
}
// 在指定目录下用指定关键词从指定偏移量开始查找到的指定数量的返回结果
private FindItemsResults- _getItemsList(string filterStr, WellKnownFolderName foldername, int num, int offset)
{
FindItemsResults- list;
ItemView iv = new ItemView(num) { Offset = offset };
if (string.IsNullOrEmpty(filterStr))
{ list = ExchService.FindItems(foldername, iv); }
else
{
SearchFilter sf = _getSearchFilt(filterStr);
list = ExchService.FindItems(foldername, sf, iv);
}
return list;
}
// 在指定目录下用指定关键词查找指定数量的返回结果
private FindItemsResults- _getItemsList(string filterStr, string folderid, int pageSize, int offset)
{
FindItemsResults- list;
ItemView iv = new ItemView(pageSize) { Offset = offset };
if (string.IsNullOrEmpty(filterStr))
{ list = ExchService.FindItems(folderid, iv); }
else
{
SearchFilter sf = _getSearchFilt(filterStr);
list = ExchService.FindItems(folderid, sf, iv);
}
return list;
}
// 从查找到的邮件列表中的指定位置开始取出指定的数量的邮件
private List _getMailList(FindItemsResults- maillist, int startnum, int pageSize)
{
List result = new List();
for (int i = startnum; i < startnum + pageSize && i < maillist.Count(); i++)
{
#region
EmailMessage message = null;
MailInfo info = new MailInfo();
if (IsQuickShowEmailList)
{
if (maillist.ElementAt(i).GetType().Name != "EmailMessage")//已刪除的不一定都是郵件,有可能是會議,也有可能是定時提醒 2017-10-13
continue;
message = (EmailMessage)maillist.ElementAt(i);
info.Descript = "";
}
else
{
message = EmailMessage.Bind(_ExchService, maillist.ElementAt(i).Id);
info.Descript = message.Body.Text;
}
//info.BodyText = message.Body.Text;// 2017-8-25
info.DisplayTo = message.DisplayTo;// 用于已发送郵件列表显示收件人 2017-10-13
info.ID = message.Id.UniqueId;
info.StartTime = message.DateTimeCreated;
info.EndTime = message.LastModifiedTime;
info.CreatedDateTime = info.StartTime;
info.ReceivedDateTime = message.DateTimeReceived;
info.IsRead = message.IsRead;
info.Importance = message.Importance;
info.Subject = message.Subject;
info.IsDraft = message.IsDraft;
info.From = "";
if (message.From != null && message.From.Name != null)
{
info.From = message.From.Name;
if (!string.IsNullOrEmpty(message.From.Address))
{
info.From += "[" + message.From.Address + "]";
}
}
info.To = "";
if (message.ToRecipients != null && message.ToRecipients.Count() > 0)
{
for (int k = 0; k < message.ToRecipients.Count(); k++)
{
info.To = _getMailAddressList(message.ToRecipients);
}
}
info.AttachmentName = new List();
info.HasAttachment = message.HasAttachments;// 2017-9-6
if (message.Attachments.Count() > 0)
{
for (int j = 0; j < message.Attachments.Count(); j++)
{
if (message.Attachments.ElementAt(j).IsInline == true)
{ continue; }
info.AttachmentName.Add(message.Attachments.ElementAt(j).Name);
}
}
info.TotalCount = maillist.TotalCount;//解决已加载数量大于邮件总数量,还能向webService发起请求的Bug 2017-9-19
result.Add(info);
#endregion
}
return result;
}
// 返回指定关键字对应的搜索条件,暂时查找发件人、收件人、主题
private SearchFilter _getSearchFilt(string filterStr)
{
filterStr = filterStr.Trim();// 2017-9-14
return new SearchFilter.SearchFilterCollection(
LogicalOperator.Or
, new SearchFilter.ContainsSubstring(ItemSchema.Subject, filterStr)
, new SearchFilter.ContainsSubstring(ItemSchema.DisplayTo, filterStr)
, new SearchFilter.ContainsSubstring(ItemSchema.Body, filterStr)//增加正文查询功能2017-08-25
, new SearchFilter.ContainsSubstring(PostItemSchema.From, filterStr)
);
}
#region 邮件地址
#region 根據關鍵字搜索郵件時,新增查詢條件【全部,主題,正文,發件人,收件人】 20170908 andrewli
public List GetPageMail(string accountName, string filterStr, string folderid, int pageSize, DateTime lasttime, int lastnum, int searchType)
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
try
{
if (string.IsNullOrEmpty(folderid))
{ return new List(); }
if (folderid.Length < 3)
{ return _getPageMail(filterStr, (WellKnownFolderName)Convert.ToInt32(folderid), pageSize, lasttime, lastnum, searchType); }
return _getPageMail(filterStr, folderid, pageSize, lasttime, lastnum, searchType);
}
catch { return new List(); }
}
private List _getPageMail(string filterStr, WellKnownFolderName foldername, int pageSize, DateTime lasttime, int lastnum, int searchType)
{
int mailnum = pageSize + pageSize;
lastnum = lastnum < (pageSize / 2) ? 0 : (lastnum - pageSize / 2);
FindItemsResults- maillist = _getItemsList(filterStr, foldername, mailnum, lastnum, searchType);
if (maillist == null || maillist.Count() < 1 || maillist.ElementAt(0).DateTimeReceived < lasttime)
{
if (lastnum > 0)
{
lastnum = lastnum < pageSize ? 0 : (lastnum - pageSize);
return _getPageMail(filterStr, foldername, pageSize, lasttime, lastnum, searchType);
}
}
else if (maillist.Count() == mailnum && maillist.ElementAt(mailnum - pageSize).DateTimeReceived >= lasttime)
{
lastnum += pageSize;
if (maillist.ElementAt(mailnum - 1).DateTimeReceived >= lasttime)
{ lastnum += pageSize - 1; }
return _getPageMail(filterStr, foldername, pageSize, lasttime, lastnum, searchType);
}
int num = -1;
for (int i = 0; maillist != null && i < maillist.Count(); i++)
{
if (maillist.ElementAt(i).DateTimeReceived < lasttime)
{ num = i; break; }
}
List result = new List();
if (num < 0)
{ return result; }
return _getMailList(maillist, num, pageSize);
}
private List _getPageMail(string filterStr, string folderid, int pageSize, DateTime lasttime, int lastnum, int searchType)
{
int mailnum = pageSize + pageSize;
lastnum = lastnum < (pageSize / 2) ? 0 : (lastnum - pageSize / 2);
FindItemsResults- maillist = _getItemsList(filterStr, folderid, mailnum, lastnum, searchType);
if (maillist == null || maillist.Count() < 1 || maillist.ElementAt(0).DateTimeReceived < lasttime)
{
if (lastnum > 0)
{
lastnum = lastnum < pageSize ? 0 : (lastnum - pageSize);
return _getPageMail(filterStr, folderid, pageSize, lasttime, lastnum, searchType);
}
}
else if (maillist.Count() == mailnum && maillist.ElementAt(mailnum - pageSize).DateTimeReceived >= lasttime)
{
lastnum += pageSize;
if (maillist.ElementAt(mailnum - 1).DateTimeReceived >= lasttime)
{ lastnum += pageSize - 1; }
return _getPageMail(filterStr, folderid, pageSize, lasttime, lastnum, searchType);
}
int num = -1;
for (int i = 0; maillist != null && i < maillist.Count(); i++)
{
if (maillist.ElementAt(i).DateTimeReceived < lasttime)
{ num = i; break; }
}
List result = new List();
if (num < 0)
{ return result; }
return _getMailList(maillist, num, pageSize);
}
private FindItemsResults- _getItemsList(string filterStr, WellKnownFolderName foldername, int num, int offset, int searchType)
{
FindItemsResults- list;
ItemView iv = new ItemView(num) { Offset = offset };
if (string.IsNullOrEmpty(filterStr))
{ list = ExchService.FindItems(foldername, iv); }
else
{
SearchFilter sf = _getSearchFilt(filterStr, searchType);
list = ExchService.FindItems(foldername, sf, iv);
}
return list;
}
private FindItemsResults- _getItemsList(string filterStr, string folderid, int pageSize, int offset, int searchType)
{
FindItemsResults- list;
ItemView iv = new ItemView(pageSize) { Offset = offset };
if (string.IsNullOrEmpty(filterStr))
{ list = ExchService.FindItems(folderid, iv); }
else
{
SearchFilter sf = _getSearchFilt(filterStr, searchType);
list = ExchService.FindItems(folderid, sf, iv);
}
return list;
}
private SearchFilter _getSearchFilt(string filterStr, int searchType)
{
filterStr = filterStr.Trim();// 2017-9-14
switch (searchType)
{
case 1:
return new SearchFilter.SearchFilterCollection(LogicalOperator.Or
, new SearchFilter.ContainsSubstring(ItemSchema.Subject, filterStr)
, new SearchFilter.ContainsSubstring(ItemSchema.DisplayTo, filterStr)
, new SearchFilter.ContainsSubstring(ItemSchema.Body, filterStr)
, new SearchFilter.ContainsSubstring(PostItemSchema.From, filterStr)
);
case 2:
return new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.ContainsSubstring(ItemSchema.Subject, filterStr));
case 3:
return new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.ContainsSubstring(ItemSchema.Body, filterStr));
case 4:
return new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.ContainsSubstring(PostItemSchema.From, filterStr));
case 5:
return new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.ContainsSubstring(ItemSchema.DisplayTo, filterStr));
}
return null;
}
#endregion
private List _getMailAddressList(string maillist)
{
List result = new List();
string[] tmpmaillist = maillist.Split(',');
for (int i = 0; i < tmpmaillist.Length; i++)
{
if (tmpmaillist[i].Trim().Length > 0)
{
string[] tmpaddress = tmpmaillist[i].Split('[');
if (tmpaddress.Length > 1 && tmpaddress[0].Trim().Length > 0 && tmpaddress[1].Trim().Length > 1 && tmpaddress[1].Split(']')[0].Trim().Length > 0)
{ result.Add(new EmailAddress() { Name = tmpaddress[0], Address = tmpaddress[1].Split(']')[0] }); }
else
{ result.Add(new EmailAddress() { Address = tmpmaillist[i] }); }
}
}
return result;
}
private string _getMailAddressList(EmailAddressCollection maillist)
{
string result = "";
if (maillist == null)
{ return result; }
for (int i = 0; i < maillist.Count(); i++)
{
if (!string.IsNullOrEmpty(maillist[i].Address))
{
result += maillist[i].Address + ",";
}
//#region 原逻辑 已注释 2017-8-10
//if (string.IsNullOrEmpty(maillist[i].Name) || string.IsNullOrEmpty(maillist[i].Address))
//{
// if (string.IsNullOrEmpty(maillist[i].Name) && !string.IsNullOrEmpty(maillist[i].Address))
// {
// //解决写邮件或回复邮件时,邮件地址中存在英文逗号会把一个邮件地址当成两个显示的BUG 2017-8-9
// result += maillist[i].Address + ",";
// }
// else if (!string.IsNullOrEmpty(maillist[i].Name) && string.IsNullOrEmpty(maillist[i].Address))
// {
// //Name里的英文逗号换成全角逗号,解决写邮件或回复邮件时,邮件地址中存在英文逗号会把一个邮件地址当成两个显示的BUG 2017-6-22
// result += maillist[i].Name.Replace(',', ',').Replace(';', ';') + ",";
// }
//}
//else
//{
// //Name里的英文逗号换成全角逗号,解决写邮件或回复邮件时,邮件地址中存在英文逗号会把一个邮件地址当成两个显示的BUG 2017-6-22
// result += maillist[i].Address + ",";
//}
//#endregion
}
if (result.Length > 0)// && result.Substring(result.Length - 1, 1) == ",")
{
result = result.TrimEnd(',');
//result = result.Substring(0, result.Length - 1);
}
return result;
}
#endregion
///
/// 是否读取 收件人/发件人邮件地址(不读取 收件人/发件人邮件地址,可快速显示邮件列表),false读取,true不读取
/// 2017-9-6
///
private bool IsQuickShowEmailList
{
get
{
return System.Configuration.ConfigurationManager.AppSettings["IsQuickShowEmailList"] == "1";
}
}
///
/// 发送邮件 2017-9-27
///
///
///
///
///
///
///
///
///
///
/// list项的值为true是内嵌图片
///
public void SendMail(string accountName, string mailId, string subject, MessageBody mb
, string[][] toreciptlist, string[][] cclist, string[][] bcclist
, List namelist, List streamlist, List typelist
, List AttachmentIsInLine, List contentIDList, List itemTypeList
, Importance import)
{
string strAttachType = "ItemAttachment";
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
//读取原邮件,比较附件的ContentId,实现删除ItemAttachment附件
EmailMessage mailOld = null;
bool hasItemAttachment = itemTypeList.IndexOf(strAttachType) > -1;
if (hasItemAttachment)
{
mailOld = EmailMessage.Bind(ExchService, mailId);
}
EmailMessage em = new EmailMessage(ExchService);
em.Subject = subject;
em.Body = mb;
for (int i = 0; i < toreciptlist.Length; i++)
{ em.ToRecipients.Add(toreciptlist[i][0], toreciptlist[i][1]); }
for (int j = 0; j < cclist.Length; j++)
{ em.CcRecipients.Add(cclist[j][0], cclist[j][1]); }
for (int k = 0; k < bcclist.Length; k++)
{ em.BccRecipients.Add(bcclist[k][0], bcclist[k][1]); }
List addedItemAttachmentList = new List();//保存已添加的ItemAttachment附件
int x = 0;
for (int i = 0; namelist != null && i < namelist.Count; i++)
{
if (hasItemAttachment && itemTypeList[i] == strAttachType)
{
#region 实现ItemAttachment附件的发送 2017-11-21
for (int j = 0; j < mailOld.Attachments.Count(); j++)
{
if (mailOld.Attachments.ElementAt(j).GetType().Name == strAttachType && mailOld.Attachments.ElementAt(j).ContentId == contentIDList[i])
{
ItemAttachment- iat = em.Attachments.AddItemAttachment
- ();//要发送的附件
ItemAttachment itemAttach = (ItemAttachment)mailOld.Attachments.ElementAt(j);//原邮件的附件
itemAttach.Load(ItemSchema.MimeContent);
iat.Item.Body = itemAttach.Item.Body;
iat.Item.Importance = itemAttach.Item.Importance;
iat.Item.ItemClass = itemAttach.Item.ItemClass;
iat.Item.MimeContent = itemAttach.Item.MimeContent;
iat.Item.Subject = itemAttach.Item.Subject;
iat.ContentId = itemAttach.ContentId;
iat.ContentLocation = itemAttach.ContentLocation;
iat.ContentType = itemAttach.ContentType;
iat.IsInline = itemAttach.IsInline;
iat.Name = itemAttach.Name;
x++;
break;
}
}
#endregion
}
else
{
#region FileAttachment
em.Attachments.AddFileAttachment(namelist[i], streamlist[i]);
em.Attachments.ElementAt(x).ContentType = typelist[i];
em.Attachments.ElementAt(x).IsInline = AttachmentIsInLine[i];
em.Attachments.ElementAt(x).ContentId = contentIDList[i];
x++;
#endregion
}
}
em.Importance = import;
em.Save();
em.SendAndSaveCopy();
}
#endregion
#region 旧接口
///
/// 获取指定主目录的下一级子目录信息
///
///
///
///
public FoldInfo getFoldInfo(string accountName, WellKnownFolderName foldname)
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
FoldInfo fi = new FoldInfo();
//fi.Name = getFolderName(foldname);
SearchFilter sf = new SearchFilter.SearchFilterCollection(
LogicalOperator.And
, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false)
);
ItemView iv = new ItemView(int.MaxValue);
FolderView folderViews = new FolderView(int.MaxValue);
FindItemsResults- list = ExchService.FindItems(foldname, sf, iv);
fi.NoRead = list.Count();
FindFoldersResults folders = ExchService.FindFolders(foldname, folderViews);
fi.ChildNum = folders.Count();
fi.ChildFolds = new List();
for (int i = 0; i < fi.ChildNum; i++)
{
FoldInfo childfold = new FoldInfo();
childfold.ID = folders.ElementAt(i).Id.UniqueId;
childfold.Name = folders.ElementAt(i).DisplayName;
childfold.ChildNum = folders.ElementAt(i).ChildFolderCount;
if (folders.ElementAt(i).TotalCount > 0)
{ childfold.NoRead = folders.ElementAt(i).UnreadCount; }
fi.ChildFolds.Add(childfold);
}
//if (fi.ChildNum > 0)
//{
// fi.ChildFolds = new List();
// foreach (var it in folders)
// {
// FoldInfo childfold = new FoldInfo();
// childfold.ID = it.Id.UniqueId;
// childfold.Name = it.DisplayName;
// childfold.NoRead = it.UnreadCount;
// fi.ChildFolds.Add(childfold);
// // FindFolders本身就有查询未读数量,不需要再循环一次了
// //fi.ChildFolds.Add(getFoldInfo(accountName, childfold, 2));// 只需要一次查询
// }
//}
return fi;
}
///
/// 获取指定目录的下一级子目录信息
///
///
///
///
public FoldInfo getFoldInfo(string accountName, string folderid)
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
SearchFilter sf = new SearchFilter.SearchFilterCollection(
LogicalOperator.And
, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false)
);
ItemView iv = new ItemView(int.MaxValue);
FindItemsResults- list = ExchService.FindItems(folderid, sf, iv);
FoldInfo fi = new FoldInfo() { ID = folderid, NoRead = list.Count() };
FolderView folderViews = new FolderView(int.MaxValue);
FindFoldersResults folders = ExchService.FindFolders(folderid, folderViews);
fi.ChildNum = folders.Count();
fi.ChildFolds = new List();
for (int i = 0; i < fi.ChildNum; i++)
{
FoldInfo childfold = new FoldInfo();
childfold.ID = folders.ElementAt(i).Id.UniqueId;
childfold.Name = folders.ElementAt(i).DisplayName;
childfold.ChildNum = folders.ElementAt(i).ChildFolderCount;
if (folders.ElementAt(i).TotalCount > 0)
{ childfold.NoRead = folders.ElementAt(i).UnreadCount; }
fi.ChildFolds.Add(childfold);
}
return fi;
}
// 获取指定目录下的分页邮件列表,
// 新增接口,用于上拉加载,
// 在获取分页邮件的时候,要比对上次获取到的最后一封邮件时间,避免因为邮件变动导致获取的邮件不连贯
public List GetNextPageMail(string accountName, string filterStr, WellKnownFolderName foldname, int pageSize, DateTime lasttime
, int lastnum = 0, string filtertype = "")
{
lastnum += pageSize;
lastnum += pageSize;
FindItemsResults- list = getItemsList(accountName, filterStr, foldname, lastnum, filtertype);
int numuse = GetNextNum(list, lasttime, lastnum);
while (list.Count() == lastnum && numuse + pageSize > list.Count() - 1)
{
lastnum += pageSize;
if (list.ElementAt(list.Count() - 1).DateTimeReceived > lasttime)// 如果最后一封邮件都大于下一页邮件的起始时间,就多加一页
{ lastnum += pageSize; }
list = getItemsList(accountName, filterStr, foldname, lastnum, filtertype);
numuse = GetNextNum(list, lasttime, lastnum);
}
return GetNextPageMail(list, pageSize, numuse);
}
// 获取邮件列表中指定时间之后的最新一封邮件的位置
private int GetNextNum(FindItemsResults- list, DateTime lasttime, int lastnum = 0)
{
if (lastnum > list.Count() - 1)
{ lastnum = list.Count() - 1; }
while (lastnum > 0 && list.ElementAt(lastnum).DateTimeReceived < lasttime)
{ lastnum--; }
if (lastnum < 0)
{ return lastnum; }
while (lastnum < list.Count() && list.ElementAt(lastnum).DateTimeReceived >= lasttime)
{ lastnum++; }
return lastnum;
}
// 获取指定目录下的分页邮件列表,
// 新增接口,用于上拉加载,
// 在获取分页邮件的时候,要比对上次获取到的最后一封邮件时间,避免因为邮件变动导致获取的邮件不连贯
private List GetNextPageMail(FindItemsResults- list, int pageSize, int lastnum)
{
List infoList = new List();
if (lastnum < 0)
{ return infoList; }
string OwaID = "pspid";//pspid可以传任何值
for (int i = lastnum; i < list.Count() && i < lastnum + pageSize; i++)
{
//Item tmpInfo = ;//EmailMessage.Bind(ExchService, it.Id);
EmailMessage message = EmailMessage.Bind(_ExchService, list.ElementAt(i).Id);
MailInfo info = new MailInfo();
info.ID = message.Id.ToString();
info.StartTime = message.DateTimeCreated;
info.EndTime = message.LastModifiedTime;
info.IsRead = message.IsRead;
info.Importance = message.Importance;
MessageBody mb = message.Body;
mb.BodyType = BodyType.HTML;
//info.Descript = mb.Text;
info.Descript = "";
info.Subject = message.Subject;
info.WebClientEditFormQueryString = OwaUrl + message.WebClientEditFormQueryString;
info.WebClientReadFormQueryString = OwaUrl + message.WebClientReadFormQueryString + "&pspid=" + OwaID;
info.IsDraft = message.IsDraft;
if (message.From != null && message.From.Name != null)
{ info.From = message.From.Name + "[" + message.From.Address + "]"; }
info.AttachmentName = new List();
info.HasAttachment = message.HasAttachments;
if (message.Attachments.Count() > 0)
{
for (int j = 0; message.Attachments != null && j < message.Attachments.Count(); j++)
{
if (message.Attachments.ElementAt(j).IsInline == true)
{ continue; }
info.AttachmentName.Add(message.Attachments.ElementAt(j).Name);
}
}
infoList.Add(info);
}
return infoList;
}
// 获取指定目录下的新邮件列表,
// 新增接口,用于下拉刷新
// 获取上次刷新新邮件之后收到的新邮件列表
public List GetNewMail(FindItemsResults- list, DateTime lasttime)
{
List infoList = new List();
try
{
string OwaID = "pspid";//pspid可以传任何值
for (int i = 0; i < list.Count() && list.ElementAt(i).DateTimeReceived > lasttime; i++)
{
EmailMessage message = EmailMessage.Bind(_ExchService, list.ElementAt(i).Id);
MailInfo info = new MailInfo();
info.ID = message.Id.ToString();
info.StartTime = message.DateTimeCreated;
info.EndTime = message.LastModifiedTime;
info.IsRead = message.IsRead;
info.Importance = message.Importance;
MessageBody mb = message.Body;
mb.BodyType = BodyType.HTML;
//info.Descript = mb.Text;
info.Descript = "";
info.Subject = message.Subject;
info.WebClientEditFormQueryString = OwaUrl + message.WebClientEditFormQueryString;
info.WebClientReadFormQueryString = OwaUrl + message.WebClientReadFormQueryString + "&pspid=" + OwaID;
info.IsDraft = message.IsDraft;
if (message.From != null && message.From.Name != null)
{ info.From = message.From.Name + "<" + message.From.Address + ">"; }
info.AttachmentName = new List();
info.HasAttachment = message.HasAttachments;
if (message.Attachments.Count() > 0)
{
for (int j = 0; j < message.Attachments.Count(); j++)
{
if (message.Attachments.ElementAt(j).IsInline == true)
{ continue; }
info.AttachmentName.Add(message.Attachments.ElementAt(j).Name);
}
}
infoList.Add(info);
}
}
catch { }
return infoList;
}
// 获取指定主目录下的分页邮件列表
//internal List GetPageMail(string accountName, string filterStr, WellKnownFolderName foldname, int pageSize, ref int page, out int TatalPage)
//{
// FindItemsResults- list = getItemsList(accountName, filterStr, foldname);
// if (pageSize * (page - 1) > list.Count())
// { page = (list.Count() + pageSize - 1) / pageSize; }
// TatalPage = list.Count() / pageSize;
// return GetNextPageMail(list, pageSize, pageSize * (page - 1));
//}
// 获取指定目录下的分页邮件列表,
// 新增接口,用于上拉加载,
// 在获取分页邮件的时候,要比对上次获取到的最后一封邮件时间,避免因为邮件变动导致获取的邮件不连贯
public List GetNextPageMail(string accountName, string filterStr, string folderid, int pageSize, DateTime lasttime
, int lastnum = 0, string filtertype = "")
{
lastnum += pageSize;
lastnum += pageSize;
FindItemsResults- list = getItemsList(accountName, filterStr, folderid, lastnum, filtertype);
int numuse = GetNextNum(list, lasttime, lastnum);
while (list.Count() == lastnum && numuse + pageSize > list.Count() - 1)
{
lastnum += pageSize;
if (list.ElementAt(list.Count() - 1).DateTimeReceived > lasttime)// 如果最后一封邮件都大于下一页邮件的起始时间,就多加一页
{ lastnum += pageSize; }
list = getItemsList(accountName, filterStr, folderid, lastnum, filtertype);
numuse = GetNextNum(list, lasttime, lastnum);
}
return GetNextPageMail(list, pageSize, numuse);
}
// 获取指定目录下的新邮件列表,
// 新增接口,用于下拉刷新
// 获取上次刷新新邮件之后收到的新邮件列表
public List GetNewMail(string accountName, string filterStr, string folderid, DateTime lasttime, string filtertype = "")
{
int pageSize = 10;
if (ConfigurationManager.AppSettings["PageSize"] != null)
{ pageSize = Convert.ToInt32(ConfigurationManager.AppSettings["PageSize"]); }
int numnew = pageSize;
FindItemsResults- list = getItemsList(accountName, filterStr, folderid, numnew, filtertype);
while (list.ElementAt(list.Count() - 1).DateTimeReceived > lasttime)
{
numnew += pageSize;
list = getItemsList(accountName, filterStr, folderid, numnew, filtertype);
}
return GetNewMail(list, lasttime);
}
public List GetNewMail(string accountName, string filterStr, WellKnownFolderName foldername, DateTime lasttime, string filtertype = "")
{
int pageSize = 10;
if (ConfigurationManager.AppSettings["PageSize"] != null)
{ pageSize = Convert.ToInt32(ConfigurationManager.AppSettings["PageSize"]); }
int numnew = pageSize;
FindItemsResults- list = getItemsList(accountName, filterStr, foldername, numnew, filtertype);
while (list.ElementAt(list.Count() - 1).DateTimeReceived > lasttime)
{
numnew += pageSize;
list = getItemsList(accountName, filterStr, foldername, numnew, filtertype);
}
return GetNewMail(list, lasttime);
}
// 获取指定目录下的分页邮件列表
//internal List GetPageMail(string accountName, string filterStr, FolderId folderid, int pageSize, ref int page, out int TatalPage)
//{
// FindItemsResults- list = getItemsList(accountName, filterStr, folderid);
// TatalPage = (list.Count() + pageSize - 1) / pageSize;
// if (page > TatalPage)
// { page = TatalPage; }
// return GetNextPageMail(list, pageSize, pageSize * (page - 1));
//}
// 获取指定主目录下的分页邮件列表
private FindItemsResults- getItemsList(string accountName, string filterStr, WellKnownFolderName foldname
, int num = int.MaxValue, string filtertype = "")
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
FindItemsResults- list;
ItemView iv = new ItemView(num);
if (string.IsNullOrEmpty(filterStr))
{ list = ExchService.FindItems(foldname, iv); }
else
{
SearchFilter sf = getSearchFilt(filterStr, filtertype);
list = ExchService.FindItems(foldname, sf, iv);
}
return list;
}
private SearchFilter getSearchFilt(string filterStr, string filtertype)
{
if (string.IsNullOrEmpty(filterStr))
{ return null; }
SearchFilter sf = new SearchFilter.SearchFilterCollection(
LogicalOperator.Or
, new SearchFilter.ContainsSubstring(ItemSchema.Subject, filterStr)
, new SearchFilter.ContainsSubstring(ItemSchema.DisplayTo, filterStr)
, new SearchFilter.ContainsSubstring(ItemSchema.Body, filterStr) //增加正文查询功能2017-08-25
, new SearchFilter.ContainsSubstring(PostItemSchema.From, filterStr)
);
if (filtertype == MailSearchType.From.ToString())
{
sf = new SearchFilter.SearchFilterCollection(
LogicalOperator.Or
, new SearchFilter.ContainsSubstring(PostItemSchema.From, filterStr)
);
}
else if (filtertype == MailSearchType.To.ToString())
{
sf = new SearchFilter.SearchFilterCollection(
LogicalOperator.Or
, new SearchFilter.ContainsSubstring(ItemSchema.DisplayTo, filterStr)
);
}
else if (filtertype == MailSearchType.Subject.ToString())
{
sf = new SearchFilter.SearchFilterCollection(
LogicalOperator.Or
, new SearchFilter.ContainsSubstring(ItemSchema.Subject, filterStr)
);
}
return sf;
}
// 获取指定目录下的指定数量的邮件列表
private FindItemsResults- getItemsList(string accountName, string filterStr, string folderid, int num = int.MaxValue, string filtertype = "")
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
FindItemsResults- list;
ItemView iv = new ItemView(num);
if (string.IsNullOrEmpty(filterStr))
{ list = ExchService.FindItems(folderid, iv); }
else
{
SearchFilter sf = getSearchFilt(filterStr, filtertype);
list = ExchService.FindItems(folderid, sf, iv);
}
return list;
}
public void DeleteMail(string accountName, string Id)
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
EmailMessage tmpInfo = EmailMessage.Bind(ExchService, Id);
if (tmpInfo == null)
{ return; }
bool isinDeletedItems = false;
#region 在DeletedItems主目录下查找指定id对应的邮件,由于不能用id直接查询,换成DateTimeCreated查询,然后再比对id确认是否真的在DeletedItems目录下
SearchFilter sf = new SearchFilter.SearchFilterCollection(
LogicalOperator.And
, new SearchFilter.IsEqualTo(EmailMessageSchema.DateTimeCreated, tmpInfo.DateTimeCreated)
);
ItemView iv = new ItemView(int.MaxValue);
FindItemsResults- list = ExchService.FindItems(WellKnownFolderName.DeletedItems, sf, iv);
if (list != null && list.Count() > 0)
{
foreach (Item o in list)
{
if (o.Id == tmpInfo.Id)
{
isinDeletedItems = true;
break;
}
}
}
// 不在DeletedItems目录下时,使用邮件的ParentFolderId来跟DeletedItems的所有子目录进行比对,确认是否在子目录下
if (!isinDeletedItems)
{
FoldInfo fi = getFoldInfo(accountName, WellKnownFolderName.DeletedItems);
isinDeletedItems = isinFolder(fi, tmpInfo.ParentFolderId.UniqueId);
}
#endregion
if (isinDeletedItems)
{ tmpInfo.Delete(DeleteMode.HardDelete); }
else
{ tmpInfo.Delete(DeleteMode.MoveToDeletedItems); }
}
private bool isinFolder(FoldInfo fi, string id)
{
try
{
for (int i = 0; i < fi.ChildNum; i++)
{
if (fi.ChildFolds[i].ID == id)
{ return true; }
if (isinFolder(fi.ChildFolds[i], id))
{ return true; }
}
return false;
}
catch
{ return false; }
}
#endregion
#region 邮件接口,供其他项目调用
///
/// 获取邮件的所有字段信息的列表 2017-9-4
///
/// 目录ID
/// 返回数量
/// 邮件位置
/// 查询条件
/// 邮箱账号
///
public List GetEmailList(string folderid, int num, int offset, string filterStr = "", string accountName = "")
{
if (accountName != "")
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
}
FindItemsResults- maillist = null;
if (folderid.Length < 3)
{ maillist = _getItemsList(filterStr, (WellKnownFolderName)Convert.ToInt32(folderid), num, offset); }
else
{
maillist = _getItemsList(filterStr, folderid, num, offset);
}
List result = new List();
if (num < 0)
{ return result; }
return ItemsResult2MailInfoList(maillist, true);
}
#endregion
#region 联系人接口 2017-10-18
private FindItemsResults- getItemsList(string filterStr, WellKnownFolderName foldername, int num, int offset)
{
FindItemsResults- list;
ItemView iv = new ItemView(num) { Offset = offset };
//Surname
iv.OrderBy.Add(ContactSchema.Surname, SortDirection.Ascending);
//iv.OrderBy.Add(ContactSchema.GivenName, SortDirection.Ascending);
if (string.IsNullOrEmpty(filterStr))
{ list = ExchService.FindItems(foldername, iv); }
else
{
SearchFilter sf = getSearchFilt(filterStr);
list = ExchService.FindItems(foldername, sf, iv);
}
return list;
}
private SearchFilter getSearchFilt(string filterStr)
{
filterStr = filterStr.Trim();
//subject对应GivenName
return new SearchFilter.SearchFilterCollection(
LogicalOperator.Or
, new SearchFilter.ContainsSubstring(ContactSchema.MobilePhone, filterStr)
, new SearchFilter.ContainsSubstring(ContactSchema.NickName, filterStr)
, new SearchFilter.ContainsSubstring(ContactSchema.MiddleName, filterStr)
, new SearchFilter.ContainsSubstring(ContactSchema.EmailAddress1, filterStr)
, new SearchFilter.ContainsSubstring(ContactSchema.EmailAddress2, filterStr)
, new SearchFilter.ContainsSubstring(ContactSchema.EmailAddress3, filterStr)
, new SearchFilter.ContainsSubstring(ContactSchema.FileAs, filterStr)
, new SearchFilter.ContainsSubstring(ContactSchema.GivenName, filterStr)
, new SearchFilter.ContainsSubstring(ContactSchema.JobTitle, filterStr)
, new SearchFilter.ContainsSubstring(ContactSchema.BusinessPhone, filterStr)
, new SearchFilter.ContainsSubstring(ContactSchema.CompanyName, filterStr)
, new SearchFilter.ContainsSubstring(ContactSchema.MobilePhone, filterStr)
, new SearchFilter.ContainsSubstring(ContactSchema.Department, filterStr)
, new SearchFilter.ContainsSubstring(ContactSchema.JobTitle, filterStr)
);
}
///
/// 获取个人联系人列表
///
///
///
///
///
///
///
public List GetContactList(string accountName, string filterStr, string folderid, int pageSize, int lastnum, bool isAll)
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
//Microsoft.Exchange.WebServices.Data.Contact contact = new Microsoft.Exchange.WebServices.Data.Contact(ExchService);
FindItemsResults- contactInfoList = getItemsList(filterStr, (WellKnownFolderName)Convert.ToInt32(folderid), pageSize, lastnum);
return _getcontactInfoList(ExchService, contactInfoList, lastnum, pageSize, isAll);
}
//private List _getPageContact(string filterStr, WellKnownFolderName foldername, int pageSize, int lastnum)
//{
// int mailnum = pageSize + pageSize;
// lastnum = lastnum < (pageSize / 2) ? 0 : (lastnum - pageSize / 2);
// FindItemsResults- maillist = getItemsList(filterStr, foldername, mailnum, lastnum);
// if (maillist == null || maillist.Count() < 1)
// {
// if (lastnum > 0)
// {
// lastnum = lastnum < pageSize ? 0 : (lastnum - pageSize);
// return _getPageContact(filterStr, foldername, pageSize, lastnum);
// }
// }
// else if (maillist.Count() == mailnum && maillist.ElementAt(mailnum - pageSize).DateTimeReceived >= lasttime)
// {
// lastnum += pageSize;
// if (maillist.ElementAt(mailnum - 1).DateTimeReceived >= lasttime)
// { lastnum += pageSize - 1; }
// return _getPageContact(filterStr, foldername, pageSize, lastnum);
// }
// int num = -1;
// for (int i = 0; maillist != null && i < maillist.Count(); i++)
// {
// if (maillist.ElementAt(i).DateTimeReceived < lasttime)
// { num = i; break; }
// }
// List result = new List();
// if (num < 0)
// { return result; }
// return _getMailList(maillist, num, pageSize);
//}
private List _getcontactInfoList(ExchangeService ex, FindItemsResults- contactInfolist, int startnum, int pageSize, bool isAll)
{
List result = new List();
for (int i = startnum; i < startnum + pageSize && i < contactInfolist.Count(); i++)
{
#region
Microsoft.Exchange.WebServices.Data.Contact message;
contactInfo info = new contactInfo();
if (contactInfolist.ElementAt(i).GetType().Name == "ContactGroup")
{
//Microsoft.Exchange.WebServices.Data.ContactGroup contactGroup = (Microsoft.Exchange.WebServices.Data.ContactGroup)contactInfolist.ElementAt(i);
//GroupMemberCollection gmlist = contactGroup.Members;
//for (int j = 0; j < gmlist.Count; j++)
//{
// GroupMember gm = gmlist[j];
//}
continue;
}
else
{
message = (Microsoft.Exchange.WebServices.Data.Contact)contactInfolist.ElementAt(i);
info.ID = message.Id.ToString();
EmailAddress em;
if (message.EmailAddresses.TryGetValue(EmailAddressKey.EmailAddress1, out em))
{
var bEmail = message.EmailAddresses[EmailAddressKey.EmailAddress1];
info.EmailAddress = message.EmailAddresses[EmailAddressKey.EmailAddress1] == null ? "" : bEmail.Address;
if (info.EmailAddress != null && info.EmailAddress.IndexOf("@") < 0)
{
info.EmailAddress = "";
if (ConfigurationManager.AppSettings["IsReadEmail"] == "1")
{
Microsoft.Exchange.WebServices.Data.Contact tmpinfo = Microsoft.Exchange.WebServices.Data.Contact.Bind(ExchService, info.ID);
if (tmpinfo.EmailAddresses.TryGetValue(EmailAddressKey.EmailAddress1, out em))
{
bEmail = tmpinfo.EmailAddresses[EmailAddressKey.EmailAddress1];
info.EmailAddress = tmpinfo.EmailAddresses[EmailAddressKey.EmailAddress1] == null ? "" : bEmail.Address;
}
}
}
if (!isAll && string.IsNullOrEmpty(info.EmailAddress))
continue;
}
if (!string.IsNullOrEmpty(message.DisplayName))
{
info.DisplayName = message.DisplayName.Replace(",", " ").Replace(";", " ");
}
else
info.DisplayName = string.Empty;
if (!string.IsNullOrEmpty(message.GivenName))
info.GivenName = message.GivenName;
else
info.GivenName = string.Empty;
if (!string.IsNullOrEmpty(message.CompanyName))
info.CompanyName = message.CompanyName;
else
info.CompanyName = string.Empty;
if (!string.IsNullOrEmpty(message.JobTitle))
info.JobTitle = message.JobTitle;
if (!string.IsNullOrEmpty(message.Department))
info.Department = message.Department;
else
info.Department = string.Empty;
if (!string.IsNullOrEmpty(message.FileAs))
info.FileAs = message.FileAs;
else
info.FileAs = string.Empty;
if (!string.IsNullOrEmpty(message.Surname))
info.Surname = message.Surname;
else
info.Surname = string.Empty;
string PhoneNumber;
if (message.PhoneNumbers.TryGetValue(PhoneNumberKey.BusinessPhone, out PhoneNumber))
{
var bPhone = message.PhoneNumbers[PhoneNumberKey.BusinessPhone];
info.OfficePhNumbers = message.PhoneNumbers[PhoneNumberKey.BusinessPhone] == null ? "" : bPhone.ToString();
}
if (message.PhoneNumbers.TryGetValue(PhoneNumberKey.MobilePhone, out PhoneNumber))
{
var mPhone = message.PhoneNumbers[PhoneNumberKey.MobilePhone];
info.MobilePhNumbers = message.PhoneNumbers[PhoneNumberKey.MobilePhone] == null ? "" : mPhone.ToString();
}
}
result.Add(info);
#endregion
}
return result;
}
///
/// 删除指定删除人
///
/// 邮箱用户名
/// 联系人ID
/// 是否物理删除
public void DeleteContact(string accountName, string Id, bool isHardDelete)
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
Microsoft.Exchange.WebServices.Data.Contact tmpInfo = Microsoft.Exchange.WebServices.Data.Contact.Bind(ExchService, Id);
if (tmpInfo == null)
{ return; }
if (isHardDelete)
tmpInfo.Delete(DeleteMode.HardDelete);
else
tmpInfo.Delete(DeleteMode.MoveToDeletedItems);
}
///
/// 修改指定联系人
///
/// 邮箱用户名
/// 联系人ID
/// 联系人对象
public void UpdateContact(string accountName, string Id, contactInfo contact)
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
Microsoft.Exchange.WebServices.Data.Contact tmpInfo = Microsoft.Exchange.WebServices.Data.Contact.Bind(ExchService, Id);
if (tmpInfo == null)
{ return; }
if (!string.IsNullOrEmpty(contact.CompanyName))
tmpInfo.CompanyName = contact.CompanyName;
if (!string.IsNullOrEmpty(contact.Department))
tmpInfo.Department = contact.Department;
if (!string.IsNullOrEmpty(contact.DisplayName))
tmpInfo.DisplayName = contact.DisplayName;
if (!string.IsNullOrEmpty(contact.EmailAddress))
{
tmpInfo.EmailAddresses[EmailAddressKey.EmailAddress1] = new EmailAddress(contact.EmailAddress);
}
if (!string.IsNullOrEmpty(contact.GivenName))
tmpInfo.GivenName = contact.GivenName;
if (!string.IsNullOrEmpty(contact.JobTitle))
tmpInfo.JobTitle = contact.JobTitle;
if (!string.IsNullOrEmpty(contact.FileAs))
tmpInfo.FileAs = contact.FileAs;
if (!string.IsNullOrEmpty(contact.Surname))
tmpInfo.Surname = contact.Surname;
if (!string.IsNullOrEmpty(contact.OfficePhNumbers))
{
tmpInfo.PhoneNumbers[PhoneNumberKey.BusinessPhone] = contact.OfficePhNumbers;
}
if (!string.IsNullOrEmpty(contact.MobilePhNumbers))
{
tmpInfo.PhoneNumbers[PhoneNumberKey.MobilePhone] = contact.MobilePhNumbers;
}
tmpInfo.Update(ConflictResolutionMode.AlwaysOverwrite);
}
///
/// 修改联系人测试用
///
/// 邮箱用户名
/// 联系人ID
public void UpdateContact(string accountName, string Id, string EmailAddress, string OfficePhNumbers, string MobilePhNumbers, string JobTitle)
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
Microsoft.Exchange.WebServices.Data.Contact tmpInfo = Microsoft.Exchange.WebServices.Data.Contact.Bind(ExchService, Id);
if (tmpInfo == null)
{ return; }
if (!string.IsNullOrEmpty(EmailAddress))
{
tmpInfo.EmailAddresses[EmailAddressKey.EmailAddress1] = new EmailAddress(EmailAddress);
}
if (!string.IsNullOrEmpty(JobTitle))
tmpInfo.JobTitle = JobTitle;
if (!string.IsNullOrEmpty(OfficePhNumbers))
{
tmpInfo.PhoneNumbers[PhoneNumberKey.BusinessPhone] = OfficePhNumbers;
}
if (!string.IsNullOrEmpty(MobilePhNumbers))
{
tmpInfo.PhoneNumbers[PhoneNumberKey.MobilePhone] = MobilePhNumbers;
}
tmpInfo.Update(ConflictResolutionMode.AlwaysOverwrite);
}
///
/// 增加联系人
///
/// 邮箱用户名
/// 联系人ID
/// 联系人对象
public void AddContact(string accountName, contactInfo contact)
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
Microsoft.Exchange.WebServices.Data.Contact tmpInfo = new Microsoft.Exchange.WebServices.Data.Contact(ExchService);
if (!string.IsNullOrEmpty(contact.CompanyName))
tmpInfo.CompanyName = contact.CompanyName;
if (!string.IsNullOrEmpty(contact.Department))
tmpInfo.Department = contact.Department;
if (!string.IsNullOrEmpty(contact.DisplayName))
tmpInfo.DisplayName = contact.DisplayName;
if (!string.IsNullOrEmpty(contact.EmailAddress))
{
tmpInfo.EmailAddresses[EmailAddressKey.EmailAddress1] = new EmailAddress(contact.EmailAddress);
}
if (!string.IsNullOrEmpty(contact.GivenName))
tmpInfo.GivenName = contact.GivenName;
if (!string.IsNullOrEmpty(contact.JobTitle))
tmpInfo.JobTitle = contact.JobTitle;
if (!string.IsNullOrEmpty(contact.FileAs))
tmpInfo.FileAs = contact.FileAs;
if (!string.IsNullOrEmpty(contact.Surname))
tmpInfo.Surname = contact.Surname;
if (!string.IsNullOrEmpty(contact.OfficePhNumbers))
{
tmpInfo.PhoneNumbers[PhoneNumberKey.BusinessPhone] = contact.OfficePhNumbers;
}
if (!string.IsNullOrEmpty(contact.MobilePhNumbers))
{
tmpInfo.PhoneNumbers[PhoneNumberKey.MobilePhone] = contact.MobilePhNumbers;
}
tmpInfo.Save();
}
///
/// 增加指定联系人测试用
///
/// 邮箱用户名
/// 联系人ID
public void AddContact(string accountName, string CompanyName, string Department, string DisplayName, string EmailAddress, string GivenName, string JobTitle, string FileAs, string Surname, string OfficePhNumbers, string MobilePhNumbers)
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
Microsoft.Exchange.WebServices.Data.Contact tmpInfo = new Microsoft.Exchange.WebServices.Data.Contact(ExchService);
if (!string.IsNullOrEmpty(CompanyName))
tmpInfo.CompanyName = CompanyName;
if (!string.IsNullOrEmpty(Department))
tmpInfo.Department = Department;
if (!string.IsNullOrEmpty(DisplayName))
tmpInfo.DisplayName = DisplayName;
if (!string.IsNullOrEmpty(EmailAddress))
{
tmpInfo.EmailAddresses[EmailAddressKey.EmailAddress1] = new EmailAddress(EmailAddress);
}
if (!string.IsNullOrEmpty(GivenName))
tmpInfo.GivenName = GivenName;
if (!string.IsNullOrEmpty(JobTitle))
tmpInfo.JobTitle = JobTitle;
if (!string.IsNullOrEmpty(FileAs))
tmpInfo.FileAs = FileAs;
if (!string.IsNullOrEmpty(Surname))
tmpInfo.Surname = Surname;
if (!string.IsNullOrEmpty(OfficePhNumbers))
{
tmpInfo.PhoneNumbers[PhoneNumberKey.BusinessPhone] = OfficePhNumbers;
}
if (!string.IsNullOrEmpty(MobilePhNumbers))
{
tmpInfo.PhoneNumbers[PhoneNumberKey.MobilePhone] = MobilePhNumbers;
}
tmpInfo.Save();
}
///
/// 获取指定联系人信息
///
///
///
///
public contactInfo GetContact(string accountName, string Id)
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
Microsoft.Exchange.WebServices.Data.Contact tmpinfo = Microsoft.Exchange.WebServices.Data.Contact.Bind(ExchService, Id);
contactInfo info = new contactInfo();
if (tmpinfo == null)
{ return null; }
info.EmailAddress = string.Empty;
info.DisplayName = string.Empty;
info.GivenName = string.Empty;
info.JobTitle = string.Empty;
info.FileAs = string.Empty;
info.Surname = string.Empty;
info.OfficePhNumbers = string.Empty;
info.MobilePhNumbers = string.Empty;
EmailAddress em;
if (tmpinfo.EmailAddresses.TryGetValue(EmailAddressKey.EmailAddress1, out em))
{
info.EmailAddress = tmpinfo.EmailAddresses[EmailAddressKey.EmailAddress1].Address;
}
info.ID = tmpinfo.Id.ToString();
if (!string.IsNullOrEmpty(tmpinfo.DisplayName))
{
info.DisplayName = tmpinfo.DisplayName.Replace(",", " ").Replace(";", " ");
}
info.GivenName = tmpinfo.GivenName;
info.CompanyName = tmpinfo.CompanyName;
info.JobTitle = tmpinfo.JobTitle;
info.Department = tmpinfo.Department;
info.FileAs = tmpinfo.FileAs;
info.Surname = tmpinfo.Surname;
string PhoneNumber;
if (tmpinfo.PhoneNumbers.TryGetValue(PhoneNumberKey.BusinessPhone, out PhoneNumber))
{
var bPhone = tmpinfo.PhoneNumbers[PhoneNumberKey.BusinessPhone];
info.OfficePhNumbers = tmpinfo.PhoneNumbers[PhoneNumberKey.BusinessPhone] == null ? "" : bPhone.ToString();
}
if (tmpinfo.PhoneNumbers.TryGetValue(PhoneNumberKey.MobilePhone, out PhoneNumber))
{
var mPhone = tmpinfo.PhoneNumbers[PhoneNumberKey.MobilePhone];
info.MobilePhNumbers = tmpinfo.PhoneNumbers[PhoneNumberKey.MobilePhone] == null ? "" : mPhone.ToString();
}
return info;
}
#endregion
#region 日历功能 2017-12-01
///
/// 根据用户账号和當前日期获取其日程安排
/// 返回在當前日期内的安排
///
/// 當前帳號
/// 當前日期
/// 返回數量
/// 返回多少月的数据
///
public List GetAppointmentsList(string accountName, DateTime currDate, int returnCount, int Month)
{
List infoList = new List();
if (ExchService != null)
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
CalendarView cv = new CalendarView(currDate.Date, currDate.Date.AddMonths(Month), returnCount);
PropertySet propSet = new PropertySet(AppointmentSchema.Subject,
AppointmentSchema.Location,
AppointmentSchema.Start,
AppointmentSchema.End,
AppointmentSchema.Id,
AppointmentSchema.IsAllDayEvent,
AppointmentSchema.IsReminderSet,
AppointmentSchema.DateTimeCreated,
AppointmentSchema.LastModifiedTime,
AppointmentSchema.ReminderMinutesBeforeStart,
AppointmentSchema.IsCancelled,
AppointmentSchema.AppointmentType);
//CalendarView cv = new CalendarView(currDate.Date, currDate.AddYears(2), returnCount);
FindItemsResults list = ExchService.FindAppointments(WellKnownFolderName.Calendar, cv);
foreach (Appointment tmpInfo in list)
{
if (!tmpInfo.IsCancelled)
{
AppointmentInfo info = new AppointmentInfo();
info.ID = tmpInfo.Id.ToString();
info.StartTime = tmpInfo.Start;
info.EndTime = tmpInfo.End;
info.Subject = tmpInfo.Subject;
info.Location = tmpInfo.Location;
info.isAllDayEvent = tmpInfo.IsAllDayEvent == true ? "1" : "0";
info.IsReminderSet = ((Microsoft.Exchange.WebServices.Data.Item)(tmpInfo)).IsReminderSet == true ? "1" : "0";
info.CreateTime = ((Microsoft.Exchange.WebServices.Data.Item)(tmpInfo)).DateTimeCreated;
info.UpdateTime = ((Microsoft.Exchange.WebServices.Data.Item)(tmpInfo)).LastModifiedTime;
info.ReminderMinutesBeforeStart = ((Microsoft.Exchange.WebServices.Data.Item)(tmpInfo)).ReminderMinutesBeforeStart;
//昨天开始的整天事件,跨天
if (currDate.Date >= info.StartTime && currDate.Date <= info.EndTime && info.isAllDayEvent == "1")
continue;
infoList.Add(info);
}
}
}
return infoList;
}
public List GetCalendarsList(string accountName, DateTime currDate, int returnCount, int Month, string updateDate)
{
List infoList = new List();
if (ExchService != null)
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
//CalendarView cv = new CalendarView(currDate.Date, currDate.Date.AddMonths(Month), returnCount);
//FindItemsResults list = ExchService.FindAppointments(WellKnownFolderName.Calendar, cv);
FindItemsResults- list = getCalendarItemsList(currDate, Month, updateDate, WellKnownFolderName.Calendar, returnCount);
foreach (Appointment tmpInfo in list)
{
if (!tmpInfo.IsCancelled)
{
Appointment recurrMaster = Appointment.Bind(ExchService, tmpInfo.Id);
AppointmentInfo info = new AppointmentInfo();
info.ID = tmpInfo.Id.ToString();
info.StartTime = tmpInfo.Start;
info.EndTime = tmpInfo.End;
info.Subject = tmpInfo.Subject;
info.Location = tmpInfo.Location;
info.isAllDayEvent = tmpInfo.IsAllDayEvent == true ? "1" : "0";
info.IsReminderSet = ((Microsoft.Exchange.WebServices.Data.Item)(tmpInfo)).IsReminderSet == true ? "1" : "0";
info.CreateTime = ((Microsoft.Exchange.WebServices.Data.Item)(tmpInfo)).DateTimeCreated;
info.UpdateTime = ((Microsoft.Exchange.WebServices.Data.Item)(tmpInfo)).LastModifiedTime;
info.ReminderMinutesBeforeStart = ((Microsoft.Exchange.WebServices.Data.Item)(tmpInfo)).ReminderMinutesBeforeStart;
//info.AppointmentType = tmpInfo.AppointmentType.ToString();
infoList.Add(info);
}
}
}
return infoList;
}
private FindItemsResults- getCalendarItemsList(DateTime currDate, int Month, string updateDate, WellKnownFolderName foldername, int num)
{
FindItemsResults- list;
ItemView iv = new ItemView(num);
//指定查询字段
//PropertySet propSet = new PropertySet(AppointmentSchema.Subject,
// AppointmentSchema.Id,
// AppointmentSchema.IsCancelled,
// AppointmentSchema.Start,
// AppointmentSchema.End,
// AppointmentSchema.IsAllDayEvent,
// AppointmentSchema.IsReminderSet,
// AppointmentSchema.DateTimeCreated,
// AppointmentSchema.LastModifiedTime,
// AppointmentSchema.ReminderMinutesBeforeStart,
// AppointmentSchema.Location,
// AppointmentSchema.End,
// AppointmentSchema.AppointmentType);
//iv.PropertySet = propSet;
SearchFilter sf = getSearchCalendarFilt(currDate, Month, updateDate);
list = ExchService.FindItems(foldername, sf, iv);
return list;
}
///
/// 日历查询筛选条件
///
/// 当前日期
/// 查询多少月
/// 获取日历的最后修改时间
///
private SearchFilter getSearchCalendarFilt(DateTime currDate, int Month, string updateDate)
{
//过滤条件为空
if (string.IsNullOrEmpty(updateDate))
{
return new SearchFilter.SearchFilterCollection(
LogicalOperator.And
, new SearchFilter.IsGreaterThanOrEqualTo(AppointmentSchema.Start, currDate)
, new SearchFilter.IsLessThanOrEqualTo(AppointmentSchema.End, currDate.AddMonths(Month))
);
}
else
{
return new SearchFilter.SearchFilterCollection(
LogicalOperator.And
, new SearchFilter.IsGreaterThanOrEqualTo(AppointmentSchema.Start, currDate)
, new SearchFilter.IsLessThanOrEqualTo(AppointmentSchema.End, currDate.AddMonths(Month))
, new SearchFilter.IsGreaterThan(AppointmentSchema.LastModifiedTime, DateTime.Parse(updateDate))
);
}
}
///
/// 创建周期性的约会
///
///
///
public void CreateAppointment(string accountName, AppointmentInfo appInfo)
{
if (ExchService != null)
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
//实例化一个Appointment
Appointment appointment = new Appointment(ExchService);
//约会主题
appointment.Subject = appInfo.Subject;
//约会开始时间
appointment.Start = appInfo.StartTime;
//约会结束时间
appointment.End = appInfo.EndTime;
//约会的位置
appointment.Location = appInfo.Location;
//是否是整天事件
appointment.IsAllDayEvent = bool.Parse(appInfo.isAllDayEvent);
//是否提醒
appointment.IsReminderSet = bool.Parse(appInfo.IsReminderSet);
//提醒的间隔时间
appointment.ReminderMinutesBeforeStart = appInfo.ReminderMinutesBeforeStart;
//添加与会者
//appointment.RequiredAttendees.Add("");
//appointment.Recurrence = new Recurrence.WeeklyPattern(
//appointment.Start,
//1,/*每一周一次*/
//DayOfTheWeek.Saturday
//);
//可以设置发送通知的方式,如:
//Appointment.Save(SendInvitationsMode.SendOnlyToAll)
appointment.Save(WellKnownFolderName.Calendar);
}
}
///
/// 修改周期性约会
///
///
///
///
public void UpdateAppointment(string accountName, string Id, AppointmentInfo appInfo)
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
Microsoft.Exchange.WebServices.Data.Appointment tmpInfo = Microsoft.Exchange.WebServices.Data.Appointment.Bind(ExchService, Id);
if (tmpInfo == null)
{ return; }
if (!string.IsNullOrEmpty(appInfo.Subject))
tmpInfo.Subject = appInfo.Subject;
if (appInfo.StartTime != null)
tmpInfo.Start = appInfo.StartTime;
if (appInfo.EndTime != null)
tmpInfo.End = appInfo.EndTime;
if (!string.IsNullOrEmpty(appInfo.Location))
tmpInfo.Location = appInfo.Location;
if (!string.IsNullOrEmpty(appInfo.isAllDayEvent))
tmpInfo.IsAllDayEvent = bool.Parse(appInfo.isAllDayEvent);
if (!string.IsNullOrEmpty(appInfo.IsReminderSet))
tmpInfo.IsReminderSet = bool.Parse(appInfo.IsReminderSet);
if (appInfo.ReminderMinutesBeforeStart != 0)
tmpInfo.ReminderMinutesBeforeStart = appInfo.ReminderMinutesBeforeStart;
tmpInfo.Update(ConflictResolutionMode.AlwaysOverwrite);
}
#endregion
#region 邮件接口 2017-10-27
#region 邮件分页相关
///
/// 分页读取邮件 2017-10-27
///
/// 邮箱账号
/// 查询条件
/// 目录ID
/// 每页显示的记录数量
///
/// 已读取的记录总数量
/// 搜索类别:主题,收件人等
///
public List GetPageMailList(string accountName, string filterStr, string folderId, int pageSize, DateTime lastLoadTime, int alreadyReadTotal, string filterType)
{
try
{
if (string.IsNullOrEmpty(folderId))
{
return new List();
}
if (folderId.Length < 3)
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
return GetPageMailInfo(filterStr, (WellKnownFolderName)Convert.ToInt32(folderId), pageSize, lastLoadTime, alreadyReadTotal, filterType, null);
}
else
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
return GetPageMailInfo(filterStr, folderId, pageSize, lastLoadTime, alreadyReadTotal, filterType, null);
}
}
catch { return new List(); }
}
///
/// 获取指定目录下,按指定关键词在指定偏移量后搜索到的指定时间之后的指定数量的邮件 2017-10-27
///
/// 过滤条件
/// 目录名/param>
/// 每页显示的记录数量
/// 最后一次加载数据的时间
/// 已读取的记录总数量
/// 搜索类别:主题,收件人等
/// 已读取的list
///
public List GetPageMailInfo(string filterStr, WellKnownFolderName folderName, int pageSize, DateTime lastLoadTime, int alreadyReadTotal, string filterType, List listMailInfo)
{
List listNewMailInfo = new List();
if (listMailInfo != null && listMailInfo.Count > 0)
{
listNewMailInfo = listMailInfo;
}
FindItemsResults- itemsResults = GetItemsResults(filterStr, folderName, pageSize, alreadyReadTotal, filterType);
bool isNeedReadData = false;//是否继续往下读取数据
if (itemsResults != null && itemsResults.Count() > 0)
{
ReadMailList(itemsResults, listNewMailInfo, pageSize, alreadyReadTotal);
//当前目录的总记录数>分页数量,则可以继续往下读取数据
isNeedReadData = itemsResults.TotalCount > pageSize;
alreadyReadTotal = listNewMailInfo[0].ReadDataOffset;
//读取的邮件数量不足pageSize(10条),则继续往下读取pageSize条数据
if (listNewMailInfo.Count < pageSize && isNeedReadData)
{
GetPageMailInfo(filterStr, folderName, pageSize, lastLoadTime, alreadyReadTotal, filterType, listNewMailInfo);
}
}
return listNewMailInfo;
}
///
/// 获取指定目录下,按指定关键词在指定偏移量后搜索到的指定时间之后的指定数量的邮件 2017-10-27
///
/// 过滤条件
/// 目录ID
/// 分页数量
/// 最后一次加载数据的时间
/// 已读取的记录总数量
/// 搜索类别:主题,收件人等
/// 已读取的list
///
public List GetPageMailInfo(string filterStr, string folderId, int pageSize, DateTime lastLoadTime, int alreadyReadTotal, string filterType, List listMailInfo)
{
List listNewMailInfo = new List();
if (listMailInfo != null && listMailInfo.Count > 0)
{
listNewMailInfo = listMailInfo;
}
FindItemsResults- itemsResults = GetItemsResults(filterStr, folderId, pageSize, alreadyReadTotal, filterType);
bool isNeedReadData = false;//是否继续往下读取数据
if (itemsResults != null && itemsResults.Count() > 0)
{
ReadMailList(itemsResults, listNewMailInfo, pageSize, alreadyReadTotal);
//当前目录的总记录数>分页数量,则可以继续往下读取数据
isNeedReadData = itemsResults.TotalCount > pageSize;
alreadyReadTotal = listNewMailInfo[0].ReadDataOffset;
//读取的邮件数量不足pageSize(10条),则继续往下读取pageSize条数据
if (listNewMailInfo.Count < pageSize && isNeedReadData)
{
GetPageMailInfo(filterStr, folderId, pageSize, lastLoadTime, alreadyReadTotal, filterType, listNewMailInfo);
}
}
return listNewMailInfo;
}
///
/// 在指定目录下用指定关键词/指定的查询类别,查找指定数量的返回结果
///
/// 过滤条件
/// 目录名
/// 分页数量
/// 下一次读取记录的位置
/// 搜索类别:主题,收件人等
///
private FindItemsResults- GetItemsResults(string filterStr, WellKnownFolderName foldername, int pageSize, int offset, string filterType)
{
FindItemsResults- list;
ItemView iv = new ItemView(pageSize) { Offset = offset };
if (string.IsNullOrEmpty(filterStr))
{
list = ExchService.FindItems(foldername, iv);
}
else
{
SearchFilter sf = getSearchFilt(filterStr, filterType);
list = ExchService.FindItems(foldername, sf, iv);
}
return list;
}
///
/// 在指定目录下用指定关键词/指定的查询类别,查找指定数量的返回结果
///
///
/// 过滤条件
/// 目录ID
/// 分页数量
/// 下一次读取记录的位置
/// 搜索类别:主题,收件人等
///
private FindItemsResults- GetItemsResults(string filterStr, string folderId, int pageSize, int offset, string filterType)
{
FindItemsResults- list;
ItemView iv = new ItemView(pageSize) { Offset = offset };
if (string.IsNullOrEmpty(filterStr))
{
list = ExchService.FindItems(folderId, iv);
}
else
{
SearchFilter sf = getSearchFilt(filterStr, filterType);
list = ExchService.FindItems(folderId, sf, iv);
}
return list;
}
///
/// 从查找到的ItemsResults列表读取邮件 2017-10-27
///
///
/// List对象
///
///
private List ReadMailList(FindItemsResults- itemsResults, List listMailInfo, int pageSize, int alreadyReadTotal)
{
int readOffsetCount = alreadyReadTotal;//最后一封读取的邮件在所有的ItemsResults数据中的位置
for (int i = 0; i < itemsResults.Count(); i++)
{
if (listMailInfo.Count() == pageSize)//解决多次加载数据时,返回的数量仍不足分页数量
break;
readOffsetCount++;
MailInfo info = new MailInfo();
EmailMessage message = null;
#region 转成EmailMessage
if (IsQuickShowEmailList)
{
if (itemsResults.ElementAt(i).GetType().Name != "EmailMessage")//已刪除的不一定都是郵件,有可能是會議或其他数据 2017-10-13
continue;
message = (EmailMessage)itemsResults.ElementAt(i);
info.Descript = "";//没有读取邮件详细数据,无法读取message.Body.Text
}
else
{
if (itemsResults.ElementAt(i).GetType().Name != "EmailMessage")//已刪除的不一定都是郵件,有可能是會議或其他数据 2017-10-13
continue;
message = EmailMessage.Bind(_ExchService, itemsResults.ElementAt(i).Id);
info.Descript = message.Body.Text;
}
#endregion
#region 封装MailInfo
//info.BodyText = message.Body.Text;// 2017-8-25
info.DisplayTo = message.DisplayTo;// 用于已发送郵件列表显示收件人 2017-10-13
info.ID = message.Id.UniqueId;
info.StartTime = message.DateTimeCreated;
info.EndTime = message.LastModifiedTime;
info.CreatedDateTime = info.StartTime;
info.ReceivedDateTime = message.DateTimeReceived;
info.IsRead = message.IsRead;
info.Importance = message.Importance;
info.Subject = message.Subject;
info.IsDraft = message.IsDraft;
info.From = "";
if (message.From != null && message.From.Name != null)
{
info.From = message.From.Name;
if (!string.IsNullOrEmpty(message.From.Address))
{
info.From += "[" + message.From.Address + "]";
}
}
info.To = "";
if (message.ToRecipients != null && message.ToRecipients.Count() > 0)
{
for (int k = 0; k < message.ToRecipients.Count(); k++)
{
info.To = _getMailAddressList(message.ToRecipients);
}
}
info.AttachmentName = new List();
info.HasAttachment = message.HasAttachments;// 2017-9-6
if (message.Attachments.Count() > 0)
{
for (int j = 0; j < message.Attachments.Count(); j++)
{
if (message.Attachments.ElementAt(j).IsInline == true)
{ continue; }
info.AttachmentName.Add(message.Attachments.ElementAt(j).Name);
}
}
info.TotalCount = itemsResults.TotalCount;//解决已加载数量大于邮件总数量,还能向webService发起请求的Bug 2017-9-19
listMailInfo.Add(info);
#endregion
}
if (listMailInfo.Count > 0)
{
listMailInfo[0].ReadDataOffset = readOffsetCount;
}
return listMailInfo;
}
#endregion
///
/// 移动邮件 2017-11-25
///
/// 账号名
/// 邮件ID
/// 新目录ID
public bool MoveMail(string accountName, string mailId, string newFolderId)
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
PropertySet propSet = new PropertySet(BasePropertySet.IdOnly, EmailMessageSchema.Subject, EmailMessageSchema.ParentFolderId);
Item item = null;
int outFolderId = 0;
EmailMessage beforeMessage = EmailMessage.Bind(ExchService, mailId, propSet);
if (int.TryParse(newFolderId, out outFolderId))
{
WellKnownFolderName destinationFolderName = (WellKnownFolderName)outFolderId;
item = beforeMessage.Move(destinationFolderName);
}
else
{
FolderId destinationFolderId = new FolderId(newFolderId);
item = beforeMessage.Move(destinationFolderId);
}
return item != null;
}
#region 附件相关
///
/// 读取ItemAttachment 2017-11-27
///
///
///
/// 附件索引
///
public MailInfo GetItemAttachment(string accountName, string mailId, int fileIndex)
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
EmailMessage tmpInfo = EmailMessage.Bind(ExchService, mailId);
if (tmpInfo == null || tmpInfo.Id == null || tmpInfo.Id.UniqueId != mailId)
{ return null; }
MailInfo mailInfo = new MailInfo();
string attachTypeName = string.Empty;
for (int i = 0; i < tmpInfo.Attachments.Count(); i++)
{
attachTypeName = tmpInfo.Attachments.ElementAt(i).GetType().Name;
if (!tmpInfo.Attachments[i].IsInline && attachTypeName == "ItemAttachment" && i == fileIndex)
{
#region ItemAttachment
ItemAttachment iam = (ItemAttachment)tmpInfo.Attachments.ElementAt(i);
iam.Load(ItemSchema.MimeContent);
#region 基本信息
mailInfo.ID = "";
mailInfo.IsRead = true;
mailInfo.Cc = iam.Item.DisplayCc;
mailInfo.Descript = iam.Item.Body == null ? "" : iam.Item.Body.Text;
mailInfo.EndTime = iam.Item.DateTimeSent;
mailInfo.StartTime = iam.Item.DateTimeCreated;
mailInfo.Subject = iam.Item.Subject;
mailInfo.To = iam.Item.DisplayTo;
mailInfo.IsDraft = iam.Item.IsDraft;
mailInfo.Importance = iam.Item.Importance;
mailInfo.IsAttachment = true;
#endregion
#region 附件相關數據聲明
mailInfo.HasAttachment = iam.Item.HasAttachments;
mailInfo.AttachmentId = new List();
mailInfo.AttachmentName = new List();
mailInfo.AttachmentType = new List();
mailInfo.AttachmentSize = new List();
mailInfo.AttachmentByte = new List();
mailInfo.AttachmentIsInLine = new List();
mailInfo.AttachmentContentID = new List();
mailInfo.ItemTypeList = new List();
mailInfo.SubEmailList = new List();
#endregion
for (int j = 0; j < iam.Item.Attachments.Count(); j++)
{
attachTypeName = iam.Item.Attachments.ElementAt(j).GetType().Name;
mailInfo.ItemTypeList.Add(attachTypeName);
switch (attachTypeName)
{
case "FileAttachment":
#region FileAttachment
FileAttachment ea = (FileAttachment)iam.Item.Attachments.ElementAt(j);
mailInfo.AttachmentId.Add(ea.Id);
mailInfo.AttachmentIsInLine.Add(iam.Item.Attachments.ElementAt(j).IsInline);
mailInfo.AttachmentName.Add(ea.Name);
mailInfo.AttachmentType.Add(ea.ContentType);
mailInfo.AttachmentSize.Add(ea.Size);
mailInfo.AttachmentContentID.Add(ea.ContentId);
ea.Load();
byte[] getbyte = ea.Content;
mailInfo.AttachmentByte.Add(getbyte);
#endregion
break;
case "ItemAttachment"://解决之前只转换为FileAttachment的BUG
#region ItemAttachment
ItemAttachment ia = (ItemAttachment)iam.Item.Attachments.ElementAt(i);
mailInfo.AttachmentId.Add(ia.Id);
mailInfo.AttachmentIsInLine.Add(iam.Item.Attachments.ElementAt(i).IsInline);
mailInfo.AttachmentName.Add(ia.Name);
mailInfo.AttachmentType.Add(ia.ContentType);
mailInfo.AttachmentSize.Add(ia.Size);
mailInfo.AttachmentContentID.Add(ia.ContentId);
mailInfo.AttachmentMsgAmount++;
mailInfo.AttachmentByte.Add(null);
//ia.Load(ItemSchema.MimeContent);
//mailInfo.SubEmailList.Add(GetEmailFromItemAttachment(ia.Item));
//mailInfo.AttachmentByte.Add(ia.Item.MimeContent.Content);
#endregion ItemAttachment
break;
}
}
#endregion
break;
}
}
return mailInfo;
}
///
/// 从ItemAttachment获取指定用户的邮件 2017-12-8
///
/// 邮件账号
/// 附件ID
///
private MailInfo GetEmailFromItemAttachment(Item item)
{
if (item == null)
{ return null; }
MailInfo mailInfo = new MailInfo();
mailInfo.ID = "";
mailInfo.Cc = item.DisplayCc;
mailInfo.Descript = item.Body == null ? "" : item.Body.Text;
mailInfo.StartTime = item.DateTimeCreated;
mailInfo.Subject = item.Subject;
mailInfo.To = item.DisplayTo;
mailInfo.IsDraft = item.IsDraft;
mailInfo.Importance = item.Importance;
mailInfo.HasAttachment = item.HasAttachments;
mailInfo.IsRead = true;
mailInfo.IsAttachment = true;
//int inlinenum = 0;
mailInfo.AttachmentId = new List();
mailInfo.AttachmentName = new List();
mailInfo.AttachmentType = new List();
mailInfo.AttachmentSize = new List();
mailInfo.AttachmentByte = new List();
mailInfo.AttachmentIsInLine = new List();
mailInfo.AttachmentContentID = new List();
mailInfo.ItemTypeList = new List();
string attachTypeName = string.Empty;
for (int i = 0; i < item.Attachments.Count(); i++)
{
attachTypeName = item.Attachments.ElementAt(i).GetType().Name;
mailInfo.ItemTypeList.Add(attachTypeName);
switch (attachTypeName)
{
case "FileAttachment":
#region ItemAttachment
FileAttachment ea = (FileAttachment)item.Attachments.ElementAt(i);
mailInfo.AttachmentId.Add(ea.Id);
mailInfo.AttachmentIsInLine.Add(item.Attachments.ElementAt(i).IsInline);
#region 已註釋
// 如果是内嵌图片,直接处理其显示代码,不出现到附件中
//发送的邮件,要在不同的终端显示,所以此处不需要处理,所以注释以下代码 2017-9-28
//if (item.Attachments.ElementAt(i).IsInline == true)
//{
// mailInfo.Descript = mailInfo.Descript.Replace("cid:" + ea.ContentId, "ShowInLineFile?id=" + Id + "&fileindex=" + inlinenum);
// inlinenum++;
// continue;
//}
#endregion
mailInfo.AttachmentName.Add(ea.Name);
mailInfo.AttachmentType.Add(ea.ContentType);
mailInfo.AttachmentSize.Add(ea.Size);
mailInfo.AttachmentContentID.Add(ea.ContentId);
ea.Load();
byte[] getbyte = ea.Content;
mailInfo.AttachmentByte.Add(getbyte);
#endregion
break;
case "ItemAttachment"://解决之前只转换为FileAttachment的BUG
#region ItemAttachment
ItemAttachment ia = (ItemAttachment)item.Attachments.ElementAt(i);
ia.Load(ItemSchema.MimeContent);
mailInfo.AttachmentId.Add(ia.Id);
mailInfo.AttachmentIsInLine.Add(item.Attachments.ElementAt(i).IsInline);
mailInfo.AttachmentName.Add(ia.Name);
mailInfo.AttachmentType.Add(ia.ContentType);
mailInfo.AttachmentSize.Add(ia.Size);
mailInfo.AttachmentContentID.Add(ia.ContentId);
mailInfo.AttachmentMsgAmount++;
byte[] iaByte = ia.Item.MimeContent.Content;
mailInfo.AttachmentByte.Add(iaByte);
#endregion
break;
}
}
return mailInfo;
}
#endregion
#endregion
#region 外出自动回复 2017-12-5
///
/// 设置外出自动回复内容 2017-12-5
/// 返回1设置成功,其他值设置失败
///
///
///
///
public void SetCustomAutoReply(string accountName, ExternalAutoReply autoReply)
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, accountName);
DateTime zeroDateTime = Convert.ToDateTime("0001/1/1 0:00:00");
var oofSettings = new OofSettings();
if (autoReply.State == "1")
{
oofSettings.State = OofState.Enabled;
if (autoReply.OnlyTime == "1" && autoReply.StartTime != zeroDateTime && autoReply.EndTime != zeroDateTime)
{
oofSettings.State = OofState.Scheduled;
oofSettings.Duration = new TimeWindow(autoReply.StartTime, autoReply.EndTime);
}
if (autoReply.AutoReplyOutOrgPersonal == "1")
{
switch (autoReply.OnlyReplyMyContactOrReplyOutOrgPersonal)
{
case "inOrg":
oofSettings.ExternalAudience = OofExternalAudience.Known;
break;
case "outOrg":
oofSettings.ExternalAudience = OofExternalAudience.All;
break;
case "none":
oofSettings.ExternalAudience = OofExternalAudience.None;
break;
}
}
else
{
oofSettings.ExternalAudience = OofExternalAudience.None;
}
}
else
{
oofSettings.State = OofState.Disabled;
}
oofSettings.InternalReply = new OofReply(autoReply.InternalReplyContent);
oofSettings.ExternalReply = new OofReply(autoReply.ExternalReplyContent);
ExchService.SetUserOofSettings(accountName, oofSettings);
}
///
/// 获取外出自动回复 2017-12-5
///
/// 邮箱账号List
///
public List GetCustomAutoReply(List emailAddressList)
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, emailAddressList[0]);
List list = new List();
foreach (var emailAddress in emailAddressList)
{
ExternalAutoReply autoReply = new ExternalAutoReply();
var oofSettings = ExchService.GetUserOofSettings(emailAddress);
if (oofSettings != null)
{
autoReply = new ExternalAutoReply();
autoReply.InternalReplyContent = oofSettings.InternalReply.Message;
autoReply.ExternalReplyContent = oofSettings.ExternalReply.Message;
autoReply.StartTime = oofSettings.Duration.StartTime;
autoReply.EndTime = oofSettings.Duration.EndTime;
autoReply.State = (oofSettings.State == OofState.Scheduled || oofSettings.State == OofState.Enabled) ? "1" : "0";
switch (oofSettings.State)
{
case OofState.Scheduled:
if (oofSettings.Duration.StartTime != null && oofSettings.Duration.EndTime != null)
autoReply.OnlyTime = "1";
else
autoReply.OnlyTime = "0";
break;
case OofState.Enabled:
case OofState.Disabled:
autoReply.OnlyTime = "0";
break;
}
switch (oofSettings.ExternalAudience)
{
case OofExternalAudience.Known:
autoReply.AutoReplyOutOrgPersonal = "1";
autoReply.OnlyReplyMyContactOrReplyOutOrgPersonal = "inOrg";
break;
case OofExternalAudience.All:
autoReply.AutoReplyOutOrgPersonal = "1";
autoReply.OnlyReplyMyContactOrReplyOutOrgPersonal = "outOrg";
break;
case OofExternalAudience.None:
autoReply.AutoReplyOutOrgPersonal = "0";
autoReply.OnlyReplyMyContactOrReplyOutOrgPersonal = "none";
break;
}
}
list.Add(autoReply);
}
return list;
}
#endregion
}
}