我想用Outlook向多个客户发送电子邮件。为此我在我的程序中有一个方法,它迭代收件人,组成邮件正文并将第一条邮件显示为预览。
这是该方法的简化版本:
public void CreateMails(List<InfoMailRecipient> recipients)
{
Microsoft.Office.Interop.Outlook.Application outlook = new Microsoft.Office.Interop.Outlook.Application();
foreach (InfoMailRecipient recipient in recipients)
{
MailItem mail = outlook.CreateItem(OlItemType.olMailItem);
mail.SentOnBehalfOfName = "Sending User";
mail.BCC = recipient.EMailAddress;
mail.Subject = "TEST";
mail.BodyFormat = OlBodyFormat.olFormatHTML;
mail.HTMLBody = "<html><body>test</body></html>";
mail.Display(true);
}
}
当显示Outlook消息窗口时,无论我是关闭窗口还是单击“发送”,只要应创建下一个MailItem
,我就会收到异常“RPC Server unavailable”。显然是因为Outlook已经关闭。我发现当我删除行
mail.Display(true);
然后只需拨打.Send();
即可正确发送所有邮件。但随后Outlook保持开放。即使我在.Quit()
循环后调用foreach
。
如何正确处理此Outlook实例?
更新1 - 手动GC呼叫
public void CreateMails(List<InfoMailRecipient> recipients)
{
Microsoft.Office.Interop.Outlook.Application outlook = new Microsoft.Office.Interop.Outlook.Application();
foreach (InfoMailRecipient recipient in recipients)
{
MailItem mail = outlook.CreateItem(OlItemType.olMailItem);
mail.SentOnBehalfOfName = "Sending User";
mail.BCC = recipient.EMailAddress;
mail.Subject = "TEST";
mail.BodyFormat = OlBodyFormat.olFormatHTML;
mail.HTMLBody = "<html><body>test</body></html>";
mail.Send();
}
outlook.Quit();
GC.Collect();
GC.WaitForPendingFinalizers();
}
Outlook一直在运行。
答案 0 :(得分:0)
这似乎有用 - 你能告诉我们它是否适合你吗?
public static void Main(string[] args)
{
CreateMails(new List<string>() {"emailaddresshere"});
Console.WriteLine("finished");
Console.ReadLine();
}
public static void CreateMails(List<string> recipients)
{
Microsoft.Office.Interop.Outlook.Application outlook = new Microsoft.Office.Interop.Outlook.Application();
foreach (string recipient in recipients)
{
MailItem mail = outlook.CreateItem(OlItemType.olMailItem);
mail.SentOnBehalfOfName = "Sending User";
mail.BCC = recipient;
mail.Subject = "TEST";
mail.BodyFormat = OlBodyFormat.olFormatPlain;
mail.HTMLBody = "Hello";
mail.Send();
System.Runtime.InteropServices.Marshal.ReleaseComObject(mail); // key change
}
GC.Collect();
GC.Collect();
GC.WaitForPendingFinalizers();
outlook.Application.Quit();
outlook.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(outlook); // key change
outlook = null;
GC.Collect();
GC.Collect();
GC.WaitForPendingFinalizers();
}
同时阅读https://ausdotnet.wordpress.com/category/technical/com-interop/和How to close outlook after automating it in c#。