user1067812
user1067812

Reputation: 17

Sending multiple e-mails using outlook MailItem in loop

Hello I am developing an outlook Add-on, as part of the work flow it should take the mailItem body and subject, and for each recipient it should change the body of message according to recipient e-mail.

The problem is that it just sends the first e-mail and after Send(); it does not send the e-mail to other recipients

 Outlook.Application application = Globals.ThisAddIn.Application;
        Outlook.Inspector inspector = application.ActiveInspector();
        Outlook.MailItem myMailItem = (Outlook.MailItem)inspector.CurrentItem;
        myMailItem.Save();



        if (myMailItem != null)
        {

            myMailItem.Save();
            PorceesData(myMailItem);
        }

           ..
           ..
           ..
           ..
   private void ProcessData(MailItem oMailItem)
      {

Recipients recipients = oMailItem.Recipients;

string Body = oMailItem.Body;
string To = oMailItem.To;
string CC = oMailItem.CC;
string bcc = oMailItem.BCC;

foreach (Recipient r in recipients)
{
   if (r.Resolve() == true)
    {

        string msg = "Hello open the attached file (msg.html); 
        string address = r.Address;
        oMailItem.Body = msg;
         oMailItem.To = address;
         oMailItem.Subject = "my subject"

        foreach (Attachment t in oMailItem.Attachments)
         {
              t.Delete();
            }

          oMailItem.Attachments.Add(@"mydirectory");

           oMailItem.Send();
}

Upvotes: 1

Views: 3102

Answers (1)

SliverNinja - MSFT
SliverNinja - MSFT

Reputation: 31651

_MailItem.Send() closes the current inspector. This isn't in the _MailItem.Send documentation, but is the actual Outlook implementation. You should probably come up with another approach. I'd suggest creating a new MailItem instance for each message you wish to send.

You can create a new MailItem using...

Outlook.MailItem eMail = (Outlook.MailItem)
Globals.ThisAddIn.Application.CreateItem(Outlook.OlItemType.olMailItem);
eMail.Subject = subject;
eMail.To = toEmail;
eMail.Body = body;
eMail.Importance = Outlook.OlImportance.olImportanceLow;
((Outlook._MailItem)eMail).Send();

After sending to all recipients you can manually close the current inspector using the following (Send() implicitly calls this method)

((Outlook._MailItem)myMailItem).Close(Outlook.OlInspectorClose.olDiscard)

Upvotes: 2

Related Questions