Programmatically creating auto-format rule in Outlook

Here is the code snippet…

private void AutoFormat()
{
      try
      {
            AutoFormatRule afr;
            TableView tv;
            tv = applicationObject.ActiveExplorer().CurrentView;
            MessageBox.Show(tv.AutoFormatRules.Count.ToString());
            for (int i=1;i<=tv.AutoFormatRules.Count;i++)
            {
                  AutoFormatRule rl =  tv.AutoFormatRules[i];
                  if(rl.Name=="TestAFRule")
                  {
                        tv.AutoFormatRules.Remove(i);
                        MessageBox.Show("Deleted" + rl.Name);
                  }
            }
            afr = tv.AutoFormatRules.Add("TestAFRule");               
            afr.Font.Color = OlColor.olColorRed;                
            afr.Enabled = true;
            tv.Save();
            tv.Apply();
            MessageBox.Show("Done");
      }
      catch(System.Exception ex)
      {
            MessageBox.Show("Err:" + ex.Message);
      }
}

 

Saving mail content when a mail is sent from Outlook

To save the content of a mail item when it is sent, here is the procedure.

Private WithEvents itms As Outlook.Items

Private WithEvents SntFldr As Outlook.Folder

SntFldr = Globals.ThisAddIn.Application.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderSentMail)

itms = SntFldr.Items

Private Sub SaveMail() Handles itms.ItemAdd

‘ DO SOMETHING

End Sub

Before, I handled Application.Send Event and checked whether the Item is MailItem or not and then retrieved the content of that. But, with this, we couldn’t get the Date/Time and sending account information. So, opted for the above procedure.

UPDATE: Here is the updated sample code.

Private WithEvents SntFldr As Outlook.Folder
Private WithEvents itms As Outlook.Items

Private Sub ThisAddIn_Startup(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Startup
    SntFldr = Globals.ThisAddIn.Application.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderSentMail)
    itms = SntFldr.Items
End Sub
Private Sub SaveMailAsMsg() Handles itms.ItemAdd
    If TypeOf itms.Item(itms.Count) Is Outlook.MailItem Then
        Dim olMail As Outlook.MailItem = itms.Item(itms.Count)
        MessageBox.Show("Item Added. " & vbCrLf & "Subject: " & olMail.Subject & vbCrLf & "From: " & olMail.SenderEmailAddress)
    End If
End Sub

Hope this helps!