1

I am trying to use a VBA script to automatically export all incoming emails with a specific subject to text files that I will then parse with a Python script. The code below works for the most part, but it will randomly skip some of the emails come in.

I haven't found any reason as to why this is, and it doesn't skip emails from the same sender each day, it varies.

We have about 20-30 emails coming in during a 30 minute period or so if that matters. I'd love some help with this.

Private Sub Items_ItemAdd(ByVal Item As Object)
Dim strSubject As String
strSubject = Item.Subject
  If TypeOf Item Is Outlook.MailItem And strSubject Like "VVAnalyze Results" Then
    SaveMailAsFile Item
  End If
End Sub

Private Sub SaveMailAsFile(oMail As Outlook.MailItem)
  Dim dtDate As Date
  Dim sName As String
  Dim sFile As String
  Dim sExt As String

  sPath = "C:\Users\ltvstatus\Desktop\Backup Reports\"
  sExt = ".txt"
  sName = oMail.Subject
  ReplaceCharsForFileName sName, "_"
  dtDate = oMail.ReceivedTime
  sName = Format(dtDate, "yyyymmdd", vbUseSystemDayOfWeek, _
    vbUseSystem) & Format(dtDate, "-hhnnss", _
    vbUseSystemDayOfWeek, vbUseSystem) & "-" & sName & sExt

  oMail.SaveAs sPath & sName, olSaveAsTxt
End Sub
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
jhugenroth
  • 25
  • 2
  • 8

1 Answers1

1

Your code looks okay to me so I am not sure if your overwriting your saved emails with new one or your getting to many emails at once while the code is processing one and skipping the other...

I have modified your code to loop in your Inbox and added Function to create new file name if the file already exist...

if you receive 10 email in 1 second, the function will create FileName(1).txt, FileName(2).txt and so on...

I will also advise you to move the emails to subfolder as you SaveAs txt...

Item.Move Subfolder

CODE UPDATED



Option Explicit
Private WithEvents Items As Outlook.Items
Private Sub Application_Startup()
    Dim olNs As Outlook.NameSpace
    Dim Inbox  As Outlook.MAPIFolder

    Set olNs = Application.GetNamespace("MAPI")
    Set Inbox = olNs.GetDefaultFolder(olFolderInbox)
    Set Items = Inbox.Items
End Sub

Private Sub Items_ItemAdd(ByVal Item As Object)
    If TypeOf Item Is Outlook.MailItem Then
        SaveMailAsFile Item ' call sub
    End If
End Sub
Public Sub SaveMailAsFile(ByVal Item As Object)
    Dim olNs As Outlook.NameSpace
    Dim Inbox As Outlook.MAPIFolder
    Dim SubFolder As Outlook.MAPIFolder
    Dim Items As Outlook.Items
    Dim ItemSubject As String
    Dim NewName As String
    Dim RevdDate As Date
    Dim Path As String
    Dim Ext As String
    Dim i As Long

    Set olNs = Application.GetNamespace("MAPI")
    Set Inbox = olNs.GetDefaultFolder(olFolderInbox)
    Set Items = Inbox.Items.Restrict("[Subject] = 'VVAnalyze Results'")

    Path = Environ("USERPROFILE") & "\Desktop\Backup Reports\"
    ItemSubject = Item.Subject
    RevdDate = Item.ReceivedTime
    Ext = "txt"

    For i = Items.Count To 1 Step -1
        Set Item = Items.Item(i)

        DoEvents

        If Item.Class = olMail Then
            Debug.Print Item.Subject ' Immediate Window
            Set SubFolder = Inbox.Folders("Temp") ' <--- Update Fldr Name

            ItemSubject = Format(RevdDate, "YYYYMMDD-HHNNSS") _
                                                    & " - " & _
                                            Item.Subject & Ext

            ItemSubject = FileNameUnique(Path, ItemSubject, Ext)

            Item.SaveAs Path & ItemSubject, olTXT
            Item.Move SubFolder
        End If
    Next

    Set olNs = Nothing
    Set Inbox = Nothing
    Set SubFolder = Nothing
    Set Items = Nothing

End Sub


'// Check if the file exists
Private Function FileExists(FullName As String) As Boolean
Dim fso As Object
    Set fso = CreateObject("Scripting.FileSystemObject")

    If fso.FileExists(FullName) Then
        FileExists = True
    Else
        FileExists = False
    End If

    Exit Function
End Function

'// If the same file name exist then add (1)
Private Function FileNameUnique(Path As String, _
                               FileName As String, _
                               Ext As String) As String
Dim lngF As Long
Dim lngName As Long
    lngF = 1
    lngName = Len(FileName) - (Len(Ext) + 1)
    FileName = Left(FileName, lngName)

    Do While FileExists(Path & FileName & Chr(46) & Ext) = True
        FileName = Left(FileName, lngName) & " (" & lngF & ")"
        lngF = lngF + 1
    Loop

    FileNameUnique = FileName & Chr(46) & Ext

    Exit Function
End Function
Community
  • 1
  • 1
0m3r
  • 12,286
  • 15
  • 35
  • 71
  • Great, thanks! I will try this and see how it works. – jhugenroth Dec 29 '16 at 14:07
  • I did some testing with this today and it seemed to work during tests. I'll see how it runs in production tomorrow when we receive a large amount of emails. – jhugenroth Jan 03 '17 at 14:50
  • It still seems to be skipping some of the emails and duplicating others. Does seem to be working a little better with this though. Any other ideas? – jhugenroth Jan 06 '17 at 14:51
  • The idea will be to move the items to subfolder, will post updated code later – 0m3r Jan 06 '17 at 17:07
  • Are you referring to moving the emails to a subfollder within outlook? Or moving the exported textfiles to a subfolder? If you could post updated code that would be wonderful! – jhugenroth Jan 10 '17 at 15:13
  • Yes It's batter to move the emails to subfolder within outlook. – 0m3r Jan 10 '17 at 16:48
  • I'm having a little trouble figuring this out. I'm extremely new to programming so this is a little tough for me. Would it not work to just set up a rule in outlook to move the desired emails to a subfolder? Or am I missing the point of moving them to a subforlder? – jhugenroth Jan 11 '17 at 18:02
  • I could still use some help with this. I've been beating my head against it and can't figure out how to integrate code that moves items to a sub folder. I appreciate your help so far! – jhugenroth Jan 18 '17 at 15:07
  • @jhugenroth is all the emails coming from one person and is the subject always the some? – 0m3r Jan 18 '17 at 21:38
  • Senders are different but they all start with "AdminService.exe" if that common ground helps. The subjects are all identical. – jhugenroth Jan 18 '17 at 22:31
  • @jhugenroth so the subjects never change, its always the same? `VVAnalyze Results`- I am trying to run test and see why is it skipping... – 0m3r Jan 18 '17 at 22:36
  • @jhugenroth Perfect, Code updated, Tested on 500 Emails - about 48 seconds , no duplicates no skipping- remember to update `Set SubFolder = Inbox.Folders("Temp")` change Temp to your folder name- – 0m3r Jan 18 '17 at 23:33
  • 1
    That seems to work in my tests as well, we will see how it works in production in the morning. Thanks!! – jhugenroth Jan 19 '17 at 15:33
  • So I ran the code in production today, it stopped working after about 4 emails. When I debugged it highlighted the following line: RevdDate = Item.ReceivedTime – jhugenroth Jan 20 '17 at 14:34
  • I restarted outlook and it worked that time. Not sure why it failed at first. – jhugenroth Jan 20 '17 at 15:15