Eugene Astafiev

How To: Change an Outlook e-mail message before sending using C# or VB.NET

As a developer you may want to modify an e-mail before sending it (eidt or just add some information, such as a non-disclosure agreement etc.). It is a fairly simple task that every Outlook developer should be familiar with. For example, sometimes you may need to change the subject of a message by adding an ID or something else to track the item in your Inbox; add something to the e-mail body; or decide whether to add an attachment to the automatically generated message or not in the process of sending e-mails and, of course, attach it if needed.

The Outlook Object Model provides the ItemSend event of the Application class for this. This event triggers right after the user clicks the Send button in Outlook (before the inspector window is closed) or when the Send method of Outlook items is called. The ItemSend event provides two parameters to the programmer:

  • The Item object – an Outlook item which is going to be sent. Can be represented by the AppointmentItem, MailItem, MeetingItem, MobileItem, SharingItem, TaskItem classes.
  • The Cancel parameter – allows you to cancel sending in Outlook. The default value is false. If you set the Cancel parameter to true in the event handler, the sending process is cancelled and the inspector window is shown to the user.

Note. Add-in Express encapsulates these two parameters into the AddinExpress.MSO.ADXOlItemSendEventArgs class which has the corresponding properties: the Item and Cancel properties.

As you see, the ItemSend event allows canceling the initiated sending process. For example, you can inspect the message properties and, if it contains some confidential information you don’t want to be sent outside, you can just cancel sending it.

In the code below I add an importance notice to the subject (“!IMPORTANT“), add a string to the end of the message body like my Windows Phone 7 smartphone does (“Sent from my Outlook 2010“). And finally, I add myself to the BCC field: add a new recipient to the Recipients collection of the e-mail message and set its type to the BCC value. Looks like a simple replica (a few lines of code ;-)) of the Auto BCC for Outlook add-in developed by our guys from the AbleBits team. Don’t you think so?

In Add-in Express based add-ins you can use the AddinExpress.MSO.ADXOutlookAppEvents component to access the ItemSend event in Outlook. This component contains the list of major events the Outlook Object Model provides to the programmer. I.e. you don’t need to look which Outlook class provides a particular event; you just need to add your own handler. Add-in Express does all the backstage work for you.

As a workaround, you can add your event handler manually using the ItemSend event of the Application class. VSTO doesn’t provide any alternative way: you have to use the event which the Application class has. So, let’s proceed to coding!

C# and Add-in Express

private void adxOutlookEvents_ItemSend(object sender, ADXOlItemSendEventArgs e)
{
    Outlook.Recipient recipient = null;
    Outlook.Recipients recipients = null;    
    Outlook.MailItem mail = e.Item as Outlook.MailItem;
    if (mail != null)
    {
        string addToSubject = " !IMPORTANT";
        string addToBody = "Sent from my Outlook 2010";
        if(!mail.Subject.Contains(addToSubject)) 
            mail.Subject += addToSubject;
        if(!mail.Body.EndsWith(addToBody))
            mail.Body += addToBody;
        recipients = mail.Recipients;
        recipient = recipients.Add("Eugene Astafiev");
        recipient.Type = (int)Outlook.OlMailRecipientType.olBCC;
        recipient.Resolve();
        if (recipient != null) Marshal.ReleaseComObject(recipient);
        if (recipients!=null) Marshal.ReleaseComObject(recipients);
    }
}

C# and Add-in Express

Private Sub adxOutlookEvents_ItemSend(sender As System.Object, _
                                      e As AddinExpress.MSO.ADXOlItemSendEventArgs) _
                                      Handles adxOutlookEvents.ItemSend
    Dim recipient As Outlook.Recipient = Nothing
    Dim recipients As Outlook.Recipients = Nothing    
    Dim mail As Outlook.MailItem = TryCast(e.Item, Outlook.MailItem)
    If Not IsNothing(mail) Then
        Dim addToSubject As String = " !IMPORTANT"
        Dim addToBody As String = "Sent from my Outlook 2010"
        If Not mail.Subject.Contains(addToSubject) Then
            mail.Subject += addToSubject
        End If
        If Not mail.Body.EndsWith(addToBody) Then
            mail.Body += addToBody
        End If
        recipients = mail.Recipients
        recipient = recipients.Add("Eugene Astafiev")
        recipient.Type = Outlook.OlMailRecipientType.olBCC
        recipient.Resolve()
        If Not IsNothing(recipient) Then Marshal.ReleaseComObject(recipient)
        If Not IsNothing(recipients) Then Marshal.ReleaseComObject(recipients)
    End If
