1

Email is received once a day from abc@xyz.com with subject line being "emails" with attachments that are emails (up to 20 attachments at 15kb each).

I am trying to move those attachments to a sub folder named "Extra" within my Outlook inbox.

I'm having trouble modifying my old code. I'm thinking its coming from here. Const attPath As String = "Mailbox/Extra".

Private WithEvents Items As Outlook.Items

Private Sub Application_Startup()
    Dim olApp As Outlook.Application
    Dim objNS As Outlook.NameSpace
    Set olApp = Outlook.Application
    Set objNS = olApp.GetNamespace("MAPI")
    Set Items = objNS.GetDefaultFolder(olFolderInbox).Items
End Sub

Private Sub Items_ItemAdd(ByVal item As Object)

    On Error GoTo ErrorHandler

    'Only act if it's a MailItem
    Dim Msg As Outlook.MailItem
    If TypeName(item) = "MailItem" Then
        Set Msg = item

        'From specified user with specified subject
        If (Msg.SenderName = "teresa") And _
          (Msg.Subject = "emails") And _
          (Msg.Attachments.Count >= 1) Then

            'Set folder to save in.
            Dim olDestFldr As Outlook.MAPIFolder
            Dim myAttachments As Outlook.Attachments
            Dim Att As String

            'location to save in. 
            Const attPath As String = "Mailbox/Extra"

            ' save attachment
            Set myAttachments = item.Attachments
            Att = myAttachments.item(1).DisplayName
            myAttachments.item(1).SaveAsFile attPath & Att

            ' mark as read
            Msg.UnRead = False
        End If
    End If

ProgramExit:
    Exit Sub

ErrorHandler:
    MsgBox Err.Number & " - " & Err.Description
    Resume ProgramExit

End Sub

enter image description here

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 1
    So your not the one sending the email , your receiving it? Can you share the current code you have? – 0m3r Jan 05 '17 at 17:10
  • Look at this examples. http://stackoverflow.com/a/29910853/4539709 – 0m3r Jan 05 '17 at 17:12
  • I am the one receiving the email. The code in the link above looks a lot cleaner looking than mine but it only moves the email from one folder to another which i can already do but its the extracting of the attachments in the email which i have an issue with. – Marc-Andre Charron Jan 05 '17 at 18:00
  • little confused now, where do want to move the attachment to? local folder? or to new email? also you may wana post your current code before your question gets closed – 0m3r Jan 05 '17 at 18:55
  • The email which i receive once a day has attachments but those are emails. i am just looking to extract the emails and instead of clicking on all of them and dragging them into a different folder in my inbox, for them to transfer automatically. im not very VBA savy so i dont even know if attachment.movetofolder can be used. – Marc-Andre Charron Jan 05 '17 at 19:15
  • I added a picture as an example under the code of what im trying to do – Marc-Andre Charron Jan 05 '17 at 19:22
  • Once you save the attachments to a hard drive, bring them back to Outlook as described here https://msdn.microsoft.com/en-us/library/office/bb176433(v=office.12).aspx – niton Jan 05 '17 at 20:40
  • The code and question was updated. Im not looking to save it on my hard drive. Just looking to move them from one folder to another – Marc-Andre Charron Jan 06 '17 at 20:59
  • SaveAsFile saves to a Windows folder. https://msdn.microsoft.com/en-us/library/office/ff869359.aspx Once you save there, you bring the mailitem back to Outlook with https://msdn.microsoft.com/en-us/library/office/bb176433(v=office.12).aspx – niton Jan 06 '17 at 23:35

2 Answers2

2

It appears you can't move attachments to another folder in Outlook without saving them locally beforehand.

The following code should hopefully work for you...

In ThisOutlookSession:

Private WithEvents InboxItems As Outlook.Items

Private Sub Application_Startup()
    On Error Resume Next
    Set InboxItems = Application.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox).Items
End Sub

Private Sub InboxItems_ItemAdd(ByVal Item As Object)
    On Error Resume Next
    If TypeName(Item) = "MailItem" Then Call MoveAttachments(Item)
End Sub

In a module:

Function MoveAttachments(ByVal Item As Object)
    
    Const AttachmentFolder As String = "Extra"
    
    Dim ThisNameSpace As Outlook.NameSpace: Set ThisNameSpace = Application.GetNamespace("MAPI")
    Dim Inbox As Outlook.MAPIFolder: Set Inbox = ThisNameSpace.GetDefaultFolder(olFolderInbox)
    
    On Error Resume Next
        Dim AttFolder As Outlook.Folder: Set AttFolder = Inbox.Folders(AttachmentFolder)
        If AttFolder Is Nothing Then Set AttFolder = Inbox.Parent.Folders(AttachmentFolder)
        If AttFolder Is Nothing Then Exit Function
    On Error GoTo ExitSub
    
    With Item   'From specified user with specified subject
        If .SenderName = "teresa" And .Subject = "emails" And .Attachments.Count >= 1 Then
            Call MoveAttachedMessages(Item, AttFolder, False)
        End If
    End With
        
