简体   繁体   中英

vba code save attachments of email with specific object in a folder - outlook 365

sry for writing but I'm really exhausted on this topic..

On Outlook 365 (so no roles + script allowed as I'm not full admin on the machine) I need to check when arrives a new mail, if it has some specific words in the subject and then save the attachment in a specific folder (it would be better with the name of the mail subject + datestamp) and then put the mail in the bin.

I tried the next code, but I'm really out of gas


Option Explicit
Private WithEvents inboxItems As Outlook.Items

Private Sub Application_Startup()
  Dim outlookApp As Outlook.Application
  Dim objectNS As Outlook.NameSpace
  
  Set outlookApp = Outlook.Application
  Set objectNS = outlookApp.GetNamespace("MAPI")
  Set inboxItems = objectNS.GetDefaultFolder(olFolderInbox).Items
End Sub
'--------------------- ok till here -----------
Private Sub inboxItems_ItemAdd(ByVal Item As Object)
On Error GoTo ErrorHandler

Dim Msg As Outlook.MailItem
Dim objAttachments As Outlook.Attachments
Set objAttachments = Msg.Attachments

If TypeName(Item) = "MailItem" Then
    If InStr(Msg.Subject, "Magic Red Carpet") Then
        
     objAttachments.SaveAsFile "C:\Users\xx12345\Desktop\vba\" & objAttachments.Msg.Subject&date
    End If
End If


ErrorHandler:
    MsgBox "dho!"

End Sub

You need to use the item object passed as a parameter to the ItemAdd event of the Items class in the code:

Private Sub inboxItems_ItemAdd(ByVal Item As Object)
On Error GoTo ErrorHandler

Dim objAttachments As Outlook.Attachments
Set objAttachments = Item.Attachments

If TypeName(Item) = "MailItem" Then
    If InStr(Item.Subject, "Magic Red Carpet") Then
        
     objAttachments.SaveAsFile "C:\Users\xx12345\Desktop\vba\" & objAttachments.Msg.Subject&date
    End If
End If
End Sub

Note, the Subject string may contain symbols not allowed in file names. So, I'd recommend checking for them before calling the SaveAsFile method.

Also you may consider handling the NewMailEx event of the Application class instead. This event fires once for every received item that is processed by Microsoft Outlook. The item can be one of several different item types, for example, MailItem , MeetingItem , or SharingItem . The NewMailEx event fires when a new message arrives in the Inbox and before client rule processing occurs. You can use the Entry ID returned in the EntryIDCollection array to call the NameSpace.GetItemFromID method and process the item.

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