对邮件附件进行整理
如果你是一个管理者,常常收到各种附件形式的报表,你希望把这些附件都保存到某个目录下。这时我们可以使用Outlook的“新到邮件”事件,自动将符合条件的邮件附件保存到某个特定目录下。
首先,我们在插件加载的时候,添加一个“新到邮件”事件的事件处理函数:
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
// 添加一个“新到邮件”的事件处理函数
this.Application.NewMail += new Microsoft.Office.Interop.
Outlook.ApplicationEvents_11_NewMailEventHandler(
ThisApplication_NewMail_Filter);
}
{
// 添加一个“新到邮件”的事件处理函数
this.Application.NewMail += new Microsoft.Office.Interop.
Outlook.ApplicationEvents_11_NewMailEventHandler(
ThisApplication_NewMail_Filter);
}
添加“新到邮件”事件处理函数后,每次有新到的邮件,这个函数就会被自动调用。我们可以在这个函数中查找收件箱中所有的未读邮件,将符合条件的邮件附件保存到特定目录下。我们将这个事件处理函数实现如下,它可以查找收件箱中所有未读邮件主题包含“[Weekly Report]”字样的邮件,并将其附件保持到一个特定的目录下:
void ThisApplication_NewMail_Filter()
{
// 设置主题过滤器
string filter = "[Weekly Report]";
// 获取收件箱中的所有邮件
Outlook.MAPIFolder inBox = this.Application.ActiveExplorer()
. Session.GetDefaultFolder(Outlook
.OlDefaultFolders.olFolderInbox);
Outlook.Items inBoxItems = inBox.Items;
Outlook.MailItem newEmail = null;
// 只处理未读邮件
inBoxItems = inBoxItems.Restrict("[Unread] = true");
// 处理所有未读邮件
try
{
foreach (object collectionItem in inBoxItems)
{
// 获取未读的新邮件项
newEmail = collectionItem as Outlook.MailItem;
if (newEmail != null)
{
// 判断邮件主题是否含有过滤器字符串
if (newEmail.MessageClass == "IPM.Note" &&
newEmail.Subject.ToUpper().Contains(filter.ToUpper()))
{
// 判断邮件是否含有附件
if (newEmail.Attachments.Count > 0)
{
// 保存所有附件到特定目录
for (int i = 1; i <= newEmail
.Attachments.Count; i++)
{
newEmail.Attachments[i].SaveAsFile
(@"C:\TestFileSave\" +
newEmail.Attachments[i].FileName);
}
}
}
}
}
}
catch (Exception ex)
{
string errorInfo = (string)ex.Message
.Substring(0, 11);
if (errorInfo == "Cannot save")
{
MessageBox.Show(@"Create Folder C:\TestFileSave");
}
}
}
{
// 设置主题过滤器
string filter = "[Weekly Report]";
// 获取收件箱中的所有邮件
Outlook.MAPIFolder inBox = this.Application.ActiveExplorer()
. Session.GetDefaultFolder(Outlook
.OlDefaultFolders.olFolderInbox);
Outlook.Items inBoxItems = inBox.Items;
Outlook.MailItem newEmail = null;
// 只处理未读邮件
inBoxItems = inBoxItems.Restrict("[Unread] = true");
// 处理所有未读邮件
try
{
foreach (object collectionItem in inBoxItems)
{
// 获取未读的新邮件项
newEmail = collectionItem as Outlook.MailItem;
if (newEmail != null)
{
// 判断邮件主题是否含有过滤器字符串
if (newEmail.MessageClass == "IPM.Note" &&
newEmail.Subject.ToUpper().Contains(filter.ToUpper()))
{
// 判断邮件是否含有附件
if (newEmail.Attachments.Count > 0)
{
// 保存所有附件到特定目录
for (int i = 1; i <= newEmail
.Attachments.Count; i++)
{
newEmail.Attachments[i].SaveAsFile
(@"C:\TestFileSave\" +
newEmail.Attachments[i].FileName);
}
}
}
}
}
}
catch (Exception ex)
{
string errorInfo = (string)ex.Message
.Substring(0, 11);
if (errorInfo == "Cannot save")
{
MessageBox.Show(@"Create Folder C:\TestFileSave");
}
}
}
这样,你收到的所有符合条件的工作报告邮件的附件就会集中保存到一个特定目录,你可以集中一次查看所有报告,而无需每封邮件都打开查看了,无形中节省了你宝贵的时间,提高了你的效率。当然,在这个实例中的附件处理还非常粗糙,如果想在实际工作中应用,还可以进一步细化,比如可以根据邮件发送的日期和部门分门别类地整理附件等等,使得Outlook大大地提升我们的办事效率。
要想成为Office达人,离不开Visual Studio 2010的帮助!