Spam Filters & .NET 2003 COM Add-Ins
by Steve Goyette

Listing One

' Function that will move e-mail that contains HTML spam to a specific folder
Public Sub FilterHTMLSpam(opMail As MailItem)
   Dim slBody As String
   On Error GoTo ErrorHandler
   If opMail.BodyFormat <> olFormatPlain Then
      Set myOlApp = CreateObject("Outlook.Application")
      Set myNameSpace = myOlApp.GetNamespace("MAPI")
      Set myPersonalFolders = myNameSpace.Folders("Personal Folders")
      Set myDestFolder = myPersonalFolders.Folders("Junk E-mail")
      ' We have an HTML message.  Flatten it
      slBody = stripHTML(opMail.HTMLBody)
      ' If after we strip and trim it's empty then it's VERY likely spam
      If (Len(Trim(slBody)) < 1) Then
         opMail.Move myDestFolder
      Else
         ' See what we've got
         If Contains(slBody, "descramble", "Medication", "Doctor", _
                     "porn", "viagra", "cash", "Prescribes", _
                     "naked", "adult", "%", "sell") Then
            opMail.Move myDestFolder
         End If
      End If
   End If
   Exit Sub
ErrorHandler:
   Msg = "Error # " & Str(Err.Number) & " was generated by " _
         & Err.Source & Chr(13) & Err.Description
   MsgBox Msg, , "Error", Err.HelpFile, Err.HelpContext
End Sub
' Function that will return true if any of the values in the ParamArray
' are contained within the Body text
Private Function Contains(spBody, ParamArray spText() As Variant) As Boolean
  Dim slText As Variant
  tempTest = LCase(spBody)
  For Each slText In spText()
    If InStr(tempTest, LCase(slText)) Then
      Contains = True
      Exit For
    End If
  Next
End Function
' Simple state machine to remove html tags from the input string
Function stripHTML(HTMLString As String)
    result = ""
    pos = 1
    skipping = False
    While (pos < Len(HTMLString))
       enable = False
       current = Mid(HTMLString, pos, 1)
       If (current = "<") Then skipping = True
       If (current = ">") Then enable = True
       If (Not skipping) Then result = result + current
       If (enable) Then skipping = False
       pos = pos + 1
    Wend
    stripHTML = result
End Function

Listing Two

public void OnConnection(object application, 
    Extensibility.ext_ConnectMode connectMode, 
    object addInInst, ref System.Array custom) {
applicationObject = (Outlook.Application)application;
    mAddInInstance = addInInst;
      if(connectMode != Extensibility.ext_ConnectMode.ext_cm_Startup) {
        OnStartupComplete(ref custom);
      }
}

Listing Three

public void OnDisconnection(Extensibility.ext_DisconnectMode 
    disconnectMode, ref System.Array custom) {
if(disconnectMode != Extensibility.ext_DisconnectMode.ext_dm_HostShutdown) {
            OnBeginShutdown(ref custom);
      }
      applicationObject = null;
}

Listing Four

public void OnStartupComplete(ref System.Array custom) {
// Setup a function to be called on the NewMailEx Event
      Outlook.NameSpace outlookNamespace = 
                                    mApplicationObject.GetNamespace("MAPI");
      try {
        utlookNamespace.Application.NewMailEx += 
         new Outlook.ApplicationEvents_11_NewMailExEventHandler(this.NewMail);
      } catch (System.Exception ex) {
System.Windows.Forms.MessageBox.Show(ex.ToString());
      }
}

Listing Five

private void NewMail( String mailId ) {
System.Windows.Forms.MessageBox.Show( "New Mail Received" );
}

Listing Six

private string stripHTML( string source ) {
System.Text.StringBuilder builder = new System.Text.StringBuilder();
      int pos = 0;
      bool skipping = false;
        while ( pos < source.Length ) {
        if ( !skipping ) {
                if ( source[pos] == '<' ) {
                    skipping = true;
                } else {
                    builder.Append( source[pos] );
                }
            } else {
                if ( source[pos] == '>' ) skipping = false;
            }
            pos ++;
      }
return builder.ToString();
}

Listing Seven

// The list of words or phrases that we want to suppress/Mark as spam
private String[] supressList = { "free cable", "prescription", "mortgage" };
private void NewMail( String mailId ) {

   try {
      // First obtain the MAPI namespace from the Outlook Application
      Outlook.NameSpace outlookNamespace = 
                                    applicationObject.GetNamespace("MAPI");
      // Now retrieve the MailItem from the default store.
      Outlook.MailItem item = 
           (Outlook.MailItem)outlookNamespace.GetItemFromID( mailId, null );
      // Figure out where we want to put the junk mail
      Outlook.MAPIFolder personalFolders = 
                                outlookNamespace.Folders["Personal Folders"];
      Outlook.MAPIFolder junkFolder = personalFolders.Folders["Junk E-mail"];
      // See if the message is in a non plain format
      if ( item.BodyFormat != Outlook.OlBodyFormat.olFormatPlain ) {
         // Strip the body text
         string body = stripHTML( item.HTMLBody );
         for ( int i = 0; i < supressList.Length; i ++ ) {
            if ( body.IndexOf( supressList[i].ToLower() ) >= 0 ) {
               // We've got spam...move it to the junk folder
               item.UnRead = true;
               item.Move( junkFolder );
            }
         }

      }
   } catch ( System.Exception e ) {
      System.Windows.Forms.MessageBox.Show( e.ToString() );
   }
}




3


