您的位置:首页 > 编程语言 > C#

删除Outlook 2007中重复邮件的C#代码

2009-03-13 11:27 369 查看
  除夕的时候写过一个用来删除Outlook中重复邮件的程序,因为年底前Apply了多次配置不恰当的Rules导致在不同的子目录中出现了很多相同的邮件。(Outlook会把分别匹配各条规则的邮件,分发到各规则指定的文件夹中,出现多个拷贝,这是By design的)

  当时写的代码,主要是为了完成这个目标,基本没有考虑效率问题,代码也很混乱。这个星期写了另一个控制Outlook的C#程序,就顺手把那个这个程序重写了一下,优化了不少。

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Office.Interop.Outlook;

namespace CleanRedundantMail
{
class Program
{
static Queue<MailItem> mailQueue = new Queue<MailItem>();
static int numDeleted = 0;

static void Main(string[] args)
{
Application outLookApp = new Application();
NameSpace outlookNS = outLookApp.GetNamespace("MAPI");
MAPIFolder inBox = outlookNS.GetDefaultFolder(OlDefaultFolders.olFolderInbox);
ListAllFolders(inBox);
DeleteRedundant(outLookApp);
Console.WriteLine(numDeleted);
}

private static void ListAllFolders(MAPIFolder folder)
{
ListAllMails(folder);
foreach (MAPIFolder subfolder in folder.Folders)
{
ListAllFolders(subfolder);
}
}

private static void ListAllMails(MAPIFolder folder)
{
DateTime tryTime;
foreach (object obj in folder.Items)
{
MailItem olMail = obj as MailItem;
if (olMail != null)
{
try
{
tryTime = olMail.ReceivedTime;
mailQueue.Enqueue(olMail);
}
catch
{ }
}
}
}

private static void DeleteRedundant(Application outLookApp)
{
MailItem tempMail = outLookApp.CreateItem(OlItemType.olMailItem) as MailItem;
tempMail.Subject = "";
foreach (MailItem olMail in mailQueue.OrderBy(mailinfo => mailinfo.ReceivedTime))
{
if (olMail.ReceivedTime == tempMail.ReceivedTime && olMail.Subject == tempMail.Subject)
{
olMail.Delete();
numDeleted++;
}
else
{
tempMail = olMail;
}
}

}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息