对outlook的操作。对于用微软提供的Lib来发并查找已经打开的邮件大家可能并不陌生,但是如何从我们的Outlook[邮件存在但是没有单独打开]里查找我们想要的Mail怎么办?如何确定我们点了发送按钮?类库里似乎没有提供相应的解决办法。
using OutLook = Microsoft.Office.Interop.Outlook;
1. Send mail:普通的发送邮件
public static OutLook.MailItem SendMail(string subject, string body, string to, string cc, string bcc, bool isDisply)
{
// Sets up and creates an outlook mail entry
OutLook.Application outlookApp = new OutLook.Application(); // creates new outlook app
OutLook.MailItem oMailItem = (OutLook.MailItem)outlookApp.CreateItem(OutLook.OlItemType.olMailItem);
// Set appointment settings
oMailItem.Subject = subject;// set the subject
// oMailItem.BodyFormat = Microsoft.Office.Interop.Outlook.OlBodyFormat.olFormatRichText;
oMailItem.Body = body; // set the body
oMailItem.ReminderSet = true; // Set the reminder
oMailItem.To = to;
oMailItem.CC = cc;
oMailItem.BCC = bcc;
oMailItem.Display(isDisply);
return oMailItem;
}
2. Find Mail:从邮箱里查找指定内容的邮件
public static OutLook.MailItem FindLatestMail(string searchText)
{
OutLook.Application oApp;
OutLook._NameSpace oNS;
OutLook.MAPIFolder oFolder;
OutLook._Explorer oExp;
OutLook.MailItem oMail = null;
OutLook.MailItem oMailReply = null;
oApp = new OutLook.Application();
oNS = (OutLook._NameSpace)oApp.GetNamespace("MAPI");
oFolder = oNS.GetDefaultFolder(OutLook.OlDefaultFolders.olFolderInbox);
oExp = oFolder.GetExplorer(false);
if (string.IsNullOrEmpty(searchText))
{
oMail = (OutLook.MailItem)oApp.CreateItem(OutLook.OlItemType.olMailItem);
oMail.Display(true);
oMail.Subject = searchText;
return oMail;
}
try
{
oNS.Logon(Missing.Value, Missing.Value, false, true);
String filter = String.Format("@SQL=\"{0}{1}\" ci_phrasematch '{2}'", PROPTAG, PR_SUBJECT, searchText);
OutLook.Items items = oFolder.Items;
OutLook.Items filteredItems = items.Restrict(filter);
filteredItems.Sort("[LastModificationTime]", true);
foreach (OutLook.MailItem item in filteredItems)
{
oMail = item;
break;
}
if (oMail == null)
{
oMail = (OutLook.MailItem)oApp.CreateItem(OutLook.OlItemType.olMailItem);
oMail.Subject = searchText;
}
else
{
oMailReply = oMail.ReplyAll();
}
}
catch
{
oMailReply = null;
}
return oMailReply;
}
3. Sent mail: 查找包含指定内容的邮件后,在回复邮件成功后Do something…
try
{
Outlook.MailItem mailItm = ApplicationCommon.FindLatestMail(“Hello boy”);
mailItm.Display(true);
}
catch (System.Runtime.InteropServices.COMException ex)
{ {
if (ex.Message.ToString() == "The item has been moved or deleted.")
{
// Do something …//发送成功
}
}