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
/// <summary>
/// 隐藏构造函数,禁止通过 new 创建新对象
/// </summary>
protected ExchangeProvider()
{
//
}
private static ExchangeProvider _Instance = null;
private static object _InstanceLock = new object();
/// <summary>
/// 获取该类的唯一实例对象
/// </summary>
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();
/// <summary>
/// 获取该类的唯一实例对象
/// </summary>
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 全局变量
/// <summary>
/// Domain,如:aaa
/// </summary>
private static string DomainName = System.Configuration.ConfigurationManager.AppSettings["ExchSvrDomain"];
/// <summary>
/// 服务器地址,如:https://aaa.com/Exchange.asmx
/// </summary>
private static string ServiceUrl = System.Configuration.ConfigurationManager.AppSettings["ExchWebServicesUrl"];
/// <summary>
/// OWA地址
/// </summary>
private static string OwaUrl = System.Configuration.ConfigurationManager.AppSettings["ExchOwaUrl"];
/// <summary>
/// 代理账号
/// </summary>
private static string ADUser = System.Configuration.ConfigurationManager.AppSettings["ExchProxyUser"];
/// <summary>
/// 代理账号密码
/// </summary>
private static string ADPassword = System.Configuration.ConfigurationManager.AppSettings["ExchProxyPwd"];
/// <summary>
/// 个人邮箱账号
/// </summary>
private string EmailAccountName { get; set; }
#endregion
/// <summary>
/// Exchange WebServices配置信息实体
/// </summary>
private struct EwsConfig
{
public ExchangeVersion ExchangeVersion;
public string EWSServiceUrl;
public string ExchangeAdministrator;
public string ExchangeAdministratorPassword;
public string DomainName;
//public string OtherUserName;
}
#region 辅助
/// <summary>
/// 获取当前Exchange的版本
/// 在配置文件里可以配置节点:ExchangeVersion
/// </summary>
/// <returns></returns>
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 未读邮件/数量
/// <summary>
/// 同时获取多个目录的未读数量 2017-11-9
/// </summary>
/// <param name="accountName">邮箱账号</param>
/// <param name="folderIdList">目录ID,多个用|分开</param>
/// <returns></returns>
public List<FoldInfo> GetNoReadNumList(string accountName, string folderIdList)
{
EmailAccountName = accountName;
List<FoldInfo> listNoReadNum = new List<FoldInfo>();
if (!string.IsNullOrEmpty(folderIdList))
{
foreach (string folderid in folderIdList.Split('|'))
{
FoldInfo entity = new FoldInfo();
entity.ID = folderid;
if (folderid == "3")
{//草稿
List<FoldInfo> 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;
}
/// <summary>
/// 获取指定ID对应目录下的未读邮件数量
/// </summary>
/// <param name="accountName"></param>
/// <param name="folderid"></param>
/// <returns></returns>
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; }
}
/// <summary>
/// 设置邮件只读或未读 2017-11-14
/// </summary>
/// <param name="accountName"></param>
/// <param name="emid"></param>
/// <param name="isread"></param>
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<Item> 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<Item> 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<MailInfo> 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; }
}
/// <summary>
/// 读取未读的邮件 2017-8-28
/// </summary>
/// <param name="foldername"></param>
/// <returns></returns>
private List<MailInfo> 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<Item> list = ExchService.FindItems(foldername, sf, iv);
return ItemsResult2MailInfoList(list, false);
}
/// <summary>
/// 读取未读的邮件 2017-8-28
/// </summary>
/// <param name="folderid"></param>
/// <returns></returns>
private List<MailInfo> 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<Item> 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; }
}
/// <summary>
/// 读取未读的邮件 2017-8-28
/// </summary>
/// <param name="foldername"></param>
/// <returns></returns>
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<Item> list = ExchService.FindItems(foldername, sf, iv);
return ItemsResult2MailInfo(list, emailId);
}
/// <summary>
/// 读取未读的邮件 2017-8-28
/// </summary>
/// <param name="folderid"></param>
/// <returns></returns>
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<Item> list = ExchService.FindItems(folderid, sf, iv);
return ItemsResult2MailInfo(list, emailId);
}
/// <summary>
/// 把Exchange对象转成MailInfo对象 2017-8-28
/// </summary>
/// <param name="list">FindItemsResults</param>
/// <returns></returns>
private MailInfo ItemsResult2MailInfo(FindItemsResults<Item> list, string emailId)
{
MailInfo info = null;
List<MailInfo> result = new List<MailInfo>();
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<string>();
//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;
}
/// <summary>
/// 把Exchange对象转成MailInfo对象 2017-8-28
/// </summary>
/// <param name="list">FindItemsResults</param>
/// <returns></returns>
private List<MailInfo> ItemsResult2MailInfoList(FindItemsResults<Item> list, bool addAttachemnt)
{
List<MailInfo> result = new List<MailInfo>();
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<string>();
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
/// <summary>
/// 获取指定目录下按指定关键词搜索到的指定时间之前的指定数量的邮件
/// </summary>
/// <param name="accountName"></param>
/// <param name="filterStr"></param>
/// <param name="folderid"></param>
/// <param name="pageSize"></param>
/// <param name="lasttime"></param>
/// <param name="lastnum"></param>
/// <returns></returns>
public List<MailInfo> 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<MailInfo>(); }
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<MailInfo>(); }
}
/// <summary>
/// 在指定目录中使用指定关键字搜索指定日期之后的所有新邮件
/// </summary>
/// <param name="accountName"></param>
/// <param name="filterStr"></param>
/// <param name="folderid"></param>
/// <param name="lasttime"></param>
/// <returns></returns>
public List<MailInfo> GetNewMail(string accountName, string filterStr, string folderid, DateTime lasttime)
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
try
{
if (string.IsNullOrEmpty(folderid))
{ return new List<MailInfo>(); }
if (folderid.Length < 3)
{ return _getNewMail(filterStr, (WellKnownFolderName)Convert.ToInt32(folderid), lasttime); }
else
{ return _getNewMail(filterStr, folderid, lasttime); }
}
catch { return new List<MailInfo>(); }
}
/// <summary>
/// 获取指定用户指定ID对应的邮件信息,并且将其未读状态更新为已读,為加快讀取速度,此接口不獲取附件內容
/// </summary>
/// <param name="accountName"></param>
/// <param name="Id"></param>
/// <param name="isReadAttachContent">true读取附件内容</param>
/// <returns></returns>
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<string>();
mailInfo.AttachmentName = new List<string>();
mailInfo.AttachmentType = new List<string>();
mailInfo.AttachmentSize = new List<int>();
mailInfo.AttachmentByte = new List<byte[]>();
mailInfo.AttachmentIsInLine = new List<bool>();
mailInfo.AttachmentContentID = new List<string>();
mailInfo.HasAttachment = tmpInfo.HasAttachments;
mailInfo.ItemTypeList = new List<string>();
#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;
}
/// <summary>
/// 获取指定用户指定ID对应的邮件信息,并且将其未读状态更新为已读,此接口獲取所有附件內容
/// </summary>
/// <param name="accountName"></param>
/// <param name="Id"></param>
/// <returns></returns>
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<string>();
mailInfo.AttachmentName = new List<string>();
mailInfo.AttachmentType = new List<string>();
mailInfo.AttachmentSize = new List<int>();
mailInfo.AttachmentByte = new List<byte[]>();
mailInfo.AttachmentIsInLine = new List<bool>();
mailInfo.AttachmentContentID = new List<string>();
mailInfo.ItemTypeList = new List<string>();
//mailInfo.SubEmailList = new List<MailInfo>();
#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;
}
/// <summary>
/// 获取指定用户指定ID对应的邮件信息中的指定附件信息
/// </summary>
/// <param name="accountName"></param>
/// <param name="Id"></param>
/// <param name="fileindex">第幾個附件</param>
/// <returns></returns>
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<string>();
mailInfo.AttachmentByte = new List<byte[]>();
mailInfo.AttachmentType = new List<string>();
mailInfo.AttachmentSize = new List<int>();
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;
}
/// <summary>
/// 获取指定用户指定ID对应的邮件信息中的指定内嵌图片信息
/// </summary>
/// <param name="accountName"></param>
/// <param name="Id"></param>
/// <param name="fileindex"></param>
/// <returns></returns>
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<string>();
mailInfo.AttachmentByte = new List<byte[]>();
mailInfo.AttachmentType = new List<string>();
mailInfo.AttachmentSize = new List<int>();
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;
}
/// <summary>
/// 根据指定标题查找指定用户的邮件,并将查找到的邮件主题更新
/// 此方法用于保存草稿时,获取被保存的邮件id,指定标题为添加时手动设置
/// </summary>
/// <param name="accountName"></param>
/// <param name="signsubject"></param>
/// <param name="realsubject"></param>
/// <returns></returns>
public string GetMailID(string accountName, string signsubject, string realsubject)
{
string result = "";
List<MailInfo> 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;
}
/// <summary>
/// 将指定用户的指定邮件保存到草稿箱
/// </summary>
/// <param name="accountName"></param>
/// <param name="mi"></param>
/// <returns></returns>
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<string>(), new List<byte[]>(), new List<string>(), new List<bool>(), new List<string>(), new List<string>(), Importance.High);
}
}
em.Subject = mi.Subject;
em.Body = new MessageBody() { Text = mi.Descript };
em.ToRecipients.Clear();
List<EmailAddress> 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); }
}
/// <summary>
/// 删除指定邮件
/// </summary>
/// <param name="accountName"></param>
/// <param name="Id"></param>
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 { ;}
}
/// <summary>
/// 彻底删除指定邮件
/// </summary>
/// <param name="accountName"></param>
/// <param name="Id"></param>
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 邮件目录列表
/// <summary>
/// 获取指定目录下的一级子目录列表
/// </summary>
/// <param name="accountName"></param>
/// <param name="folderid"></param>
/// <param name="isReadSytemFolderId">是否讀取系統目錄ID對應的索引( 2017-12-11)</param>
/// <returns></returns>
public List<FoldInfo> GetChildFolderList(string accountName, string folderid, string isReadSytemFolderId)
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
try
{
EmailAccountName = accountName;
if (string.IsNullOrEmpty(folderid))
{ return new List<FoldInfo>(); }
if (folderid.Length < 3)
{ return _getChildFolderList((WellKnownFolderName)Convert.ToInt32(folderid), isReadSytemFolderId); }
else
{ return _getChildFolderList(folderid, isReadSytemFolderId); }
}
catch { return new List<FoldInfo>(); }
}
private List<FoldInfo> _getChildFolderList(WellKnownFolderName foldername, string isReadSytemFolderId)
{
FolderView folderViews = new FolderView(int.MaxValue);
FindFoldersResults folders = ExchService.FindFolders(foldername, folderViews);
return _getFolderList(folders, isReadSytemFolderId);
}
private List<FoldInfo> _getChildFolderList(string folderid, string isReadSytemFolderId)
{
FolderView folderViews = new FolderView(int.MaxValue);
FindFoldersResults folders = ExchService.FindFolders(folderid, folderViews);
return _getFolderList(folders, isReadSytemFolderId);
}
private List<FoldInfo> _getFolderList(FindFoldersResults folders, string isReadSytemFolderId)
{
//DateTime now = DateTime.Now;
//string tmp = "开始:" + now.ToString("HH:mm:ss") + "_" + now.Millisecond.ToString();
List<WellKnownFolderName> foldnamelist = new List<WellKnownFolderName>() {
WellKnownFolderName.Drafts// 这个位置不要随便动,后面有单独针对草稿箱的操作
,WellKnownFolderName.DeletedItems
,WellKnownFolderName.Inbox
,WellKnownFolderName.Outbox
,WellKnownFolderName.SentItems
,WellKnownFolderName.JunkEmail
};
List<string> foldidlist = new List<string>();
if (isReadSytemFolderId == "1")
{
for (int fi = 0; fi < foldnamelist.Count(); fi++)
{ foldidlist.Add(_getFolderID(foldnamelist[fi])); }
}
List<FoldInfo> result = new List<FoldInfo>();
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
/// <summary>
/// 获取指定WellKnownFolderName对应的UniqueId
/// </summary>
/// <param name="foldname"></param>
/// <returns></returns>
private string _getFolderID(WellKnownFolderName foldname)
{
Folder folder = Folder.Bind(ExchService, foldname);
return folder.Id.UniqueId;
}
#endregion
/// <summary>
/// 返回当前用户的草稿箱UniqueId,用于获取目录列表时,比对查找草稿箱
/// </summary>
/// <returns></returns>
private string _getDraftID()
{
Folder folder_draft = Folder.Bind(ExchService, WellKnownFolderName.Drafts);
return folder_draft.Id.UniqueId;
}
//获取指定目录下按指定关键词在指定偏移量后搜索到的指定时间之后的指定数量的邮件
private List<MailInfo> _getPageMail(string filterStr, WellKnownFolderName foldername, int pageSize, DateTime lasttime, int lastnum)
{
int mailnum = pageSize + pageSize;
lastnum = lastnum < (pageSize / 2) ? 0 : (lastnum - pageSize / 2);
FindItemsResults<Item> 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<MailInfo> result = new List<MailInfo>();
if (num < 0)
{ return result; }
return _getMailList(maillist, num, pageSize);
}
// 获取指定目录下按指定关键词在指定偏移量后搜索到的指定时间之后的指定数量的邮件
private List<MailInfo> _getPageMail(string filterStr, string folderid, int pageSize, DateTime lasttime, int lastnum)
{
int mailnum = pageSize + pageSize;
lastnum = lastnum < (pageSize / 2) ? 0 : (lastnum - pageSize / 2);
FindItemsResults<Item> 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<MailInfo> result = new List<MailInfo>();
if (num < 0)
{ return result; }
return _getMailList(maillist, num, pageSize);
}
// 在指定目录中使用指定关键字搜索指定日期之后的所有邮件
private List<MailInfo> _getNewMail(string filterStr, WellKnownFolderName foldername, DateTime lasttime)
{
int mailnum = 20;
FindItemsResults<Item> 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<MailInfo> result = new List<MailInfo>();
if (num < 0)
{ return result; }
return _getMailList(maillist, 0, num);
}
// 在指定目录中使用指定关键字搜索指定日期之后的所有邮件
private List<MailInfo> _getNewMail(string filterStr, string folderid, DateTime lasttime)
{
int mailnum = 20;
FindItemsResults<Item> 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<MailInfo> result = new List<MailInfo>();
if (num < 0)
{ return result; }
return _getMailList(maillist, 0, num);
}
// 在指定目录下用指定关键词从指定偏移量开始查找到的指定数量的返回结果
private FindItemsResults<Item> _getItemsList(string filterStr, WellKnownFolderName foldername, int num, int offset)
{
FindItemsResults<Item> 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<Item> _getItemsList(string filterStr, string folderid, int pageSize, int offset)
{
FindItemsResults<Item> 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<MailInfo> _getMailList(FindItemsResults<Item> maillist, int startnum, int pageSize)
{
List<MailInfo> result = new List<MailInfo>();
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<string>();
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<MailInfo> 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<MailInfo>(); }
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<MailInfo>(); }
}
private List<MailInfo> _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<Item> 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<MailInfo> result = new List<MailInfo>();
if (num < 0)
{ return result; }
return _getMailList(maillist, num, pageSize);
}
private List<MailInfo> _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<Item> 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<MailInfo> result = new List<MailInfo>();
if (num < 0)
{ return result; }
return _getMailList(maillist, num, pageSize);
}
private FindItemsResults<Item> _getItemsList(string filterStr, WellKnownFolderName foldername, int num, int offset, int searchType)
{
FindItemsResults<Item> 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<Item> _getItemsList(string filterStr, string folderid, int pageSize, int offset, int searchType)
{
FindItemsResults<Item> 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<EmailAddress> _getMailAddressList(string maillist)
{
List<EmailAddress> result = new List<EmailAddress>();
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
/// <summary>
/// 是否读取 收件人/发件人邮件地址(不读取 收件人/发件人邮件地址,可快速显示邮件列表),false读取,true不读取
/// 2017-9-6
/// </summary>
private bool IsQuickShowEmailList
{
get
{
return System.Configuration.ConfigurationManager.AppSettings["IsQuickShowEmailList"] == "1";
}
}
/// <summary>
/// 发送邮件 2017-9-27
/// </summary>
/// <param name="accountName"></param>
/// <param name="subject"></param>
/// <param name="mb"></param>
/// <param name="toreciptlist"></param>
/// <param name="cclist"></param>
/// <param name="bcclist"></param>
/// <param name="namelist"></param>
/// <param name="streamlist"></param>
/// <param name="typelist"></param>
/// <param name="isInLineList">list项的值为true是内嵌图片</param>
/// <param name="import"></param>
public void SendMail(string accountName, string mailId, string subject, MessageBody mb
, string[][] toreciptlist, string[][] cclist, string[][] bcclist
, List<string> namelist, List<byte[]> streamlist, List<string> typelist
, List<bool> AttachmentIsInLine, List<string> contentIDList, List<string> 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<string> addedItemAttachmentList = new List<string>();//保存已添加的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<Item> iat = em.Attachments.AddItemAttachment<Item>();//要发送的附件
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 旧接口
/// <summary>
/// 获取指定主目录的下一级子目录信息
/// </summary>
/// <param name="accountName"></param>
/// <param name="foldname"></param>
/// <returns></returns>
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<Item> list = ExchService.FindItems(foldname, sf, iv);
fi.NoRead = list.Count();
FindFoldersResults folders = ExchService.FindFolders(foldname, folderViews);
fi.ChildNum = folders.Count();
fi.ChildFolds = new List<FoldInfo>();
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<FoldInfo>();
// 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;
}
/// <summary>
/// 获取指定目录的下一级子目录信息
/// </summary>
/// <param name="accountName"></param>
/// <param name="folderid"></param>
/// <returns></returns>
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<Item> 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<FoldInfo>();
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<MailInfo> GetNextPageMail(string accountName, string filterStr, WellKnownFolderName foldname, int pageSize, DateTime lasttime
, int lastnum = 0, string filtertype = "")
{
lastnum += pageSize;
lastnum += pageSize;
FindItemsResults<Item> 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<Item> 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<MailInfo> GetNextPageMail(FindItemsResults<Item> list, int pageSize, int lastnum)
{
List<MailInfo> infoList = new List<MailInfo>();
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<string>();
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<MailInfo> GetNewMail(FindItemsResults<Item> list, DateTime lasttime)
{
List<MailInfo> infoList = new List<MailInfo>();
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<string>();
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<MailInfo> GetPageMail(string accountName, string filterStr, WellKnownFolderName foldname, int pageSize, ref int page, out int TatalPage)
//{
// FindItemsResults<Item> 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<MailInfo> GetNextPageMail(string accountName, string filterStr, string folderid, int pageSize, DateTime lasttime
, int lastnum = 0, string filtertype = "")
{
lastnum += pageSize;
lastnum += pageSize;
FindItemsResults<Item> 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<MailInfo> 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<Item> 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<MailInfo> 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<Item> 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<MailInfo> GetPageMail(string accountName, string filterStr, FolderId folderid, int pageSize, ref int page, out int TatalPage)
//{
// FindItemsResults<Item> 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<Item> getItemsList(string accountName, string filterStr, WellKnownFolderName foldname
, int num = int.MaxValue, string filtertype = "")
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
FindItemsResults<Item> 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<Item> getItemsList(string accountName, string filterStr, string folderid, int num = int.MaxValue, string filtertype = "")
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
FindItemsResults<Item> 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<Item> 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 邮件接口,供其他项目调用
/// <summary>
/// 获取邮件的所有字段信息的列表 2017-9-4
/// </summary>
/// <param name="folderid">目录ID</param>
/// <param name="num">返回数量</param>
/// <param name="offset">邮件位置</param>
/// <param name="filterStr">查询条件</param>
/// <param name="accountName">邮箱账号</param>
/// <returns></returns>
public List<MailInfo> GetEmailList(string folderid, int num, int offset, string filterStr = "", string accountName = "")
{
if (accountName != "")
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
}
FindItemsResults<Item> maillist = null;
if (folderid.Length < 3)
{ maillist = _getItemsList(filterStr, (WellKnownFolderName)Convert.ToInt32(folderid), num, offset); }
else
{
maillist = _getItemsList(filterStr, folderid, num, offset);
}
List<MailInfo> result = new List<MailInfo>();
if (num < 0)
{ return result; }
return ItemsResult2MailInfoList(maillist, true);
}
#endregion
#region 联系人接口 2017-10-18
private FindItemsResults<Item> getItemsList(string filterStr, WellKnownFolderName foldername, int num, int offset)
{
FindItemsResults<Item> 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)
);
}
/// <summary>
/// 获取个人联系人列表
/// </summary>
/// <param name="accountName"></param>
/// <param name="filterStr"></param>
/// <param name="foldername"></param>
/// <param name="pageSize"></param>
/// <param name="lastnum"></param>
/// <returns></returns>
public List<contactInfo> 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<Item> contactInfoList = getItemsList(filterStr, (WellKnownFolderName)Convert.ToInt32(folderid), pageSize, lastnum);
return _getcontactInfoList(ExchService, contactInfoList, lastnum, pageSize, isAll);
}
//private List<contactInfo> _getPageContact(string filterStr, WellKnownFolderName foldername, int pageSize, int lastnum)
//{
// int mailnum = pageSize + pageSize;
// lastnum = lastnum < (pageSize / 2) ? 0 : (lastnum - pageSize / 2);
// FindItemsResults<Item> 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<MailInfo> result = new List<MailInfo>();
// if (num < 0)
// { return result; }
// return _getMailList(maillist, num, pageSize);
//}
private List<contactInfo> _getcontactInfoList(ExchangeService ex, FindItemsResults<Item> contactInfolist, int startnum, int pageSize, bool isAll)
{
List<contactInfo> result = new List<contactInfo>();
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;
}
/// <summary>
/// 删除指定删除人
/// </summary>
/// <param name="accountName">邮箱用户名</param>
/// <param name="Id">联系人ID</param>
/// <param name="isHardDelete">是否物理删除</param>
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);
}
/// <summary>
/// 修改指定联系人
/// </summary>
/// <param name="accountName">邮箱用户名</param>
/// <param name="Id">联系人ID</param>
/// <param name="contact">联系人对象</param>
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);
}
/// <summary>
/// 修改联系人测试用
/// </summary>
/// <param name="accountName">邮箱用户名</param>
/// <param name="Id">联系人ID</param>
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);
}
/// <summary>
/// 增加联系人
/// </summary>
/// <param name="accountName">邮箱用户名</param>
/// <param name="Id">联系人ID</param>
/// <param name="contact">联系人对象</param>
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();
}
/// <summary>
/// 增加指定联系人测试用
/// </summary>
/// <param name="accountName">邮箱用户名</param>
/// <param name="Id">联系人ID</param>
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();
}
/// <summary>
/// 获取指定联系人信息
/// </summary>
/// <param name="accountName"></param>
/// <param name="Id"></param>
/// <returns></returns>
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
/// <summary>
/// 根据用户账号和當前日期获取其日程安排
/// 返回在當前日期内的安排
/// </summary>
/// <param name="accountName">當前帳號</param>
/// <param name="currDate">當前日期</param>
/// <param name="returnCount">返回數量</param>
/// <param name="Days">返回多少月的数据</param>
/// <returns></returns>
public List<AppointmentInfo> GetAppointmentsList(string accountName, DateTime currDate, int returnCount, int Month)
{
List<AppointmentInfo> infoList = new List<AppointmentInfo>();
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<Appointment> 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<AppointmentInfo> GetCalendarsList(string accountName, DateTime currDate, int returnCount, int Month, string updateDate)
{
List<AppointmentInfo> infoList = new List<AppointmentInfo>();
if (ExchService != null)
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
//CalendarView cv = new CalendarView(currDate.Date, currDate.Date.AddMonths(Month), returnCount);
//FindItemsResults<Appointment> list = ExchService.FindAppointments(WellKnownFolderName.Calendar, cv);
FindItemsResults<Item> 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<Item> getCalendarItemsList(DateTime currDate, int Month, string updateDate, WellKnownFolderName foldername, int num)
{
FindItemsResults<Item> 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;
}
/// <summary>
/// 日历查询筛选条件
/// </summary>
/// <param name="currDate">当前日期</param>
/// <param name="Month">查询多少月</param>
/// <param name="updateDate">获取日历的最后修改时间</param>
/// <returns></returns>
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))
);
}
}
/// <summary>
/// 创建周期性的约会
/// </summary>
/// <param name="accountName"></param>
/// <param name="appInfo"></param>
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);
}
}
/// <summary>
/// 修改周期性约会
/// </summary>
/// <param name="accountName"></param>
/// <param name="Id"></param>
/// <param name="appInfo"></param>
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 邮件分页相关
/// <summary>
/// 分页读取邮件 2017-10-27
/// </summary>
/// <param name="accountName">邮箱账号</param>
/// <param name="filterStr">查询条件</param>
/// <param name="folderId">目录ID</param>
/// <param name="pageSize">每页显示的记录数量</param>
/// <param name="lastLoadTime"></param>
/// <param name="alreadyReadTotal">已读取的记录总数量</param>
/// <param name="filterType">搜索类别:主题,收件人等</param>
/// <returns></returns>
public List<MailInfo> GetPageMailList(string accountName, string filterStr, string folderId, int pageSize, DateTime lastLoadTime, int alreadyReadTotal, string filterType)
{
try
{
if (string.IsNullOrEmpty(folderId))
{
return new List<MailInfo>();
}
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<MailInfo>(); }
}
/// <summary>
/// 获取指定目录下,按指定关键词在指定偏移量后搜索到的指定时间之后的指定数量的邮件 2017-10-27
/// </summary>
/// <param name="filterStr">过滤条件</param>
/// <param name="folderName">目录名/param>
/// <param name="pageSize">每页显示的记录数量</param>
/// <param name="lastLoadTime">最后一次加载数据的时间</param>
/// <param name="alreadyReadTotal">已读取的记录总数量</param>
/// <param name="filterType">搜索类别:主题,收件人等</param>
/// <param name="listMailInfo">已读取的list</param>
/// <returns></returns>
public List<MailInfo> GetPageMailInfo(string filterStr, WellKnownFolderName folderName, int pageSize, DateTime lastLoadTime, int alreadyReadTotal, string filterType, List<MailInfo> listMailInfo)
{
List<MailInfo> listNewMailInfo = new List<MailInfo>();
if (listMailInfo != null && listMailInfo.Count > 0)
{
listNewMailInfo = listMailInfo;
}
FindItemsResults<Item> 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;
}
/// <summary>
/// 获取指定目录下,按指定关键词在指定偏移量后搜索到的指定时间之后的指定数量的邮件 2017-10-27
/// </summary>
/// <param name="filterStr">过滤条件</param>
/// <param name="folderId">目录ID</param>
/// <param name="pageSize">分页数量</param>
/// <param name="lastLoadTime">最后一次加载数据的时间</param>
/// <param name="alreadyReadTotal">已读取的记录总数量</param>
/// <param name="filterType">搜索类别:主题,收件人等</param>
/// <param name="listMailInfo">已读取的list</param>
/// <returns></returns>
public List<MailInfo> GetPageMailInfo(string filterStr, string folderId, int pageSize, DateTime lastLoadTime, int alreadyReadTotal, string filterType, List<MailInfo> listMailInfo)
{
List<MailInfo> listNewMailInfo = new List<MailInfo>();
if (listMailInfo != null && listMailInfo.Count > 0)
{
listNewMailInfo = listMailInfo;
}
FindItemsResults<Item> 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;
}
/// <summary>
/// 在指定目录下用指定关键词/指定的查询类别,查找指定数量的返回结果
/// </summary>
/// <param name="filterStr">过滤条件</param>
/// <param name="foldername">目录名</param>
/// <param name="pageSize">分页数量</param>
/// <param name="offset">下一次读取记录的位置</param>
/// <param name="filterType">搜索类别:主题,收件人等</param>
/// <returns></returns>
private FindItemsResults<Item> GetItemsResults(string filterStr, WellKnownFolderName foldername, int pageSize, int offset, string filterType)
{
FindItemsResults<Item> 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;
}
/// <summary>
/// 在指定目录下用指定关键词/指定的查询类别,查找指定数量的返回结果
/// </summary>
/// <param name="filterStr"></param>
/// <param name="filterStr">过滤条件</param>
/// <param name="folderId">目录ID</param>
/// <param name="pageSize">分页数量</param>
/// <param name="offset">下一次读取记录的位置</param>
/// <param name="filterType">搜索类别:主题,收件人等</param>
/// <returns></returns>
private FindItemsResults<Item> GetItemsResults(string filterStr, string folderId, int pageSize, int offset, string filterType)
{
FindItemsResults<Item> 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;
}
/// <summary>
/// 从查找到的ItemsResults列表读取邮件 2017-10-27
/// </summary>
/// <param name="itemsResults"></param>
/// <param name="listMailInfo">List<MailInfo>对象</param>
/// <param name="readOffset"></param>
/// <returns></returns>
private List<MailInfo> ReadMailList(FindItemsResults<Item> itemsResults, List<MailInfo> 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<string>();
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
/// <summary>
/// 移动邮件 2017-11-25
/// </summary>
/// <param name="accountName">账号名</param>
/// <param name="mailId">邮件ID</param>
/// <param name="newFolderId">新目录ID</param>
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 附件相关
/// <summary>
/// 读取ItemAttachment 2017-11-27
/// </summary>
/// <param name="accountName"></param>
/// <param name="mailId"></param>
/// <param name="fileIndex">附件索引</param>
/// <returns></returns>
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<string>();
mailInfo.AttachmentName = new List<string>();
mailInfo.AttachmentType = new List<string>();
mailInfo.AttachmentSize = new List<int>();
mailInfo.AttachmentByte = new List<byte[]>();
mailInfo.AttachmentIsInLine = new List<bool>();
mailInfo.AttachmentContentID = new List<string>();
mailInfo.ItemTypeList = new List<string>();
mailInfo.SubEmailList = new List<MailInfo>();
#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;
}
/// <summary>
/// 从ItemAttachment获取指定用户的邮件 2017-12-8
/// </summary>
/// <param name="accountName">邮件账号</param>
/// <param name="attachmentId">附件ID</param>
/// <returns></returns>
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<string>();
mailInfo.AttachmentName = new List<string>();
mailInfo.AttachmentType = new List<string>();
mailInfo.AttachmentSize = new List<int>();
mailInfo.AttachmentByte = new List<byte[]>();
mailInfo.AttachmentIsInLine = new List<bool>();
mailInfo.AttachmentContentID = new List<string>();
mailInfo.ItemTypeList = new List<string>();
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
/// <summary>
/// 设置外出自动回复内容 2017-12-5
/// 返回1设置成功,其他值设置失败
/// </summary>
/// <param name="accountName"></param>
/// <param name="replyContent"></param>
/// <returns></returns>
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);
}
/// <summary>
/// 获取外出自动回复 2017-12-5
/// </summary>
/// <param name="emailAddressList">邮箱账号List</param>
/// <returns></returns>
public List<ExternalAutoReply> GetCustomAutoReply(List<string> emailAddressList)
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, emailAddressList[0]);
List<ExternalAutoReply> list = new List<ExternalAutoReply>();
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
}
}
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
/// <summary>
/// 隐藏构造函数,禁止通过 new 创建新对象
/// </summary>
protected ExchangeProvider()
{
//
}
private static ExchangeProvider _Instance = null;
private static object _InstanceLock = new object();
/// <summary>
/// 获取该类的唯一实例对象
/// </summary>
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();
/// <summary>
/// 获取该类的唯一实例对象
/// </summary>
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 全局变量
/// <summary>
/// Domain,如:aaa
/// </summary>
private static string DomainName = System.Configuration.ConfigurationManager.AppSettings["ExchSvrDomain"];
/// <summary>
/// 服务器地址,如:https://aaa.com/Exchange.asmx
/// </summary>
private static string ServiceUrl = System.Configuration.ConfigurationManager.AppSettings["ExchWebServicesUrl"];
/// <summary>
/// OWA地址
/// </summary>
private static string OwaUrl = System.Configuration.ConfigurationManager.AppSettings["ExchOwaUrl"];
/// <summary>
/// 代理账号
/// </summary>
private static string ADUser = System.Configuration.ConfigurationManager.AppSettings["ExchProxyUser"];
/// <summary>
/// 代理账号密码
/// </summary>
private static string ADPassword = System.Configuration.ConfigurationManager.AppSettings["ExchProxyPwd"];
/// <summary>
/// 个人邮箱账号
/// </summary>
private string EmailAccountName { get; set; }
#endregion
/// <summary>
/// Exchange WebServices配置信息实体
/// </summary>
private struct EwsConfig
{
public ExchangeVersion ExchangeVersion;
public string EWSServiceUrl;
public string ExchangeAdministrator;
public string ExchangeAdministratorPassword;
public string DomainName;
//public string OtherUserName;
}
#region 辅助
/// <summary>
/// 获取当前Exchange的版本
/// 在配置文件里可以配置节点:ExchangeVersion
/// </summary>
/// <returns></returns>
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 未读邮件/数量
/// <summary>
/// 同时获取多个目录的未读数量 2017-11-9
/// </summary>
/// <param name="accountName">邮箱账号</param>
/// <param name="folderIdList">目录ID,多个用|分开</param>
/// <returns></returns>
public List<FoldInfo> GetNoReadNumList(string accountName, string folderIdList)
{
EmailAccountName = accountName;
List<FoldInfo> listNoReadNum = new List<FoldInfo>();
if (!string.IsNullOrEmpty(folderIdList))
{
foreach (string folderid in folderIdList.Split('|'))
{
FoldInfo entity = new FoldInfo();
entity.ID = folderid;
if (folderid == "3")
{//草稿
List<FoldInfo> 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;
}
/// <summary>
/// 获取指定ID对应目录下的未读邮件数量
/// </summary>
/// <param name="accountName"></param>
/// <param name="folderid"></param>
/// <returns></returns>
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; }
}
/// <summary>
/// 设置邮件只读或未读 2017-11-14
/// </summary>
/// <param name="accountName"></param>
/// <param name="emid"></param>
/// <param name="isread"></param>
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<Item> 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<Item> 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<MailInfo> 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; }
}
/// <summary>
/// 读取未读的邮件 2017-8-28
/// </summary>
/// <param name="foldername"></param>
/// <returns></returns>
private List<MailInfo> 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<Item> list = ExchService.FindItems(foldername, sf, iv);
return ItemsResult2MailInfoList(list, false);
}
/// <summary>
/// 读取未读的邮件 2017-8-28
/// </summary>
/// <param name="folderid"></param>
/// <returns></returns>
private List<MailInfo> 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<Item> 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; }
}
/// <summary>
/// 读取未读的邮件 2017-8-28
/// </summary>
/// <param name="foldername"></param>
/// <returns></returns>
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<Item> list = ExchService.FindItems(foldername, sf, iv);
return ItemsResult2MailInfo(list, emailId);
}
/// <summary>
/// 读取未读的邮件 2017-8-28
/// </summary>
/// <param name="folderid"></param>
/// <returns></returns>
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<Item> list = ExchService.FindItems(folderid, sf, iv);
return ItemsResult2MailInfo(list, emailId);
}
/// <summary>
/// 把Exchange对象转成MailInfo对象 2017-8-28
/// </summary>
/// <param name="list">FindItemsResults</param>
/// <returns></returns>
private MailInfo ItemsResult2MailInfo(FindItemsResults<Item> list, string emailId)
{
MailInfo info = null;
List<MailInfo> result = new List<MailInfo>();
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<string>();
//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;
}
/// <summary>
/// 把Exchange对象转成MailInfo对象 2017-8-28
/// </summary>
/// <param name="list">FindItemsResults</param>
/// <returns></returns>
private List<MailInfo> ItemsResult2MailInfoList(FindItemsResults<Item> list, bool addAttachemnt)
{
List<MailInfo> result = new List<MailInfo>();
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<string>();
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
/// <summary>
/// 获取指定目录下按指定关键词搜索到的指定时间之前的指定数量的邮件
/// </summary>
/// <param name="accountName"></param>
/// <param name="filterStr"></param>
/// <param name="folderid"></param>
/// <param name="pageSize"></param>
/// <param name="lasttime"></param>
/// <param name="lastnum"></param>
/// <returns></returns>
public List<MailInfo> 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<MailInfo>(); }
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<MailInfo>(); }
}
/// <summary>
/// 在指定目录中使用指定关键字搜索指定日期之后的所有新邮件
/// </summary>
/// <param name="accountName"></param>
/// <param name="filterStr"></param>
/// <param name="folderid"></param>
/// <param name="lasttime"></param>
/// <returns></returns>
public List<MailInfo> GetNewMail(string accountName, string filterStr, string folderid, DateTime lasttime)
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
try
{
if (string.IsNullOrEmpty(folderid))
{ return new List<MailInfo>(); }
if (folderid.Length < 3)
{ return _getNewMail(filterStr, (WellKnownFolderName)Convert.ToInt32(folderid), lasttime); }
else
{ return _getNewMail(filterStr, folderid, lasttime); }
}
catch { return new List<MailInfo>(); }
}
/// <summary>
/// 获取指定用户指定ID对应的邮件信息,并且将其未读状态更新为已读,為加快讀取速度,此接口不獲取附件內容
/// </summary>
/// <param name="accountName"></param>
/// <param name="Id"></param>
/// <param name="isReadAttachContent">true读取附件内容</param>
/// <returns></returns>
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<string>();
mailInfo.AttachmentName = new List<string>();
mailInfo.AttachmentType = new List<string>();
mailInfo.AttachmentSize = new List<int>();
mailInfo.AttachmentByte = new List<byte[]>();
mailInfo.AttachmentIsInLine = new List<bool>();
mailInfo.AttachmentContentID = new List<string>();
mailInfo.HasAttachment = tmpInfo.HasAttachments;
mailInfo.ItemTypeList = new List<string>();
#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;
}
/// <summary>
/// 获取指定用户指定ID对应的邮件信息,并且将其未读状态更新为已读,此接口獲取所有附件內容
/// </summary>
/// <param name="accountName"></param>
/// <param name="Id"></param>
/// <returns></returns>
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<string>();
mailInfo.AttachmentName = new List<string>();
mailInfo.AttachmentType = new List<string>();
mailInfo.AttachmentSize = new List<int>();
mailInfo.AttachmentByte = new List<byte[]>();
mailInfo.AttachmentIsInLine = new List<bool>();
mailInfo.AttachmentContentID = new List<string>();
mailInfo.ItemTypeList = new List<string>();
//mailInfo.SubEmailList = new List<MailInfo>();
#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;
}
/// <summary>
/// 获取指定用户指定ID对应的邮件信息中的指定附件信息
/// </summary>
/// <param name="accountName"></param>
/// <param name="Id"></param>
/// <param name="fileindex">第幾個附件</param>
/// <returns></returns>
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<string>();
mailInfo.AttachmentByte = new List<byte[]>();
mailInfo.AttachmentType = new List<string>();
mailInfo.AttachmentSize = new List<int>();
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;
}
/// <summary>
/// 获取指定用户指定ID对应的邮件信息中的指定内嵌图片信息
/// </summary>
/// <param name="accountName"></param>
/// <param name="Id"></param>
/// <param name="fileindex"></param>
/// <returns></returns>
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<string>();
mailInfo.AttachmentByte = new List<byte[]>();
mailInfo.AttachmentType = new List<string>();
mailInfo.AttachmentSize = new List<int>();
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;
}
/// <summary>
/// 根据指定标题查找指定用户的邮件,并将查找到的邮件主题更新
/// 此方法用于保存草稿时,获取被保存的邮件id,指定标题为添加时手动设置
/// </summary>
/// <param name="accountName"></param>
/// <param name="signsubject"></param>
/// <param name="realsubject"></param>
/// <returns></returns>
public string GetMailID(string accountName, string signsubject, string realsubject)
{
string result = "";
List<MailInfo> 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;
}
/// <summary>
/// 将指定用户的指定邮件保存到草稿箱
/// </summary>
/// <param name="accountName"></param>
/// <param name="mi"></param>
/// <returns></returns>
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<string>(), new List<byte[]>(), new List<string>(), new List<bool>(), new List<string>(), new List<string>(), Importance.High);
}
}
em.Subject = mi.Subject;
em.Body = new MessageBody() { Text = mi.Descript };
em.ToRecipients.Clear();
List<EmailAddress> 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); }
}
/// <summary>
/// 删除指定邮件
/// </summary>
/// <param name="accountName"></param>
/// <param name="Id"></param>
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 { ;}
}
/// <summary>
/// 彻底删除指定邮件
/// </summary>
/// <param name="accountName"></param>
/// <param name="Id"></param>
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 邮件目录列表
/// <summary>
/// 获取指定目录下的一级子目录列表
/// </summary>
/// <param name="accountName"></param>
/// <param name="folderid"></param>
/// <param name="isReadSytemFolderId">是否讀取系統目錄ID對應的索引( 2017-12-11)</param>
/// <returns></returns>
public List<FoldInfo> GetChildFolderList(string accountName, string folderid, string isReadSytemFolderId)
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
try
{
EmailAccountName = accountName;
if (string.IsNullOrEmpty(folderid))
{ return new List<FoldInfo>(); }
if (folderid.Length < 3)
{ return _getChildFolderList((WellKnownFolderName)Convert.ToInt32(folderid), isReadSytemFolderId); }
else
{ return _getChildFolderList(folderid, isReadSytemFolderId); }
}
catch { return new List<FoldInfo>(); }
}
private List<FoldInfo> _getChildFolderList(WellKnownFolderName foldername, string isReadSytemFolderId)
{
FolderView folderViews = new FolderView(int.MaxValue);
FindFoldersResults folders = ExchService.FindFolders(foldername, folderViews);
return _getFolderList(folders, isReadSytemFolderId);
}
private List<FoldInfo> _getChildFolderList(string folderid, string isReadSytemFolderId)
{
FolderView folderViews = new FolderView(int.MaxValue);
FindFoldersResults folders = ExchService.FindFolders(folderid, folderViews);
return _getFolderList(folders, isReadSytemFolderId);
}
private List<FoldInfo> _getFolderList(FindFoldersResults folders, string isReadSytemFolderId)
{
//DateTime now = DateTime.Now;
//string tmp = "开始:" + now.ToString("HH:mm:ss") + "_" + now.Millisecond.ToString();
List<WellKnownFolderName> foldnamelist = new List<WellKnownFolderName>() {
WellKnownFolderName.Drafts// 这个位置不要随便动,后面有单独针对草稿箱的操作
,WellKnownFolderName.DeletedItems
,WellKnownFolderName.Inbox
,WellKnownFolderName.Outbox
,WellKnownFolderName.SentItems
,WellKnownFolderName.JunkEmail
};
List<string> foldidlist = new List<string>();
if (isReadSytemFolderId == "1")
{
for (int fi = 0; fi < foldnamelist.Count(); fi++)
{ foldidlist.Add(_getFolderID(foldnamelist[fi])); }
}
List<FoldInfo> result = new List<FoldInfo>();
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
/// <summary>
/// 获取指定WellKnownFolderName对应的UniqueId
/// </summary>
/// <param name="foldname"></param>
/// <returns></returns>
private string _getFolderID(WellKnownFolderName foldname)
{
Folder folder = Folder.Bind(ExchService, foldname);
return folder.Id.UniqueId;
}
#endregion
/// <summary>
/// 返回当前用户的草稿箱UniqueId,用于获取目录列表时,比对查找草稿箱
/// </summary>
/// <returns></returns>
private string _getDraftID()
{
Folder folder_draft = Folder.Bind(ExchService, WellKnownFolderName.Drafts);
return folder_draft.Id.UniqueId;
}
//获取指定目录下按指定关键词在指定偏移量后搜索到的指定时间之后的指定数量的邮件
private List<MailInfo> _getPageMail(string filterStr, WellKnownFolderName foldername, int pageSize, DateTime lasttime, int lastnum)
{
int mailnum = pageSize + pageSize;
lastnum = lastnum < (pageSize / 2) ? 0 : (lastnum - pageSize / 2);
FindItemsResults<Item> 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<MailInfo> result = new List<MailInfo>();
if (num < 0)
{ return result; }
return _getMailList(maillist, num, pageSize);
}
// 获取指定目录下按指定关键词在指定偏移量后搜索到的指定时间之后的指定数量的邮件
private List<MailInfo> _getPageMail(string filterStr, string folderid, int pageSize, DateTime lasttime, int lastnum)
{
int mailnum = pageSize + pageSize;
lastnum = lastnum < (pageSize / 2) ? 0 : (lastnum - pageSize / 2);
FindItemsResults<Item> 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<MailInfo> result = new List<MailInfo>();
if (num < 0)
{ return result; }
return _getMailList(maillist, num, pageSize);
}
// 在指定目录中使用指定关键字搜索指定日期之后的所有邮件
private List<MailInfo> _getNewMail(string filterStr, WellKnownFolderName foldername, DateTime lasttime)
{
int mailnum = 20;
FindItemsResults<Item> 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<MailInfo> result = new List<MailInfo>();
if (num < 0)
{ return result; }
return _getMailList(maillist, 0, num);
}
// 在指定目录中使用指定关键字搜索指定日期之后的所有邮件
private List<MailInfo> _getNewMail(string filterStr, string folderid, DateTime lasttime)
{
int mailnum = 20;
FindItemsResults<Item> 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<MailInfo> result = new List<MailInfo>();
if (num < 0)
{ return result; }
return _getMailList(maillist, 0, num);
}
// 在指定目录下用指定关键词从指定偏移量开始查找到的指定数量的返回结果
private FindItemsResults<Item> _getItemsList(string filterStr, WellKnownFolderName foldername, int num, int offset)
{
FindItemsResults<Item> 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<Item> _getItemsList(string filterStr, string folderid, int pageSize, int offset)
{
FindItemsResults<Item> 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<MailInfo> _getMailList(FindItemsResults<Item> maillist, int startnum, int pageSize)
{
List<MailInfo> result = new List<MailInfo>();
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<string>();
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<MailInfo> 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<MailInfo>(); }
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<MailInfo>(); }
}
private List<MailInfo> _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<Item> 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<MailInfo> result = new List<MailInfo>();
if (num < 0)
{ return result; }
return _getMailList(maillist, num, pageSize);
}
private List<MailInfo> _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<Item> 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<MailInfo> result = new List<MailInfo>();
if (num < 0)
{ return result; }
return _getMailList(maillist, num, pageSize);
}
private FindItemsResults<Item> _getItemsList(string filterStr, WellKnownFolderName foldername, int num, int offset, int searchType)
{
FindItemsResults<Item> 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<Item> _getItemsList(string filterStr, string folderid, int pageSize, int offset, int searchType)
{
FindItemsResults<Item> 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<EmailAddress> _getMailAddressList(string maillist)
{
List<EmailAddress> result = new List<EmailAddress>();
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
/// <summary>
/// 是否读取 收件人/发件人邮件地址(不读取 收件人/发件人邮件地址,可快速显示邮件列表),false读取,true不读取
/// 2017-9-6
/// </summary>
private bool IsQuickShowEmailList
{
get
{
return System.Configuration.ConfigurationManager.AppSettings["IsQuickShowEmailList"] == "1";
}
}
/// <summary>
/// 发送邮件 2017-9-27
/// </summary>
/// <param name="accountName"></param>
/// <param name="subject"></param>
/// <param name="mb"></param>
/// <param name="toreciptlist"></param>
/// <param name="cclist"></param>
/// <param name="bcclist"></param>
/// <param name="namelist"></param>
/// <param name="streamlist"></param>
/// <param name="typelist"></param>
/// <param name="isInLineList">list项的值为true是内嵌图片</param>
/// <param name="import"></param>
public void SendMail(string accountName, string mailId, string subject, MessageBody mb
, string[][] toreciptlist, string[][] cclist, string[][] bcclist
, List<string> namelist, List<byte[]> streamlist, List<string> typelist
, List<bool> AttachmentIsInLine, List<string> contentIDList, List<string> 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<string> addedItemAttachmentList = new List<string>();//保存已添加的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<Item> iat = em.Attachments.AddItemAttachment<Item>();//要发送的附件
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 旧接口
/// <summary>
/// 获取指定主目录的下一级子目录信息
/// </summary>
/// <param name="accountName"></param>
/// <param name="foldname"></param>
/// <returns></returns>
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<Item> list = ExchService.FindItems(foldname, sf, iv);
fi.NoRead = list.Count();
FindFoldersResults folders = ExchService.FindFolders(foldname, folderViews);
fi.ChildNum = folders.Count();
fi.ChildFolds = new List<FoldInfo>();
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<FoldInfo>();
// 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;
}
/// <summary>
/// 获取指定目录的下一级子目录信息
/// </summary>
/// <param name="accountName"></param>
/// <param name="folderid"></param>
/// <returns></returns>
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<Item> 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<FoldInfo>();
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<MailInfo> GetNextPageMail(string accountName, string filterStr, WellKnownFolderName foldname, int pageSize, DateTime lasttime
, int lastnum = 0, string filtertype = "")
{
lastnum += pageSize;
lastnum += pageSize;
FindItemsResults<Item> 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<Item> 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<MailInfo> GetNextPageMail(FindItemsResults<Item> list, int pageSize, int lastnum)
{
List<MailInfo> infoList = new List<MailInfo>();
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<string>();
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<MailInfo> GetNewMail(FindItemsResults<Item> list, DateTime lasttime)
{
List<MailInfo> infoList = new List<MailInfo>();
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<string>();
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<MailInfo> GetPageMail(string accountName, string filterStr, WellKnownFolderName foldname, int pageSize, ref int page, out int TatalPage)
//{
// FindItemsResults<Item> 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<MailInfo> GetNextPageMail(string accountName, string filterStr, string folderid, int pageSize, DateTime lasttime
, int lastnum = 0, string filtertype = "")
{
lastnum += pageSize;
lastnum += pageSize;
FindItemsResults<Item> 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<MailInfo> 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<Item> 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<MailInfo> 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<Item> 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<MailInfo> GetPageMail(string accountName, string filterStr, FolderId folderid, int pageSize, ref int page, out int TatalPage)
//{
// FindItemsResults<Item> 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<Item> getItemsList(string accountName, string filterStr, WellKnownFolderName foldname
, int num = int.MaxValue, string filtertype = "")
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
FindItemsResults<Item> 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<Item> getItemsList(string accountName, string filterStr, string folderid, int num = int.MaxValue, string filtertype = "")
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
FindItemsResults<Item> 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<Item> 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 邮件接口,供其他项目调用
/// <summary>
/// 获取邮件的所有字段信息的列表 2017-9-4
/// </summary>
/// <param name="folderid">目录ID</param>
/// <param name="num">返回数量</param>
/// <param name="offset">邮件位置</param>
/// <param name="filterStr">查询条件</param>
/// <param name="accountName">邮箱账号</param>
/// <returns></returns>
public List<MailInfo> GetEmailList(string folderid, int num, int offset, string filterStr = "", string accountName = "")
{
if (accountName != "")
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
}
FindItemsResults<Item> maillist = null;
if (folderid.Length < 3)
{ maillist = _getItemsList(filterStr, (WellKnownFolderName)Convert.ToInt32(folderid), num, offset); }
else
{
maillist = _getItemsList(filterStr, folderid, num, offset);
}
List<MailInfo> result = new List<MailInfo>();
if (num < 0)
{ return result; }
return ItemsResult2MailInfoList(maillist, true);
}
#endregion
#region 联系人接口 2017-10-18
private FindItemsResults<Item> getItemsList(string filterStr, WellKnownFolderName foldername, int num, int offset)
{
FindItemsResults<Item> 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)
);
}
/// <summary>
/// 获取个人联系人列表
/// </summary>
/// <param name="accountName"></param>
/// <param name="filterStr"></param>
/// <param name="foldername"></param>
/// <param name="pageSize"></param>
/// <param name="lastnum"></param>
/// <returns></returns>
public List<contactInfo> 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<Item> contactInfoList = getItemsList(filterStr, (WellKnownFolderName)Convert.ToInt32(folderid), pageSize, lastnum);
return _getcontactInfoList(ExchService, contactInfoList, lastnum, pageSize, isAll);
}
//private List<contactInfo> _getPageContact(string filterStr, WellKnownFolderName foldername, int pageSize, int lastnum)
//{
// int mailnum = pageSize + pageSize;
// lastnum = lastnum < (pageSize / 2) ? 0 : (lastnum - pageSize / 2);
// FindItemsResults<Item> 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<MailInfo> result = new List<MailInfo>();
// if (num < 0)
// { return result; }
// return _getMailList(maillist, num, pageSize);
//}
private List<contactInfo> _getcontactInfoList(ExchangeService ex, FindItemsResults<Item> contactInfolist, int startnum, int pageSize, bool isAll)
{
List<contactInfo> result = new List<contactInfo>();
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;
}
/// <summary>
/// 删除指定删除人
/// </summary>
/// <param name="accountName">邮箱用户名</param>
/// <param name="Id">联系人ID</param>
/// <param name="isHardDelete">是否物理删除</param>
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);
}
/// <summary>
/// 修改指定联系人
/// </summary>
/// <param name="accountName">邮箱用户名</param>
/// <param name="Id">联系人ID</param>
/// <param name="contact">联系人对象</param>
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);
}
/// <summary>
/// 修改联系人测试用
/// </summary>
/// <param name="accountName">邮箱用户名</param>
/// <param name="Id">联系人ID</param>
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);
}
/// <summary>
/// 增加联系人
/// </summary>
/// <param name="accountName">邮箱用户名</param>
/// <param name="Id">联系人ID</param>
/// <param name="contact">联系人对象</param>
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();
}
/// <summary>
/// 增加指定联系人测试用
/// </summary>
/// <param name="accountName">邮箱用户名</param>
/// <param name="Id">联系人ID</param>
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();
}
/// <summary>
/// 获取指定联系人信息
/// </summary>
/// <param name="accountName"></param>
/// <param name="Id"></param>
/// <returns></returns>
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
/// <summary>
/// 根据用户账号和當前日期获取其日程安排
/// 返回在當前日期内的安排
/// </summary>
/// <param name="accountName">當前帳號</param>
/// <param name="currDate">當前日期</param>
/// <param name="returnCount">返回數量</param>
/// <param name="Days">返回多少月的数据</param>
/// <returns></returns>
public List<AppointmentInfo> GetAppointmentsList(string accountName, DateTime currDate, int returnCount, int Month)
{
List<AppointmentInfo> infoList = new List<AppointmentInfo>();
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<Appointment> 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<AppointmentInfo> GetCalendarsList(string accountName, DateTime currDate, int returnCount, int Month, string updateDate)
{
List<AppointmentInfo> infoList = new List<AppointmentInfo>();
if (ExchService != null)
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, accountName);
//CalendarView cv = new CalendarView(currDate.Date, currDate.Date.AddMonths(Month), returnCount);
//FindItemsResults<Appointment> list = ExchService.FindAppointments(WellKnownFolderName.Calendar, cv);
FindItemsResults<Item> 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<Item> getCalendarItemsList(DateTime currDate, int Month, string updateDate, WellKnownFolderName foldername, int num)
{
FindItemsResults<Item> 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;
}
/// <summary>
/// 日历查询筛选条件
/// </summary>
/// <param name="currDate">当前日期</param>
/// <param name="Month">查询多少月</param>
/// <param name="updateDate">获取日历的最后修改时间</param>
/// <returns></returns>
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))
);
}
}
/// <summary>
/// 创建周期性的约会
/// </summary>
/// <param name="accountName"></param>
/// <param name="appInfo"></param>
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);
}
}
/// <summary>
/// 修改周期性约会
/// </summary>
/// <param name="accountName"></param>
/// <param name="Id"></param>
/// <param name="appInfo"></param>
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 邮件分页相关
/// <summary>
/// 分页读取邮件 2017-10-27
/// </summary>
/// <param name="accountName">邮箱账号</param>
/// <param name="filterStr">查询条件</param>
/// <param name="folderId">目录ID</param>
/// <param name="pageSize">每页显示的记录数量</param>
/// <param name="lastLoadTime"></param>
/// <param name="alreadyReadTotal">已读取的记录总数量</param>
/// <param name="filterType">搜索类别:主题,收件人等</param>
/// <returns></returns>
public List<MailInfo> GetPageMailList(string accountName, string filterStr, string folderId, int pageSize, DateTime lastLoadTime, int alreadyReadTotal, string filterType)
{
try
{
if (string.IsNullOrEmpty(folderId))
{
return new List<MailInfo>();
}
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<MailInfo>(); }
}
/// <summary>
/// 获取指定目录下,按指定关键词在指定偏移量后搜索到的指定时间之后的指定数量的邮件 2017-10-27
/// </summary>
/// <param name="filterStr">过滤条件</param>
/// <param name="folderName">目录名/param>
/// <param name="pageSize">每页显示的记录数量</param>
/// <param name="lastLoadTime">最后一次加载数据的时间</param>
/// <param name="alreadyReadTotal">已读取的记录总数量</param>
/// <param name="filterType">搜索类别:主题,收件人等</param>
/// <param name="listMailInfo">已读取的list</param>
/// <returns></returns>
public List<MailInfo> GetPageMailInfo(string filterStr, WellKnownFolderName folderName, int pageSize, DateTime lastLoadTime, int alreadyReadTotal, string filterType, List<MailInfo> listMailInfo)
{
List<MailInfo> listNewMailInfo = new List<MailInfo>();
if (listMailInfo != null && listMailInfo.Count > 0)
{
listNewMailInfo = listMailInfo;
}
FindItemsResults<Item> 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;
}
/// <summary>
/// 获取指定目录下,按指定关键词在指定偏移量后搜索到的指定时间之后的指定数量的邮件 2017-10-27
/// </summary>
/// <param name="filterStr">过滤条件</param>
/// <param name="folderId">目录ID</param>
/// <param name="pageSize">分页数量</param>
/// <param name="lastLoadTime">最后一次加载数据的时间</param>
/// <param name="alreadyReadTotal">已读取的记录总数量</param>
/// <param name="filterType">搜索类别:主题,收件人等</param>
/// <param name="listMailInfo">已读取的list</param>
/// <returns></returns>
public List<MailInfo> GetPageMailInfo(string filterStr, string folderId, int pageSize, DateTime lastLoadTime, int alreadyReadTotal, string filterType, List<MailInfo> listMailInfo)
{
List<MailInfo> listNewMailInfo = new List<MailInfo>();
if (listMailInfo != null && listMailInfo.Count > 0)
{
listNewMailInfo = listMailInfo;
}
FindItemsResults<Item> 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;
}
/// <summary>
/// 在指定目录下用指定关键词/指定的查询类别,查找指定数量的返回结果
/// </summary>
/// <param name="filterStr">过滤条件</param>
/// <param name="foldername">目录名</param>
/// <param name="pageSize">分页数量</param>
/// <param name="offset">下一次读取记录的位置</param>
/// <param name="filterType">搜索类别:主题,收件人等</param>
/// <returns></returns>
private FindItemsResults<Item> GetItemsResults(string filterStr, WellKnownFolderName foldername, int pageSize, int offset, string filterType)
{
FindItemsResults<Item> 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;
}
/// <summary>
/// 在指定目录下用指定关键词/指定的查询类别,查找指定数量的返回结果
/// </summary>
/// <param name="filterStr"></param>
/// <param name="filterStr">过滤条件</param>
/// <param name="folderId">目录ID</param>
/// <param name="pageSize">分页数量</param>
/// <param name="offset">下一次读取记录的位置</param>
/// <param name="filterType">搜索类别:主题,收件人等</param>
/// <returns></returns>
private FindItemsResults<Item> GetItemsResults(string filterStr, string folderId, int pageSize, int offset, string filterType)
{
FindItemsResults<Item> 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;
}
/// <summary>
/// 从查找到的ItemsResults列表读取邮件 2017-10-27
/// </summary>
/// <param name="itemsResults"></param>
/// <param name="listMailInfo">List<MailInfo>对象</param>
/// <param name="readOffset"></param>
/// <returns></returns>
private List<MailInfo> ReadMailList(FindItemsResults<Item> itemsResults, List<MailInfo> 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<string>();
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
/// <summary>
/// 移动邮件 2017-11-25
/// </summary>
/// <param name="accountName">账号名</param>
/// <param name="mailId">邮件ID</param>
/// <param name="newFolderId">新目录ID</param>
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 附件相关
/// <summary>
/// 读取ItemAttachment 2017-11-27
/// </summary>
/// <param name="accountName"></param>
/// <param name="mailId"></param>
/// <param name="fileIndex">附件索引</param>
/// <returns></returns>
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<string>();
mailInfo.AttachmentName = new List<string>();
mailInfo.AttachmentType = new List<string>();
mailInfo.AttachmentSize = new List<int>();
mailInfo.AttachmentByte = new List<byte[]>();
mailInfo.AttachmentIsInLine = new List<bool>();
mailInfo.AttachmentContentID = new List<string>();
mailInfo.ItemTypeList = new List<string>();
mailInfo.SubEmailList = new List<MailInfo>();
#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;
}
/// <summary>
/// 从ItemAttachment获取指定用户的邮件 2017-12-8
/// </summary>
/// <param name="accountName">邮件账号</param>
/// <param name="attachmentId">附件ID</param>
/// <returns></returns>
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<string>();
mailInfo.AttachmentName = new List<string>();
mailInfo.AttachmentType = new List<string>();
mailInfo.AttachmentSize = new List<int>();
mailInfo.AttachmentByte = new List<byte[]>();
mailInfo.AttachmentIsInLine = new List<bool>();
mailInfo.AttachmentContentID = new List<string>();
mailInfo.ItemTypeList = new List<string>();
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
/// <summary>
/// 设置外出自动回复内容 2017-12-5
/// 返回1设置成功,其他值设置失败
/// </summary>
/// <param name="accountName"></param>
/// <param name="replyContent"></param>
/// <returns></returns>
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);
}
/// <summary>
/// 获取外出自动回复 2017-12-5
/// </summary>
/// <param name="emailAddressList">邮箱账号List</param>
/// <returns></returns>
public List<ExternalAutoReply> GetCustomAutoReply(List<string> emailAddressList)
{
ExchService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, emailAddressList[0]);
List<ExternalAutoReply> list = new List<ExternalAutoReply>();
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
}
}