首页 > 解决方案 > 使用接收时间和发件人姓名保存电子邮件附件

问题描述

问题:从电子邮件中保存多个具有相同文件名的附件会将一个附件保存到文件夹

可能的解决方案:将接收时间和发件人姓名添加到新文件名中。
我有我在互联网上找到的有效的 VBA 代码。似乎有多种方法可以做到这一点,但并非所有方法都适用于我的代码。如果可能,我不想运行规则脚本。

我在 Outlook 365 中使用下面的 VBA 代码。它保存所选电子邮件的电子邮件附件。

该宏不会拾取具有相同名称的附件。例如,我将有多个名为“image.pdf”的附件,但它只保存一个具有该名称和文件类型的附件。我想我可以将收到的日期和时间以及发件人的姓名添加到文件名中,以使文件名唯一。当我尝试这个时,我得到了错误。

有两个宏。“Save_Emails_TEST”找到我指定的文件夹,然后调用保存附件的“SaveAttachments”。

请求:如何将收到的日期和时间、发件人姓名、原文件名添加为新文件名?

Public Sub Save_Emails_TEST()
strFolderpath = "H:\Saved Email Attachments\Test\"
SaveAttachments
End Sub

Private Sub SaveAttachments()
Dim objOL As Outlook.Application
Dim objMsg As Object
Dim objAttachments As Outlook.Attachments
Dim objSelection As Outlook.Selection
Dim i As Long
Dim lngCount As Long
Dim strFile As String

    On Error Resume Next
    Set objOL = Application

    Set objSelection = objOL.ActiveExplorer.Selection

    ' Check each selected item for attachments.
    For Each objMsg In objSelection

    Set objAttachments = objMsg.Attachments
    lngCount = objAttachments.count
        
    If lngCount > 0 Then
    
    ' Use a count down loop for removing items
    ' from a collection. Otherwise, the loop counter gets
    ' confused and only every other item is removed.
    
    For i = lngCount To 1 Step -1
    
    ' Get the file name.
    strFile = objAttachments.Item(i).FileName
    
    ' Combine with the path to the folder.
    strFile = strFolderpath & strFile
    
    ' Save the attachment as a file.
    objAttachments.Item(i).SaveAsFile strFile
    
    Next i
    End If
    
    Next
    
ExitSub:

Set objAttachments = Nothing
Set objMsg = Nothing
Set objSelection = Nothing
Set objOL = Nothing
End Sub

标签: vbadatetimeoutlook

解决方案


Dim date_now As Date
Dim dateStamp As String
Dim LRandomNumber As Integer

For i = lngCount To 1 Step -1
    
    ' Get the file name.
    strFile = objAttachments.Item(i).FileName
    
    LRandomNumber = Int((300 - 200 + 1) * Rnd + 200)
    date_obj =  objMsg.ReceivedTime ' Now()
    dateStamp = Format(date_obj, "yyyy-mm-dd-hh-mm-ss")

     ' Combine with the path to the folder.
    strFile = strFolderpath & dateStamp & LRandomNumber & strFile

    ' Save the attachment as a file.
    objAttachments.Item(i).SaveAsFile strFile

Next i

推荐阅读