简体   繁体   中英

Save email attachment based on email subject

Ever day at 12 am there is an automatic email with an excel attachment from a vendor service with a specific subject. I am using rules and code to attempt to save the attachment and insert the information into a database I have created upon being received in the inbox.

I have tried code that I have found online however I don't know if doesn't work because of some network/ security setting my company has or if its he code it self.

Rule:

在此处输入图片说明

CODE:

Public Sub CribMaster2Database(itm As Outlook.MailItem)
Dim objAtt As Outlook.Attachment
Dim saveFolder As String

saveFolder = "c:\temp\"
    If olItem.Subject = "Test" Then
        For Each objAtt In itm.Attachments
            objAtt.SaveAsFile saveFolder & "\" & objAtt.DisplayName
            Set objAtt = Nothing
        Next
    End If

End Sub

Add code to the ThisOutlookSession to watch your folder for arrivals.
CribMaster_ItemAdd fires whenever something arrives in your watched folder.

At the very top of the module:

Dim WithEvents CribMaster As Items

Const SAVE_PATH As String = "c:\temp\"

Private Sub Application_Startup()

    Dim ns As Outlook.NameSpace
    Set ns = GetNamespace("MAPI")

    'Change `holi4683` to the name of your account
    '(should be visible just above your inbox).
    Set CribMaster = ns.Folders.Item("holi4683") _
            .Folders.Item("Inbox").Items

End Sub

Sub CribMaster_ItemAdd(ByVal Item As Object)
    Dim olAtt As Attachment
    Dim i As Integer

    With Item
        For i = 1 To .Attachments.Count
            Set olAtt = .Attachments(i)
            olAtt.SaveAsFile SAVE_PATH & olAtt.DisplayName
            .UnRead = False
            DoEvents
        Next i
    End With
    Set olAtt = Nothing

End Sub  

I'd usually use a rule to move the emails to a subfolder and watch that folder - means I don't have to worry about meeting invites, etc.
To do this you'd change your watched folder like this:

Set CribMaster = ns.Folders.Item("holi4683") _
        .Folders.Item("Inbox") _
        .Folders.Item("SubFolder").Items  

Restart Outlook for the code to work, or manually run the Application_Startup() procedure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM