title: VBA Automatically Saving incoming emails from outlook
body: <p>I am trying to write a small macro program for outlook.
  The Program Should automatically save the text of incoming emails as a text file. </p>
  
  <p>I found large pieces of code and tried to make this work but it still won't work.</p>
  
  <pre><code>Option Explicit
  
  Public Enum olSaveAsTypeEnum
      olSaveAsTxt = 0
      olSaveAsRTF = 1
      olSaveAsMsg = 3
  End Enum
  
  Private WithEvents Items As Outlook.Items
  
  
  Private Const MAIL_PATH As String = "C:\mails\"
  'Private Const MAIL_PATH As String = "C:\Users\dirk\AppData\Local\Microsoft\Outlook\"
  
  
  Private Sub Application_Startup()
      Dim Ns As Outlook.NameSpace
  
      Set Ns = Application.GetNamespace("MAPI")
      Set Items = Ns.GetDefaultFolder(olFolderInbox).Items
  
  End Sub
  
  Private Sub ItemsItemAdd(ByVal Item As Object)
      If TypeOf Item Is Outlook.MailItem Then
      SaveMailAsFile Item, olSaveAsTxt, MAIL_PATH
      End If
  End Sub
  
  Private Sub SaveMailAsFile(oMail As Outlook.MailItem, eType As olSaveAsTypeEnum, sPath As String)
      Dim dtDate As Date
      Dim sName As String
      Dim sFile As String
      Dim sExt As String
  
      Select Case eType
          Case olSaveAsTxt = sExt = ".txt"
          Case olSaveAsMsg = sExt = ".msg"
          Case olSaveAsRTF = sExt = ".rtf"
          Case Else: Exit Sub
      End Select
      sName = oMail.Subject
      RecplaceCharsForFileName sName, "_"
  
      dtDate = oMail.RecievedTime
      sName = Format(dtDate, "yyyymmdd", vbUseSystemDayOfWeek, vbUseSystem) &amp; Format(dtDate, "-hhnnss", vbUseSystemDayOfWeek, vbUseSystem) &amp; "-" &amp; sName &amp; sExt
  
      oMail.SaveAs sPath &amp; sName, eType
  
  
  End Sub
  
  Private Sub RecplaceCharsForFileName(sName As String, sChr As String)
      sName = Replace(sName, "/", sChr)
      sName = Replace(sName, "\", sChr)
      sName = Replace(sName, ";", sChr)
      sName = Replace(sName, "?", sChr)
      sName = Replace(sName, "&lt;", sChr)
      sName = Replace(sName, "&gt;", sChr)
      sName = Replace(sName, "|", sChr)
      sName = Replace(sName, "Chr(34)", sChr)
  
  End Sub
  </code></pre>
  
  <p>I wrote this code not in a separate module but in the already existing <code>ThisOutlookSession</code> module. </p>
  
  <p>Could anyone tell me what am I doing wrong? </p>