Outlook 邮件助手
1 Overview
2 C# 编程
3 Outlook 设置
3.1 Outlook 2013
3.2 Outlook 2010
1 Overview
本章将示例如何开发一个邮件助手,对新收到的邮件进行自定义操作。例如:
- 对于垃圾邮件,直接删除
- 对于不重要邮件,自动标为已读
- 对于重要邮件,弹出提醒
2 C# 编程
需要解决如下几个问题
- 如何连接到 Outlook
- 如何获得新收到的邮件
- 如何读取邮件的信息,例如标题,发送者,邮件正文等
- 如何对邮件进行操作,例如删除,标为已读等
下面的代码演示了对上述问题的解决方案
using System;
using Outlook = Microsoft.Office.Interop.Outlook;
namespace Test
{
class Program
{
static void Main(string[] args)
{
Outlook.Application outlook = GetOutlookInstance();
if (outlook != null)
{
System.Console.WriteLine("Get outlook successfully.");
}
else
{
System.Console.Error.WriteLine("Cannot get outlook!");
return;
}
AddMonitor(outlook);
System.Console.Read();
}
//连接到 Outlook
private static Outlook.Application GetOutlookInstance()
{
Outlook.Application outlook = (Outlook.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Outlook.Application");
return outlook;
}
//添加对新到邮件的监控
private static void AddMonitor(Outlook.Application outlook)
{
Outlook.NameSpace mapiNamespace = outlook.GetNamespace("MAPI");
Outlook.MAPIFolder inbox = mapiNamespace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
inbox.Items.ItemAdd += Items_ItemAdd;
}
//读取邮件内容并进行相应处理
private static void Items_ItemAdd(object Item)
{
Outlook.MailItem mail = Item as Outlook.MailItem;
if (mail == null)
{
return;
}
Console.WriteLine(string.Format("Received Email at {0}
Subject: {1}
Sender: {2}
Content:
{3}", mail.ReceivedTime, mail.Subject, mail.Sender.Name, mail.Body));
if (mail.Subject == "test")
{
mail.Delete();
}
else if (mail.Subject == "test1")
{
mail.UnRead = false;
}
}
}
}
3 Outlook 设置
外部程序试图读取 Outlook 内容时,Outlook 会弹出如下警示框:
可对注册表进行修改阻止弹出该警示框
感谢网上的大神找到的办法How to stop the Outlook “A program is trying to access” pop-up messages
3.1 Outlook 2013
找到键 HKEY_LOCAL_MACHINESOFTWAREMicrosoftOffice15.0OutlookSecurity,如果没有则创建,并添加如下 DWORD 值
- CheckAdminSettings: 1
- AdminSecurityMode: 3
- PromptSimpleMAPISend : 2
- PromptSimpleMAPINameResolve : 2
- PromptSimpleMAPIOpenMessage : 2
- PromptOOMCustomAction : 2
- PromptOOMSend : 2
- PromptOOMAddressBookAccess : 2
- PromptOOMAddressInformationAccess : 2
- PromptOOMMeetingTaskRequestResponse : 2
再找到键 HKEY_CURRENT_USERSoftwarePoliciesMicrosoftOffice15.0outlooksecurity,如果没有则创建,并添加如下 DWORD 值
- CheckAdminSettings: 1
- AdminSecurityMode: 3
- PromptSimpleMAPISend: 2
- PromptSimpleMAPINameResolve: 2
- PromptSimpleMAPIOpenMessage: 2
- PromptOOMCustomAction: 2
- PromptOOMSend: 2
- PromptOOMAddressBookAccess: 2
- PromptOOMAddressInformationAccess: 2
- PromptOOMMeetingTaskRequestResponse: 2
3.2 Outlook 2010
操作步骤与 Outlook 2013 相同,只是将 15.0 换为 14.0