1
votes

I'm programming an outlook add-in. I want to modify the mail before it gets sent. Therefore I have registered me for an event before the email gets sent. I can modify it but when I m trying to change the recipient of the mail (so mail.To) it gives me an error (not while my code is running but when outlook tries to sent the mail).

Error says: '...Can not resolve the receivername' (i have translated it so it is not the real error text but close to it)

Here is my code:

void Application_ItemSend(object item, ref bool cancel)
    {
        if (item is Outlook.MailItem mail)
        {
            var to = mail.To;
            var body = mail.Body;
            var editedBody = to + "#" + body;
            mail.Body = editedBody;
            mail.To = @"<another email>";
        }
    }


private void ThisAddIn_Startup(object sender, System.EventArgs e)
    {
        //Register the new event
        Globals.ThisAddIn.Application.ItemSend += Application_ItemSend;
    }
3

3 Answers

0
votes

You need to cancel the action by setting the cancel parameter to true and schedule re-sending operation with a new email address. A timer which fires the Tick event on the main thread can help with that task.

Also you may consider making a copy of the email, changing recipients (do any changes on the copy) and submit it. In that case you will have to differentiate such messages and skip them in the ItemSend event handler. To get that working you may use UserProperties.

0
votes

You are resetting all To recipients. Is that what you really want to do? Try to use MailItem.Recipients.Add (retuns Recipient object) followed by Recipient.Resolve.

You are also setting the plain text Body property wiping out all formatting. Consider using HTMLBody instead, just keep in mind that two HTML strings must be merged rather than concatenated to produce valid HTML.

0
votes

Got it working:

                    var to = string.Empty;

                    mail.Recipients.ResolveAll();

                    foreach (Outlook.Recipient r in mail.Recipients)
                    {
                        to += r.Address + ";";
                    }
                    if (to.Length > 0)
                        to = to.Substring(0, to.Length - 1);

                    mail.Body = to + "#" + mail.Body;

                    //Modify receiver
                    mail.To = string.Empty;
                    Outlook.Recipient recipient = mail.Recipients.Add("<email>");
                    recipient.Resolve();