neocorp
neocorp

Reputation: 569

Sending mail to multiple recipients via Interop library C#

I'm developing a desktop application that has mail sending option. I have the following code to that and it works perfect for only 1 recipient:

DialogResult status;
status = MessageBox.Show("Some message", "Info", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
if (status == DialogResult.OK)
{
    try
    {
        // Create the Outlook application.
        Outlook.Application oApp = new Outlook.Application();
        // Create a new mail item.
        Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);

        // Set HTMLBody. 
        //add the body of the email
        oMsg.HTMLBody = "<html>" +
                "<body>" +
                "some html text" +
                "</body>" +
                "</html>";

        int iPosition = (int)oMsg.Body.Length + 1;
        //Subject line
        oMsg.Subject = txt_mailKonu.Text;
        oMsg.Importance = Outlook.OlImportance.olImportanceHigh;
        // Recipient
        Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients;    
        //Following line causes the problem  
        Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add(senderForm.getRecipientList().ToString());
        oRecip.Resolve();
        //oRecip.Resolve();
        // Send.
        oMsg.Send();
        // Clean up.
        oRecip = null;
        oRecips = null;
        oMsg = null;
        oApp = null;
        MessageBox.Show("Successful", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
    catch (Exception)
    {
        MessageBox.Show("Failed", "Eror", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }                
}

I get the error at the bold line where I'm adding multiple recipients in the following pattern: [email protected]; [email protected]

It works fine for 1 address but when I get multiple addresses separated it throws COM Exception - Outlook cannot resolve one or more names.

Hope you'll help me with this.

Upvotes: 4

Views: 3064

Answers (1)

Nemanja Boric
Nemanja Boric

Reputation: 22187

Did you try to add multiple recipients to oMsg.Recipients?

// I assume that senderForm.getRecipientList() returns List<String>
foreach(String recipient in senderForm.getRecipientList())
{
    Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add(recipient);
    oRecip.Resolve();
}

If needed, you could explode senderForm.getRecipientList().ToString() with

String [] rcpts = senderForm.getRecipientList().ToString().Split(new string[] { "; " }, StringSplitOptions.None);

and use new object in foreach loop.

Upvotes: 2

Related Questions