I want to send an E-Mail to multiple customers with Outlook. For this I have a method in my Program that iterates the recipients, composes the message body and displays the first message as a Preview.
This is a simplified version of that method:
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);
}
}
When the Outlook message window is displayed, no matter if I just close the window or click "Send", as soon as the next MailItem
should be created I get an exception "RPC Server unavailable". Obviously because Outlook has closed. I've found out that when I remove the line
mail.Display(true);
and just call .Send();
all the messages are sent properly. But then Outlook stays open. Even if I call .Quit()
after the foreach
loop.
How do I handle this Outlook instance properly?
Update 1 - Manual GC-Call
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 keeps running.