ExitSub:
End Function

Function MoveAttachedMessages(ByVal Item As Object, _
    AttachmentFolder As Outlook.Folder, _
    Optional DeleteMoved As Boolean)

    If IsMissing(DeleteMoved) Then DeleteMoved = False

    Dim TempPath As String: TempPath = Environ("temp") & "\OLAtt-" & Format(Now(), "yyyy-mm-dd") & "\"
    If Dir(TempPath, vbDirectory) = "" Then MkDir TempPath

    Dim ThisNameSpace As Outlook.NameSpace: Set ThisNameSpace = Application.GetNamespace("MAPI")
    Dim AttItems As Outlook.Attachments, AttItem As Outlook.Attachment
    Dim msgItem As Outlook.MailItem

    ' Save attachments
    On Error Resume Next

    Set AttItems = Item.Attachments
    For Each AttItem In AttItems
        If LCase(Right(AttItem.FileName, 4)) = ".msg" Then
            AttItem.SaveAsFile TempPath & AttItem.FileName
            Set msgItem = ThisNameSpace.OpenSharedItem(TempPath & AttItem.FileName)
            'Set msgItem = Outlook.CreateItemFromTemplate(TempPath & AttItem.FileName)
            If Not msgItem Is Nothing Then
                msgItem.UnRead = True
                msgItem.Save
                msgItem.Move AttachmentFolder
                If msgItem.Saved = True And DeleteMoved = True Then
                    AttItem.Delete
                    Item.Save
                End If
            End If
        End If
    Next AttItem

    If Err.Number = 0 Then Item.UnRead = False ' Mark as Read

    If Dir(TempPath, vbDirectory) <> "" Then
        Kill TempPath & "\" & "*.*"
        RmDir TempPath
    End If
    
End Function

Note: not sure why, but using this code the copied attachments can't be marked as unread. I've left in the code, maybe someone else can identify the issue.

Thanks to Seby for identifying the issue; code has been updated

Tragamor
  • 3,594
  • 3
  • 15
  • 32
  • Thank you. Im having a hard time with Function MoveAttachedMessages(ByVal Item As Object, _ AttachmentFolder As Outlook.Folder, _ Optional DeleteMoved As Boolean) states that it is undefined – Marc-Andre Charron Jan 13 '17 at 23:13
  • Hi - without a bit more information, I'm not sure I can help. The code generally works for me (although I take out the logic [If .SenderName = "teresa" And .Subject = "emails" And .Attachments.Count >= 1 Then] to test it). Perhaps there is something wrong with this? – Tragamor Jan 15 '17 at 23:18
  • Bumping an old thread. @Tragamor, the setting of unread property fails as the msgItem has been already saved and moved. If you move [msgItem.UnRead = True] to before [msgItem.Save], it works well. – Seby Jul 22 '20 at 03:23
0

This is my code with my Folders

-Inbox
--Folder1
---SubFolder1
---SubFolder2
--Folder2

.. Serch email with Attachement in Folder1 and move in specific SubFolder

Sub MoveAttachmentToFolder(Item As Outlook.MailItem)

'Dichiarazione
Dim OutApp As Outlook.Application
Dim Namespace As Outlook.Namespace
Dim Mfolder As Outlook.MAPIFolder
Dim Folder As Outlook.MAPIFolder
Dim SubFolder As Outlook.MAPIFolder
Dim UserFolder As Outlook.MAPIFolder
Dim UserUserFolder As Outlook.MAPIFolder
Dim olkAtt As Outlook.Attachment

Set OutApp = New Outlook.Application
Set Namespace = OutApp.GetNamespace("MAPI")
Set Root = Namespace.Folders("root")
Set Folder = Root.Folders("Inbox")
Set SubFolder = Folder.Folders("Folder1")
Set UserFolder = SubFolder.Folders("SubFolder1")
Debug.Print UserFolder.Name

    'Check each attachment
    For Each olkAtt In Item.Attachments
        'If the attachment's file name with 202627
         If InStr(LCase(olkAtt), "202627") > 0 Then
            'Move the message to SubFolder "DL IT CG SKY-DE PRJ"
            Item.Move SubFolder.Folders("SubFolder1")
            'No need to check any of this message's remaining attachments
            Exit For
        End If
    Next
    Set olkAtt = Nothing
End Sub
  • The .msg attachments are to be saved in Outlook, not the item. "Move attachments that are emails to a subfolder in Outlook" – niton Nov 16 '18 at 17:17