End Sub

C# and VSTO:

using System.Runtime.InteropServices;
// ...
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
    Application.ItemSend += new 
        Outlook.ApplicationEvents_11_ItemSendEventHandler(Application_ItemSend);
}
 
void Application_ItemSend(object Item, ref bool Cancel)
{
    Outlook.Recipient recipient = null;
    Outlook.Recipients recipients = null;    
    Outlook.MailItem mail = Item as Outlook.MailItem;
    if (mail != null)
    {
        string addToSubject = " !IMPORTANT";
        string addToBody = "Sent from my Outlook 2010";
        if (!mail.Subject.Contains(addToSubject))
        mail.Subject += addToSubject;
        if (!mail.Body.EndsWith(addToBody))
        mail.Body += addToBody;
        recipients = mail.Recipients;
        recipient = recipients.Add("Eugene Astafiev");
        recipient.Type = (int)Outlook.OlMailRecipientType.olBCC;
        recipient.Resolve();
        if (recipient != null) Marshal.ReleaseComObject(recipient);
        if (recipients != null) Marshal.ReleaseComObject(recipients);
    }
}

VB.NET and VSTO:

Imports System.Runtime.InteropServices
' ...
Private Sub OnItemSend(Item As System.Object, ByRef Cancel As Boolean) _
                       Handles Application.ItemSend
    Dim recipient As Outlook.Recipient = Nothing
    Dim recipients As Outlook.Recipients = Nothing    
    Dim mail As Outlook.MailItem = TryCast(Item, Outlook.MailItem)
    If Not IsNothing(mail) Then
        Dim addToSubject As String = " !IMPORTANT"
        Dim addToBody As String = "Sent from my Outlook 2010"
        If Not mail.Subject.Contains(addToSubject) Then
            mail.Subject += addToSubject
        End If
        If Not mail.Body.EndsWith(addToBody) Then
            mail.Body += addToBody
        End If
        recipients = mail.Recipients
        recipient = recipients.Add("Eugene Astafiev")
        recipient.Type = Outlook.OlMailRecipientType.olBCC
        recipient.Resolve()
        If Not IsNothing(recipient) Then Marshal.ReleaseComObject(recipient)
        If Not IsNothing(recipients) Then Marshal.ReleaseComObject(recipients)
    End If
End Sub

See you on our forums and in the e-mail support!

You may also be interested in:

How To: Create and send an Outlook message programmatically
How To: Fill TO,CC and BCC fields in Outlook programmatically

