鉴于项目需要,近对Outlook API进行了研究。我们需要实现通过内部工具(C#实现)调用Outlook来定期发送邮件,邮件部分内容需人工撰写,部分内容是工具自动生成的html格式的报告。大致需求如下:
  自动填写邮件主题,收件人,默认内容
  嵌入生成的html报告
  显示邮件,经发件人确认修改后手动发送
  具体解决方案如下:
  1. 添加引用。
  工程 Reference 右键 -> COM tab -> Microsoft Outlook 12.0 Object Library.
  此时可见引用列表中多了“System.Office.Interop.Outlook”.
  在程序文件头部添加“using Microsoft.Office.Interop.Outlook;”.
  2. 发送邮件。

 

# generate email automatically
private string GenerateEmail()
{
# default content of mail, sender will modify and verify before sending out
string hello = "Hi,<br><br>This is an example for sending automatic email via outlook.<br><br>Thanks,";
# html report that is gennerated automatically
string report = "<html>report content.</html>";
ApplicationClass app = new Microsoft.Office.Interop.Outlook.ApplicationClass();
MailItem mail = (MailItem)app.CreateItem(OlItemType.olMailItem); # create mail object
mail.SendUsingAccount = app.Session.Accounts[1];    # sender
string date = DateTime.Today.Month + "-" + DateTime.Today.Day + "-" + DateTime.Today.Year;    # current date,format “7-10-2013”
mail.Subject = "[" + date + ", pass] Smoke Test Report";    # email subject
mail.To = "to_1@***.com";    # To list
mail.CC = "cc_1@***.com;cc_2@***.com;";    # cc list
mail.BodyFormat = OlBodyFormat.olFormatHTML;    # email is in html format
mail.HTMLBody = hello + report + ReadSignature();    # email content
mail.Display();    # popup email interface before sending
}