60 Comments

  • lucie says:

    Hi!
    Is that work when you have an embed image in your mail? (like a signature)

  • Eugene Astafiev says:

    Hi Lucie,

    Yes, it does. I have just tested it on my PC with Outlook 2010 x64.

    Do you compose a message in the HTML format? If so, please consider using the HTMLBody property in this case.

  • Rob K says:

    Is an Add-in Express ItemSend event handler able to modify the MailItem.SentOn and MailItem.Sent fields of the MailItem object that is being composed?

    Those fields are both always readonly in the OOM, and although Redemption makes both fields writable, I’m not having any success with that.

    I see in https://www.add-in-express.com/programming-outlook-express/objects.php that MailItem.SentOn is writable, but MailItem.Sent isn’t mentioned, and because a MailItem being composed isn’t quite the same as one that went through a mailserver, I thought I should ask.

    (Background info: the plugin I’m writing (in C# for Outlook2007&2010) is conditionally rerouting the composed email without sending it to the actual mailserver, but I want it to “look like” it was sent. My ItemSend handler can Move() it to the Sent folder, cancel the send, and close/discard the Inspector window just fine, but the Sent: date header is “None” and Outlook shows “This message has not been sent.” when viewing it in the Sent folder)

    (Feel free to move this into the forums if that is a more appropriate place).

  • Eugene Astafiev says:

    Hi Rob,

    Note, the mentioned above link relates to Outlook Express (not Microsoft Office Outlook). The Sent and SentOn propeties are read-only in the Outlook Object Model. To bridge the gap please try to use Extended MAPI or any third-party libraries (for example, such as Redemption).

  • Pratik J says:

    Hi Eugene,

    Can you tell me how can I append my new text that will be same formatted as my original HTML body of the email?

    Thanks,
    Pratik J

  • Andrei Smolin (Add-in Express Team) says:

    Hello Patrik,

    It is possible. This requires that you parse the HTML body to find out the format(s) used and then use the same format(s) in the HTML code which you append to the body.

  • Pratik J says:

    Hello Andrei, thanks for your reply,

    I referred your blog https://www.add-in-express.com/creating-addins-blog/2008/03/28/build-outlook-add-in-in-net-to-manage-outlook-templates-signatures/ which suggests using Inspector.EditorType property, my EditorType is olEditorWord but I am quite a newbie to this, and not sure how to use it to append text to the existing body with same formatting. Do you have some sample that will help me resolve this issue?

    Thank you,
    Pratik J

  • Andrei Smolin (Add-in Express Team) says:

    olEditorWord means you’ve opened the email in Outlook 2007-2013: they use Word as an email editor. Now, you need to get Inspector.WordEditor, cast it to Word.Document and use the Word object model to modify the document. After modifying it, you may need to save the Outlook item opened in this inspector (Inspector.CurrentItem and MailItem.Save).

    As to the Word object model, I suggest that you record a macro while performing the things in UI which you need to perform programmatically. The macro will show you the objects and members to use in your code. Further details on the Word object model are given at https://msdn.microsoft.com/en-us/library/vstudio/kw65a0we.aspx.

  • mostafa says:

    hi
    I want in Compose Email read fields(TO,CC,Bcc,…) filled by user before user click On button send? I how to do ?How i do it with C#?
    thanks

  • Andrei Smolin (Add-in Express Team) says:

    In the ItemSend event of the Outlook.Application object, you call MailItem.Save() first, then read MailItem.To, MailItem.CC, MailItem.BCC. Also, you may want to walk through the MailItem.Recipients collection. In Add-in Express, the ItemSend event is mapped to the ItemSend event of the ADXOutlookAppEvents component: right-click the designer surface of the add-in module and see the item Add Events in the context menu.

  • mostafa says:

    thank you so much MR.Andrei Smolin
    how to get current user or sender email in compose ?
    thank you very much

  • Andrei Smolin (Add-in Express Team) says:

    See Namespace.CurrentUser. Note that calling this property produces an Outlook security warning if this is specified by an Exchange administrator. In this case, you’ll neeed to use our Security Manager for Outlook, see https://www.add-in-express.com/outlook-security/index.php.

  • Nitin Rawat says:

    Hey I was looking for this only.
    Thanks buddy

  • Nitin Rawat says:

    Have a question , will be glad if you can help.
    In the Item_Send event I am moving the mailitem to a separate folder(My Outbox) and cancelling the send processing by setting the Cancel to true.
    My question is . I want to trigger a code whenever a mailitem is entering My Outbox folder. Please tell how to achieve it.

  • Andrei Smolin (Add-in Express Team) says:

    Hello Nitin,

    See the ItemAdd event – https://msdn.microsoft.com/en-us/library/office/ff869609%28v=office.15%29.aspx.

  • Am says:

    I want to set the followup message sign programmatically using c#, when i send a message using outlook 2010, How can i send followup at message?

  • Dmitry Kostochko (Add-in Express Team) says:

    Hi Am,

    You can connect to the Items.ItemAdd event of the Sent Items folder and call the MarkAsTask method for the email item passed to the event handler.

  • Sudharshan Talari says:

    I want to update the content of Meeting Invite body in which the html content is set already on loading using Word Editor. I am triggering ItemSend event to update content before sending but somehow the changes are not reflecting on recipient’s copy. The changes are reflecting fine in host’s calendar. I am invoking appointmentItem.Save() and display() methods after updating the content but changes are reflecting though the Body property showing updated text (plain text) when I put breakpoint and debugged the code. Can you please tell me how we can update the body html content (set thru WordEditor) of AppointmentItem before sending it?

  • Andrei Smolin (Add-in Express Team) says:

    Hello Sudharshan,

    There’s no HTMLBody property on the list of members of the AppointmentItem class, see https://msdn.microsoft.com/en-us/library/office/ff869026%28v=office.15%29.aspx. I suggest that you use Inspector.WordEditor to get a Word.Document representing the item’s body and use the Word object model to edit the document as required. Make sure that you release all COM objects that your code creates.

  • Sudharshan Talari says:

    Thanks Andrei for quick reply! I know that appointmentItem object doesn’t have HTMLBody property but the actual issue here is the Body is not getting saved (receipent’s not receiving updated template) when we update details in ItemSend event.
    Currently we are using Inspector.WordEditor and associated word document object to load html template in the body while creating new AppointmentItem (let’s say the code is in InitBody()). Once appointment Inspector is loaded with html template, if user updates any of appointment details like change appointment time or set Recurrence pattern then we need to update body (html template) with those details before sending it. So what we are doing is we are recalling that initial loading function InitBody() from ItemSend() event, thus it is using Inspector.WordEditor and its Word.Document again to reload the template with updated details. The Guest’s are NOT seeing updated invitation though Host copy has updated details. Thus, whatever changes we made in ItemSend event those are not saved on the original ApoointmentItem. Do we have any other solution that you guys can suggest to update ApoointmentItem’s HTML content body before sending it?

  • Andrei Smolin (Add-in Express Team) says:

    When a meeting request is sent, you can find in the ItemSend event that Outlook actually sends a MeetingItem, not AppointmentItem. If you modify the MeetingItem’s body (see code below) in the ItemSend event, then the modifications do not come through. This happens for me in Outlook 2013. I suppose this is the issue you are having. But this works if you modify the associated AppointmentItem instead; you get it via MeetintgItem.GetAssociatedAppointment(false), see https://msdn.microsoft.com/en-us/library/office/ff867189%28v=office.15%29.aspx.

    Here’s my test InitBody method:

    using Outlook = Microsoft.Office.Interop.Outlook;
    using Word = Microsoft.Office.Interop.Word;

    private void InitBody(Outlook._AppointmentItem appointment) {
    System.Diagnostics.Debug.WriteLine(“!!! InitBody(_AppointmentItem)”);
    Outlook._Inspector inspector = appointment.GetInspector;
    object wordEditor = inspector.WordEditor;
    if (wordEditor != null) {
    System.Diagnostics.Debug.WriteLine(“!!! wordEditor != null”);
    Word.Document document = wordEditor as Word.Document;
    Word.Range content = document.Content;
    System.Diagnostics.Debug.WriteLine(“!!! content.Text='” + content.Text + “‘”);
    System.Diagnostics.Debug.WriteLine(“!!! appointment.Subject=” + appointment.Subject);
    content.Text += “\n” + appointment.Subject;
    System.Diagnostics.Debug.WriteLine(“!!! content.Text='” + content.Text + “‘”);
    Marshal.ReleaseComObject(content); content = null;
    Marshal.ReleaseComObject(wordEditor); wordEditor = null;
    }
    Marshal.ReleaseComObject(inspector); inspector = null;
    System.Diagnostics.Debug.WriteLine(“!!! InitBody end”);
    }

    Here’s how I call it:

    private void adxOutlookEvents_ItemSend(object sender, ADXOlItemSendEventArgs e) {
    System.Diagnostics.Debug.WriteLine(“!!! adxOutlookEvents_ItemSend”);
    System.Diagnostics.Debug.WriteLine(“!!! TypeName(e.Item)=” + Microsoft.VisualBasic.Information.TypeName(e.Item));
    if (e.Item is Outlook._MeetingItem) {
    Outlook._MeetingItem meetingItem = e.Item as Outlook._MeetingItem;
    Outlook._AppointmentItem appointment = meetingItem.GetAssociatedAppointment(false);
    //meetingItem.Save();
    InitBody(appointment);
    //meetingItem.Save();
    System.Diagnostics.Debug.WriteLine(“!!! adxOutlookEvents_ItemSend end”);
    }
    }

  • Sean Ram says:

    This is good information! In my scenario, the email body already has some text and email signature. I want to insert new text programatically just before the signature. The current explanation adds the text after the outlook signature.

  • Andrei Smolin (Add-in Express Team) says:

    Hello Sean,

    Outlook 2007+ uses the Word object model. You get Inspector.WordEditor and cast it to Word.Document. Then you parse the document to find the signature and modify the text as required. In the scenario which is most common, the signature is wrapped with a bookmark called _MailAutoSig. Getting this bookmark requires setting Document.Bookmarks.ShowHidden=true.

  • Derek says:

    Hi,

    I am trying to create a Script that will add a text on the subject (but keeps the original) of the email before it gets forwarded to another email address. I am No Outlook Developer and this is the first time i am writing one.

    My criteria is set on the rule it self, the only function that the script will do is check the subject if it contains certain text then depending on the text on the subject it will add a certain text on it but will keep the original subject.

    Example, the email I receive contains JobsDB on the subject then the text that should be added to the subject is (added text–>”Jobs DB” JobsDB<–Original Subject) then it gets forwarded to a certain address. If the subject does not contains JobsDB then will go to next IF to check if it contains Indeed. If it does not it will go to another IF to check if it contains LinkedIn.

    Current code that I used, is:

    Sub ForwardEmailIndeed(Item As Outlook.MailItem)

    Set myForward = Item.Forward

    If Item.Subject.Contains("Indeed") Then
    myForward.Subject = Item.Subject & ("Indeed")

    If Item.Body.Contains("s1JOBS") Then
    myForward.Subject = Item.Subject & ("S1 Jobs")

    If Item.Subject.Contains("JobsDB") Then
    myForward.Subject = Item.Subject & ("JobsDB")

    If Item.Subject.Contains("TradeWindsJobs") Then
    myForward.Subject = Item.Subject & ("Tradewinds")

    If Item.From.Contains("auto@oilandgasjobsearch.com") Or Item.Body.Contains("oilandgasjobsearch.com") Then
    myForward.Subject = Item.Subject & ("Oil&Gas JobSearch")

    If Item.From.Contains("LinkedIn") Or Item.Body.Contains("LinkedIn") Then
    myForward.Subject = Item.Subject & ("Linkedin Advert")

    End If

    myForward.Recipients.Add "derekpatrickdaya@yahoo.com"

    myForward.Send

    End Sub

    My rule works correctly but the script associated to it (above code) is not working.

    PLEASE HELP ME!

  • Derek says:

    This Code previously worked for me.

    Sub ForwardEmail(Item As Outlook.MailItem)

    Set myForward = Item.Forward

    myForward.Subject = Item.Subject & (“Indeed”)
    myForward.Recipients.Add “derekpatrickdaya@yahoo.com”

    myForward.Send

    End Sub

    Now it does not work anymore. it does not forward anything. :(

  • Dmitry Kostochko (Add-in Express Team) says:

    Hi Derek,

    I can assume that your code is not executed by Outlook rule for some reason. I would suggest that you add an MsgBox call to your code (for testing purposes only) to ensure it is executed. If you don’t see the MsgBox, try to recreate Outlook rule.

  • Derek says:

    Hi Dmitry,

    I recreated the rule and used this:

    Apply this rule after the messages arrives
    with Indeed in the Subject
    and on this computer only
    assign it to the Added To Salesforce category
    and run Project1.ThisOutlookSession.ForwardEmail

    The rule works until assign it to the Added To Salesforce category but it never forwards the email to derekpatrickdaya@yahoo.com

    Sub ForwardEmail(Item As Outlook.MailItem)

    Set myForward = Item.Forward

    If InStr(Item.Subject, “Indeed”) Then
    myForward.Subject = Item.Subject & (“Indeed”)

    If InStr(Item.Subject, “s1JOBS”) Then
    myForward.Subject = Item.Subject & (“S1 Jobs”)

    If InStr(Item.Subject, “JobsDB”) Then
    myForward.Subject = Item.Subject & (“JobsDB”)

    If InStr(Item.Subject, “TradeWindsJobs”) Then
    myForward.Subject = Item.Subject & (“Tradewinds”)

    If InStr(Item.From, “auto@oilandgasjobsearch.com”) Or InStr(Item.Body, “oilandgasjobsearch.com”) Then
    myForward.Subject = Item.Subject & (“Oil&Gas JobSearch”)

    If InStr(Item.Subject, “LinkedIn”) Or InStr(Item.Subject, “LinkedIn”) Then
    myForward.Subject = Item.Subject & (“Linkedin Advert”)

    End If

    myForward.Recipients.Add “derekpatrickdaya@yahoo.com”

    myForward.Send

    End Sub

  • Sudharshan says:

    Inserting Signature crashing the HTML designed templates in outlook invites.

    We have developed an Outlook Add-in to create HTML designed outlook invites but been facing an issue when inserting signature into these templates. These templates are made of HTML tags and images and we are using Word Editor to render the design onto Outlook invites. These templates also contains a text area in the middle for the user to type any message. When user tries to insert a signature (Insert – Signature) in this Text area, then all this template will get crash and whatever the content on the invite is there all will disappear. This works fine when user inserts signature outside of the template.
    We are trying to find the event handler for Insert-Signature click, so that we can reload whole HTML template with user entered text and signature but did not find it.
    Can someone please help us on how to handle Insert-Signature click using Add-in Express library. Appreciate if you could provide other possible solutions to resolve this issue that would be great.

  • Andrei Smolin (Add-in Express Team) says:

    Hello Sudharshan,

    The Ribbon API doesn’t let you intercept choosing an item in the ribbon menu/gallery.

    I suppose the issue may relate to the fact that the signature is wrapped with a bookmark called _MailAutoSig; at the very least, this is true in Outlook 2010-2013. Getting the bookmark requires setting Document.Bookmarks.ShowHidden=true. That is, you get Inspector.WordEditor, cast it to Word.Document, and then deal with the bookmark. I think you make the bookmark to include the things that Outlook cannot deal with or ignore.

  • Sudharshan says:

    Thanks for the reply Andrei!

    Currently we have not coded anything to insert signature programmatically on the invite. But user can intercept signature into free Text Area manually by selecting Insert-Signature on the Menu during invite creation or modification which actually crashing the html template and content is disappearing. So we are looking to find a way to handle Ribbon item“Insert – Signature” click event, so that we can reload all the template again along with the signature. Is it possible to handle Ribbon’s “INSERT” item handler (just like Send event) programmatically on the new Inspector? If so how?

    Or is it possible to disable “Signature” button under INSERT menu item of the new Inspector? If it can be disabled then looking to add new option with in our Add-in ribbon for the user to choose and intercept signature on the invite which I believe will have full control on it.

  • Andrei Smolin (Add-in Express Team) says:

    Sudharshan,

    As explained you cannot intercept clicking a signature item in the Insert Signature menu. You can disable the menu items however. Here’re the setting of an ADXRibbonCommand that does this in a compose email inspector:

    this.adxRibbonCommand1.ActionTarget = AddinExpress.MSO.ADXRibbonCommandTarget.NonActionControl;
    this.adxRibbonCommand1.Enabled = false;
    this.adxRibbonCommand1.Id = %a unique string%;
    this.adxRibbonCommand1.IdMso = “SignatureGallery”;
    this.adxRibbonCommand1.Ribbons = AddinExpress.MSO.ADXRibbons.msrOutlookMailCompose;

  • Dmitry Kostochko (Add-in Express Team) says:

    Hi Derek,

    Sorry, your message has been in the pending category for quite a long time. Please add an MsgBox call to your code and re-test it. If you don’t see the MsgBox, then the rule is not executed.

  • Allen says:

    Hi, I’m working on outlook 2016,
    I want to get email current content, before send.
    On outlook 2010, it works well, but I cannot get the contents on outlook 2016.
    I’m using visual studio 2010, (C#).
    What I have to do? Please help.. thanks ;(

  • Andrei Smolin (Add-in Express Team) says:

    Hello Allen,

    Try to save the email before reading it.

  • Nikhil says:

    Hi Andrei:

    I want to encode the message as PGP/MIME when the user clicks the Send Button.

    The MIME for PGP/MIME messages look like this:



    Content-Type: multipart/encrypted; boundary=foo;
    protocol=”application/pgp-encrypted”

    Can I change the Content-Type (or any other MIME headers) of an outgoing email item inside ItemSend() (or any other method)?

    Thanks!
    Nikhil

  • Andrei Smolin (Add-in Express Team) says:

    Hello Nikhil,

    When you click the Send button, no headers exist; they are added to the email when it is actually sent (this occurs outside of Outlook). Also, just changing the headers won’t encode the message. I don’t know how to achieve this as this is outside of the scope of Add-in Express.

  • Nikhil says:

    Hi Andrei:

    Thanks for your response.

    I suppose, another option for me is to:
    1) Capture the contents of the Compose MailItem
    2) mailItem.GetInspector.Close(Outlook.OlInspectorClose.olDiscard); – To discard the message
    3) Apply PGP/MIME myself & create the message MIME.
    4) Send the message from my add-in directly using EWS (instead of relying on Outlook).

    I believe that should work.

    The only point I am wondering about is, if I send the message in add-in directly to Exchange (instead of using Outlook), can I fetch it from Exchange using Outlook VSTO object model and store it in the Sent items folder. Would that be possible?

    Thanks
    Nikhil

  • Andrei Smolin (Add-in Express Team) says:

    > if I send the message in add-in directly to Exchange (instead of using Outlook), can I fetch it from Exchange using Outlook VSTO object model and store it in the Sent items folder. Would that be possible?

    I seriously doubt it. But I have to admit that I don’t know features that Exchange provides for developers.

  • Lawrence E Hughes says:

    Hi,

    Is there a way to update the message header before sending an email? I need to include my own encryption on message send.

    Thanks,
    Lawrence.

  • Andrei Smolin (Add-in Express Team) says:

    Hello Lawrence,

    The internet headers don’t exist before the message is actually sent. Still, you can use the code below to add a custom value to the headers: MailItem.PropertyAccessor.SetProperty(‘https://schemas.microsoft.com/mapi/string/{00020386-0000-0000-C000-000000000046}/X-{element name such as ProjectID}’, ‘{some value such as Project #123}’).

  • Sangeetha Mohan says:

    overriding the send options is working great but is it possible to override the validations like even if wrong mail id is typed in To field or nothing is typed I don’t want to see validation or check name popup.

    Is it possible to do so? if so please let me know.

  • Sangeetha Mohan says:

    And also it would be great if To filed is disabled for user entry.

  • Dmitry Kostochko (Add-in Express Team) says:

    Hi Sangeetha,

    Unfortunately the Outlook Object Model does not provide any methods for developers to implement such tasks.

  • Doug says:

    Sorry, this is a really old post but I’m trying to display a pop-up to users when they click Send in Outlook 2016. It’s not working…the message will just be sent without interruption. I buildt the VSTO using the VB.NET example you provided to see if it would work but the message was sent normally. Any ideas? How do we get a VSTO add-in to detect the Send event and do something?

  • Dmitry Kostochko (Add-in Express Team) says:

    Hello Doug,

    I have just created a simple VSTO add-in with the following code:

    Public Class ThisAddIn

    Private Sub ThisAddIn_Startup() Handles Me.Startup

    End Sub

    Private Sub ThisAddIn_Shutdown() Handles Me.Shutdown

    End Sub

    Private Sub OnItemSend(Item As System.Object, ByRef Cancel As Boolean) Handles Application.ItemSend

    System.Windows.Forms.MessageBox.Show(“OnItemSend!”)

    End Sub
    End Class

    It works for me, I see the message box when sending an email. Please check if your add-in works in your Outlook. You can find the list of active add-ins in the COM Add-ins dialog.

  • Suman Das says:

    Hello,
    I am creating an add-in that will process emails after sent. But not all, only those marked while sending. I could implement Application_Itemsent event and process those while sending(before), but could not do it due to not availability of sender email address. I tried with SentItems folder ItemAdded event, where I added custom properties(MailItem) while sending. And it worked. But when I configured a Gmail Account I am not getting those Cutstom Properties in SentItems folder ItemAdded event. Can you please help me

    Thanks
    Suman

  • Andrei Smolin (Add-in Express Team) says:

    Hello Suman,

    Try to use a custom named property instead; see Adding User Properties and disabling TNEF at https://www.add-in-express.com/forum/read.php?FID=5&TID=14156.

    Another way would be to use the ItemSent event: read MailItem.SendUsingAccount, find that Account in Namespace.Accounts, and then: Account.CurrentUser, Recipient.Address. Note that calling Account.CurrentUser may end with a security warning if this is specified by an Exchange admin; in this case your only remedy is to use our Outlook Security Manager (see https://www.add-in-express.com/outlook-security/index.php).

  • Suman Das says:

    Thanks Andrei,
    Your suggestion worked. With PropertyAccessor I can able to set and get those custom properties. I have another question to ask. The Plug-In I am building is deals with only mailitem. I have defined context menu in Ribbon.xml – contextMenu idMso=”ContextMenuMailItem”. Menu shows on right clicking MailItem. But when I goes to DeletedItems folder, there all contents are mixed. Even I right click on ContactItems it show the Context Menu. How to stop it ?

    Thanks
    Suman

  • Andrei Smolin (Add-in Express Team) says:

    Hello Suman,

    You should handle the getVisible callback of the Ribbon button that you added onto the context menu. With Add-in Express, you handle the PropertyChanging event of the Ribbon button component and check if e.PropertyType is ADXRibbonControlPropertyType.Visible. In this case, you retrieve the context and if it is of the Outlook.Selection type, you check if it contains a MailItem or not. Finally, you return true/false to show/hide the button; in Add-in Express, you set e.Value = true/false (again, you do this in the PropertyChanging event of the Ribbon button shown on the context menu).

  • Suman Das says:

    Thanks Andrei for your valuable comment. In my add-in user drag and drop emails to a custom folder, I subscribe to that folder’s items-add event and process mailitems in separate thread. Even if multiple emails dropped, I received each event separately. For few emails it is working fine, but if I try with 300 emails or more, Outlook sometime not responding and get hanged. I am worried about the approach I took. Can you please suggest.

    Thanks
    Suman

  • Andrei Smolin (Add-in Express Team) says:

    Hello Suman,

    The description of the ItemAdd event at https://msdn.microsoft.com/en-us/vba/outlook-vba/articles/items-itemadd-event-outlook contains these words:
    “This event does not run when a large number of items are added to the folder at once.” At https://www.add-in-express.com/creating-addins-blog/outlook-newmail-custom-solution/ we describe a way to deal with another event producing the very same issue; the way is to scan the folder looking for emails that aren’t marked yet.

    Also, accessing the Outlook object model (any Office model) on a background thread leads to problems; you should always access the object model on the main thread.

  • Shana says:

    Andrei, is it possible to send rights protected mail via outlook using selenium c#

  • Andrei Smolin (Add-in Express Team) says:

    Hello Shana,

    I don’t know an answer to this question as I know nothing about Selenium C#.

  • Shana says:

    Andrei, Could you help me with my previous question using Visual Studio? I haven’t yet been able to figure out how to send confidential emails using the Outlook -> New Email -> Options -> Permissions and selecting the confidential option.

    It would be of great help if you can help me with the code snippet.

  • Andrei Smolin (Add-in Express Team) says:

    Hello Shana,

    The Outlook object model doesn’t let you create such an email.

    I’d look in “clicking” the involved Ribbon controls programmatically, via CommandBars.ExecuteMso(strIdMsoOfTheControlToClick). You can find the Ids of the controls involved in the first paragraph of section Referring to built-in Office ribbon controls; see https://www.add-in-express.com/docs/net-ribbon-components.php#referring-built-in-ribbon-controls.

    Another way to find these IDs is demonstrated at https://www.add-in-express.com/creating-addins-blog/customizing-builtin-office-ribbon-groups/.

    Note that there’s no way to invoke an item in a gallery or drop down. If you need to do this or if you need to “click” a control shown outside of the Ribbon UI, your only option is to use UI Automation or/and Windows API.

    Another direction to research would be to get a Word.Document object (via Inspector.WordEditor) representing your email and check if the Office.SignatureSet object (see https://docs.microsoft.com/en-us/office/vba/api/office.signatureset; you obtain it via Document.Signatures) provides all the features you are looking for. Actually, this direction looks more promising.

  • Shana says:

    Thanks Adrei. I will try and get back

  • Rahul Shravage says:

    Hello folks,

    Is there a way to track the response to olPromptForSave of the OlInspector event? I need to show a front end message dialog if the user cancel outs of the olPromptForSave.

    Regards
    Rahul

  • Andrei Smolin (Add-in Express Team) says:

    Hello Rahul,

    The Outlook object model doesn’t provide a way to achieve this.

  • YT says:

    Hi, the C# code does not kick in when the mail is saved as draft and sent from outlook main window. When the mail is popped out, it works but with embedded, it does not. Is the event different for the send? I really appreciate if there is solution to it….. Thank you,

  • Andrei Smolin (Add-in Express Team) says:

    ItemSend is an application-level event. It doesn’t depend on the way you send your email. Check the way you connect to that event. In Add-in Express, the ItemSend event is mapped to the ADXOutlookAppEvents.ItemSend event – this one works as expected.

Post a comment

Have any questions? Ask us right now!