Ir para o conteúdo principal

Como salvar todos os anexos de vários e-mails em uma pasta no Outlook?

É fácil salvar todos os anexos de um e-mail com o recurso embutido Salvar todos os anexos no Outlook. No entanto, se você deseja salvar todos os anexos de vários e-mails de uma vez, nenhum recurso direto pode ajudar. Você precisa aplicar repetidamente o recurso Salvar todos os anexos em cada e-mail até que todos os anexos sejam salvos desses e-mails. Isso é demorado. Neste artigo, apresentamos dois métodos para você salvar em massa todos os anexos de vários e-mails em uma pasta específica facilmente no Outlook.

Salve todos os anexos de vários e-mails em uma pasta com o código VBA
Vários cliques para salvar todos os anexos de vários e-mails em uma pasta com uma ferramenta incrível


Salve todos os anexos de vários e-mails em uma pasta com o código VBA

Esta seção demonstra um código VBA em um guia passo a passo para ajudá-lo a salvar rapidamente todos os anexos de vários emails em uma pasta específica de uma vez. Faça o seguinte.

1. Em primeiro lugar, você precisa criar uma pasta para salvar os anexos em seu computador.

Entre no Documentos pasta e crie uma pasta chamada “Anexos”. Veja a imagem:

2. Selecione os e-mails cujos anexos você salvará e pressione outro + F11 chaves para abrir o Microsoft Visual Basic para Aplicações janela.

3. Clique inserção > Módulo para abrir o Módulo janela e, em seguida, copie um dos seguintes códigos VBA para a janela.

Código VBA 1: salvar em massa anexos de vários e-mails (salvar diretamente anexos com o mesmo nome)

Tips: Este código salvará exatamente os mesmos anexos de nome adicionando os dígitos 1, 2, 3 ... após os nomes dos arquivos.

Dim GCount As Integer
Dim GFilepath As String
Public Sub SaveAttachments()
'Update 20200821
Dim xMailItem As Outlook.MailItem
Dim xAttachments As Outlook.Attachments
Dim xSelection As Outlook.Selection
Dim i As Long
Dim xAttCount As Long
Dim xFilePath As String, xFolderPath As String, xSaveFiles As String
On Error Resume Next
xFolderPath = CreateObject("WScript.Shell").SpecialFolders(16)
Set xSelection = Outlook.Application.ActiveExplorer.Selection
xFolderPath = xFolderPath & "\Attachments\"
If VBA.Dir(xFolderPath, vbDirectory) = vbNullString Then
    VBA.MkDir xFolderPath
End If
GFilepath = ""
For Each xMailItem In xSelection
    Set xAttachments = xMailItem.Attachments
    xAttCount = xAttachments.Count
    xSaveFiles = ""
    If xAttCount > 0 Then
        For i = xAttCount To 1 Step -1
            GCount = 0
            xFilePath = xFolderPath & xAttachments.Item(i).FileName
            GFilepath = xFilePath
            xFilePath = FileRename(xFilePath)
            If IsEmbeddedAttachment(xAttachments.Item(i)) = False Then
                xAttachments.Item(i).SaveAsFile xFilePath
                If xMailItem.BodyFormat <> olFormatHTML Then
                    xSaveFiles = xSaveFiles & vbCrLf & "<Error! Hyperlink reference not valid.>"
                Else
                    xSaveFiles = xSaveFiles & "<br>" & "<a href='file://" & xFilePath & "'>" & xFilePath & "</a>"
                End If
            End If
        Next i
    End If
Next
Set xAttachments = Nothing
Set xMailItem = Nothing
Set xSelection = Nothing
End Sub

Function FileRename(FilePath As String) As String
Dim xPath As String
Dim xFso As FileSystemObject
On Error Resume Next
Set xFso = CreateObject("Scripting.FileSystemObject")
xPath = FilePath
FileRename = xPath
If xFso.FileExists(xPath) Then
    GCount = GCount + 1
    xPath = xFso.GetParentFolderName(GFilepath) & "\" & xFso.GetBaseName(GFilepath) & " " & GCount & "." + xFso.GetExtensionName(GFilepath)
    FileRename = FileRename(xPath)
End If
xFso = Nothing
End Function

Function IsEmbeddedAttachment(Attach As Attachment)
Dim xItem As MailItem
Dim xCid As String
Dim xID As String
Dim xHtml As String
On Error Resume Next
IsEmbeddedAttachment = False
Set xItem = Attach.Parent
If xItem.BodyFormat <> olFormatHTML Then Exit Function
xCid = ""
xCid = Attach.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001F")
If xCid <> "" Then
    xHtml = xItem.HTMLBody
    xID = "cid:" & xCid
    If InStr(xHtml, xID) > 0 Then
        IsEmbeddedAttachment = True
    End If
End If
End Function
Código VBA 2: salvar em massa anexos de vários e-mails (verifique se há duplicatas)
Public Sub SaveAttachments()
'Update 20200821
Dim xMailItem As Outlook.MailItem
Dim xAttachments As Outlook.Attachments
Dim xSelection As Outlook.Selection
Dim i As Long
Dim xAttCount As Long
Dim xFilePath As String, xFolderPath As String, xSaveFiles As String
Dim xYesNo As Integer
Dim xFlag As Boolean
On Error Resume Next
xFolderPath = CreateObject("WScript.Shell").SpecialFolders(16)
Set xSelection = Outlook.Application.ActiveExplorer.Selection
xFolderPath = xFolderPath & "\Attachments\"
If VBA.Dir(xFolderPath, vbDirectory) = vbNullString Then
    VBA.MkDir xFolderPath
End If
For Each xMailItem In xSelection
    Set xAttachments = xMailItem.Attachments
    xAttCount = xAttachments.Count
    xSaveFiles = ""
    If xAttCount > 0 Then
        For i = xAttCount To 1 Step -1
            xFilePath = xFolderPath & xAttachments.Item(i).FileName
            xFlag = True
            If VBA.Dir(xFilePath, 16) <> Empty Then
                xYesNo = MsgBox("The file is exists, do you want to replace it", vbYesNo + vbInformation, "Kutools for Outlook")
                If xYesNo = vbNo Then xFlag = False
            End If
            If xFlag = True Then
                xAttachments.Item(i).SaveAsFile xFilePath
                If xMailItem.BodyFormat <> olFormatHTML Then
                    xSaveFiles = xSaveFiles & vbCrLf & "<Error! Hyperlink reference not valid.>"
                Else
                    xSaveFiles = xSaveFiles & "<br>" & "<a href='file://" & xFilePath & "'>" & xFilePath & "</a>"
                End If
            End If
        Next i
    End If
Next
Set xAttachments = Nothing
Set xMailItem = Nothing
Set xSelection = Nothing
End Sub

Notas:

1) Se você deseja salvar todos os anexos com o mesmo nome em uma pasta, aplique o acima Código VBA 1. Antes de executar este código, clique em Ferramentas > Referências, e depois verifique o Tempo de execução de scripts da Microsoft caixa no Referências - Projeto caixa de diálogo;

doc salvar anexos 07

2) Se você deseja verificar se há nomes de anexo duplicados, aplique o código VBA 2. Depois de executar o código, uma caixa de diálogo aparecerá para lembrá-lo se deseja substituir os anexos duplicados, escolha Sim or Não com base em suas necessidades.

5. aperte o F5 chave para executar o código.

Em seguida, todos os anexos em e-mails selecionados são salvos na pasta que você criou na etapa 1. 

Observações: Pode haver um Microsoft Outlook caixa de prompt aparecendo, por favor, clique no Permitir botão para ir em frente.


Salve todos os anexos de vários e-mails em uma pasta com uma ferramenta incrível

Se você é um novato no VBA, aqui recomendo fortemente o Salvar todos os anexos utilidade de Kutools para Outook para voce. Com este utilitário, você pode salvar rapidamente todos os anexos de vários e-mails de uma vez com vários cliques apenas no Outlook.
Antes de aplicar o recurso, por favor baixe e instale o Kutools para Outlook primeiro.

1. Selecione os e-mails contendo os anexos que você deseja salvar.

Dicas: Você pode selecionar vários e-mails não adjacentes segurando o Ctrl tecla e selecione-os um por um;
Ou selecione vários e-mails adjacentes segurando o Shift e selecione o primeiro e-mail e o último.

2. Clique Kutools >Ferramentas de AnexoSalve Todos. Veja a imagem:

3. No Salvar configurações diálogo, clique no para selecionar uma pasta para salvar os anexos e, em seguida, clique no OK botão.

3. Clique OK duas vezes na próxima janela pop-up, então todos os anexos dos e-mails selecionados são salvos na pasta especificada de uma vez.

Observações:

  • 1. Se você deseja salvar anexos em pastas diferentes com base em e-mails, verifique o Crie subpastas no seguinte estilo e escolha um estilo de pasta no menu suspenso.
  • 2. Além de salvar todos os anexos, você pode salvar anexos por condições específicas. Por exemplo, se você deseja salvar apenas os anexos do arquivo pdf cujo nome do arquivo contém a palavra "Fatura", clique no botão opções avançadas para expandir as condições e, em seguida, configurar conforme mostrado a seguir.
  • 3. Se você deseja salvar automaticamente os anexos quando o e-mail chegar, o Salvar anexos automaticamente recurso pode ajudar.
  • 4. Para desanexar os anexos diretamente dos e-mails selecionados, o Desanexar todos os anexos característica de Kutools for Outlook pode te fazer um favor.

  Se você quiser ter um teste gratuito (60 dias) deste utilitário, por favor clique para fazer o downloade, em seguida, aplique a operação de acordo com as etapas acima.


Artigos relacionados

Insira anexos no corpo da mensagem de e-mail no Outlook
Normalmente, os anexos são exibidos no campo Anexado em um e-mail de redação. Aqui, este tutorial fornece métodos para ajudá-lo a inserir facilmente anexos no corpo do e-mail no Outlook.

Baixar / salvar automaticamente anexos do Outlook para uma determinada pasta
De um modo geral, você pode salvar todos os anexos de um e-mail clicando em Anexos> Salvar todos os anexos no Outlook. Mas, se precisar salvar todos os anexos de todos os emails recebidos e recebidos, algum ideal? Este artigo apresentará duas soluções para baixar automaticamente anexos do Outlook para uma determinada pasta.

Imprima todos os anexos em um / vários e-mails no Outlook
Como você sabe, ele só imprimirá o conteúdo do e-mail, como cabeçalho e corpo, quando você clicar em Arquivo> Imprimir no Microsoft Outlook, mas não imprimirá os anexos. Aqui vamos mostrar como imprimir todos os anexos em um e-mail selecionado com facilidade no Microsoft Outlook.

Pesquisar palavras em anexo (conteúdo) no Outlook
Quando digitamos uma palavra-chave na caixa de Pesquisa Instantânea do Outlook, ele vai pesquisar a palavra-chave nos assuntos, corpos, anexos, etc. dos emails. Mas agora só preciso pesquisar a palavra-chave no conteúdo dos anexos apenas no Outlook, alguma ideia? Este artigo mostra as etapas detalhadas para pesquisar palavras no conteúdo de anexos no Outlook com facilidade.

Mantenha os anexos ao responder no Outlook
Quando encaminhamos uma mensagem de e-mail no Microsoft Outlook, os anexos originais dessa mensagem de e-mail permanecem na mensagem encaminhada. No entanto, quando respondemos a uma mensagem de e-mail, os anexos originais não serão anexados na nova mensagem de resposta. Aqui, vamos apresentar alguns truques sobre como manter os anexos originais ao responder no Microsoft Outlook.


Melhores ferramentas de produtividade de escritório

Kutools for Outlook - Mais de 100 recursos poderosos para turbinar seu Outlook

🤖 Assistente de correio AI: E-mails profissionais instantâneos com magia de IA – um clique para respostas geniais, tom perfeito, domínio multilíngue. Transforme o envio de e-mails sem esforço! ...

📧 Automação de e-mail: Fora do escritório (disponível para POP e IMAP)  /  Agendar envio de e-mails  /  CC/BCC automático por regras ao enviar e-mail  /  Encaminhamento automático (regras avançadas)   /  Adicionar saudação automaticamente   /  Divida automaticamente e-mails de vários destinatários em mensagens individuais ...

📨 Gestão de E-mail: Lembre-se facilmente de e-mails  /  Bloquear e-mails fraudulentos por assuntos e outros  /  Apagar Emails Duplicados  /  Pesquisa Avançada  /  Consolidar pastas ...

📁 Anexos PróSalvar em lote  /  Desanexar lote  /  Comprimir em Lote  /  Salvamento automático   /  Desanexação Automática  /  Compressão automática ...

???? Interface Mágica: 😊Mais emojis bonitos e legais   /  Aumente a produtividade do seu Outlook com visualizações com guias  /  Minimize o Outlook em vez de fechar ...

???? Maravilhas com um clique: Responder a todos com anexos recebidos  /   E-mails antiphishing  /  🕘Mostrar fuso horário do remetente ...

👩🏼‍🤝‍👩🏻 Contatos e calendário: Adicionar contatos em lote de e-mails selecionados  /  Dividir um grupo de contatos em grupos individuais  /  Remover lembretes de aniversário ...

Sobre Características 100 Aguarde sua exploração! Clique aqui para descobrir mais.

 

 

Comments (81)
Rated 3.5 out of 5 · 3 ratings
This comment was minimized by the moderator on the site
Thank you for sharing the code. Unfortunately, I tried both with failure. This is what I got - The macros in this project are disabled. Please refer to the online help or documentation of the host application to determine how to enable macros. Thank you.
This comment was minimized by the moderator on the site
Hi,
Please follow the instructions in the screenshot below to check if macros are enabled in the macro settings in your Outlook. After enabling both options, re-run the VBA code.

https://www.extendoffice.com/images/stories/comments/comment-picture-zxm/macro-enabled.png
This comment was minimized by the moderator on the site
Thank you so much.
Rated 5 out of 5
This comment was minimized by the moderator on the site
Thank you for sharing VBA code. This work like magic and is going to save it lots of time!
This comment was minimized by the moderator on the site
Hello friends!

Thanks for sharing this VBA code.

Is there any way to change the location of the save folder?

I share the pc with some colleagues and in this case I need the files to be saved in a password protected folder which is not located in the documents folder.

How can I make this change?

Thank you in advance
This comment was minimized by the moderator on the site
Hi Fabiana,
Change the line 14
xFolderPath = xFolderPath & "\Attachments\"

to
xFolderPath = "C:\Users\Win10x64Test\Desktop\save attachments\1\"

Here "C:\Users\Win10x64Test\Desktop\save attachments\1\" is the folder path in my case.
Don't forget to end the folder path with a slash "\"
This comment was minimized by the moderator on the site
Hello friends!

Thank you for sharing that VBA code.

Is there any way to change the location of the save folder?

I share the pc with some colleagues and in this case I need the files to be saved in a password protected folder which is not located in the documents folder.

How can I make this change?

Thank you in advance
This comment was minimized by the moderator on the site
If you are trying to run the Code that renames duplicate files and keep getting a "User Type Not Defined" error message here is the code fixed. Instead of the "Dim xFso As FileSystemObject" on line 47 it should be "Dim xFso As Variant"
Also added a Message Box to appear at the end of data transfer.

Dim GCount As Integer
Dim GFilepath As String
Public Sub SaveAttachments()
'Update 20200821
Dim xMailItem As Outlook.MailItem
Dim xAttachments As Outlook.Attachments
Dim xSelection As Outlook.Selection
Dim i As Long
Dim xAttCount As Long
Dim xFilePath As String, xFolderPath As String, xSaveFiles As String
On Error Resume Next
xFolderPath = CreateObject("WScript.Shell").SpecialFolders(16)
Set xSelection = Outlook.Application.ActiveExplorer.Selection
xFolderPath = xFolderPath & "\Attachments\"
If VBA.Dir(xFolderPath, vbDirectory) = vbNullString Then
VBA.MkDir xFolderPath
End If
GFilepath = ""
For Each xMailItem In xSelection
Set xAttachments = xMailItem.Attachments
xAttCount = xAttachments.Count
xSaveFiles = ""
If xAttCount > 0 Then
For i = xAttCount To 1 Step -1
GCount = 0
xFilePath = xFolderPath & xAttachments.Item(i).FileName
GFilepath = xFilePath
xFilePath = FileRename(xFilePath)
If IsEmbeddedAttachment(xAttachments.Item(i)) = False Then
xAttachments.Item(i).SaveAsFile xFilePath
If xMailItem.BodyFormat <> olFormatHTML Then
xSaveFiles = xSaveFiles & vbCrLf & "<Error! Hyperlink reference not valid.>"
Else
xSaveFiles = xSaveFiles & "<br>" & "<a href='file://" & xFilePath & "'>" & xFilePath & "</a>"
End If
End If
Next i
End If
Next
Set xAttachments = Nothing
Set xMailItem = Nothing
Set xSelection = Nothing
MsgBoX prompt:="File Transfer Complete", Title:="Sweatyjalapenos tha Goat"
End Sub

Function FileRename(FilePath As String) As String
Dim xPath As String
Dim xFso As Variant
On Error Resume Next
Set xFso = CreateObject("Scripting.FileSystemObject")
xPath = FilePath
FileRename = xPath
If xFso.FileExists(xPath) Then
GCount = GCount + 1
xPath = xFso.GetParentFolderName(GFilepath) & "\" & xFso.GetBaseName(GFilepath) & " " & GCount & "." + xFso.GetExtensionName(GFilepath)
FileRename = FileRename(xPath)
End If
xFso = Nothing
End Function

Function IsEmbeddedAttachment(Attach As Attachment)
Dim xItem As MailItem
Dim xCid As String
Dim xID As String
Dim xHtml As String
On Error Resume Next
IsEmbeddedAttachment = False
Set xItem = Attach.Parent
If xItem.BodyFormat <> olFormatHTML Then Exit Function
xCid = ""
xCid = Attach.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001F")
If xCid <> "" Then
xHtml = xItem.HTMLBody
xID = "cid:" & xCid
If InStr(xHtml, xID) > 0 Then
IsEmbeddedAttachment = True

End If
End If
End Function
This comment was minimized by the moderator on the site
Very nice script as of 2022-10-19 works great, for me doesn't seem to change original message by adding text. The only thing I changed is I added message received date time to each file name with the following format so it would nicely sort by date time in Windows folder: "yyyy-mm-dd HH-mm-ss ".

Code:

Dim GCount As Integer
Dim GFilepath As String
Public Sub SaveAttachments()
'Update 20200821
Dim xMailItem As Outlook.MailItem
Dim xAttachments As Outlook.Attachments
Dim xSelection As Outlook.Selection
Dim i As Long
Dim xAttCount As Long
Dim xFilePath As String, xFolderPath As String, xSaveFiles As String, xDateFormat As String
On Error Resume Next
xFolderPath = CreateObject("WScript.Shell").SpecialFolders(16)
Set xSelection = Outlook.Application.ActiveExplorer.Selection
xFolderPath = xFolderPath & "\Attachments\"
If VBA.Dir(xFolderPath, vbDirectory) = vbNullString Then
VBA.MkDir xFolderPath
End If
GFilepath = ""
For Each xMailItem In xSelection
Set xAttachments = xMailItem.Attachments
xAttCount = xAttachments.Count
xSaveFiles = ""
If xAttCount > 0 Then
For i = xAttCount To 1 Step -1
GCount = 0
xDateFormat = Format(xMailItem.ReceivedTime, "yyyy-mm-dd HH-mm-ss ")
xFilePath = xFolderPath & xDateFormat & xAttachments.Item(i).FileName
GFilepath = xFilePath
xFilePath = FileRename(xFilePath)
If IsEmbeddedAttachment(xAttachments.Item(i)) = False Then
xAttachments.Item(i).SaveAsFile xFilePath
If xMailItem.BodyFormat <> olFormatHTML Then
xSaveFiles = xSaveFiles & vbCrLf & "<Error! Hyperlink reference not valid.>"
Else
xSaveFiles = xSaveFiles & "<br>" & "<a href='file://" & xFilePath & "'>" & xFilePath & "</a>"
End If
End If
Next i
End If
Next
Set xAttachments = Nothing
Set xMailItem = Nothing
Set xSelection = Nothing
End Sub

Function FileRename(FilePath As String) As String
Dim xPath As String
Dim xFso As FileSystemObject
On Error Resume Next
Set xFso = CreateObject("Scripting.FileSystemObject")
xPath = FilePath
FileRename = xPath
If xFso.FileExists(xPath) Then
GCount = GCount + 1
xPath = xFso.GetParentFolderName(GFilepath) & "\" & xFso.GetBaseName(GFilepath) & " " & GCount & "." + xFso.GetExtensionName(GFilepath)
FileRename = FileRename(xPath)
End If
xFso = Nothing
End Function

Function IsEmbeddedAttachment(Attach As Attachment)
Dim xItem As MailItem
Dim xCid As String
Dim xID As String
Dim xHtml As String
On Error Resume Next
IsEmbeddedAttachment = False
Set xItem = Attach.Parent
If xItem.BodyFormat <> olFormatHTML Then Exit Function
xCid = ""
xCid = Attach.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001F")
If xCid <> "" Then
xHtml = xItem.HTMLBody
xID = "cid:" & xCid
If InStr(xHtml, xID) > 0 Then
IsEmbeddedAttachment = True
End If
End If
End Function
This comment was minimized by the moderator on the site
Hi Oigo,
This is a very useful VBA script. Thank you for sharing it.
This comment was minimized by the moderator on the site
Hi crystal,

sorry for not being clear.

I was trying to use the code above mentioned. However, apparently I was doing something wrong. I was thinking that I might need to amend some parts in the code shown. For instance the path where to save the attachments and maybe some other parts. Therefore I was asking if you could share the code highlighting the parts which needs tailoring and how to tailor them.

Many thanks,
BR
This comment was minimized by the moderator on the site
Hi Rokkie,
Did you get any error prompt when the code runs? Or which line in your code is highlighted? I need more details so I can see where you can modify the code.
This comment was minimized by the moderator on the site
Hey crystal,

completeley new to this VBA. Can you share a code to use which shows where I have to amend with an example? As a Rookie it is a bit difficult to figure it out.

I am working via a Ctrix connection. Could this be a blocker for the macro?

Much appreaciate the help.
This comment was minimized by the moderator on the site
Hi Rookie,
Sorry I don't understand what you mean: "Can you share a code to use which shows where I have to amend with an example?"
And the code operates on selected emails in Outlook, Ctrix Connection does not block the macro.
This comment was minimized by the moderator on the site
Hi, I am running this Code 1 to extract .txt files from separate sub-folders of an inbox. It works great out of one sub-folder but not at all out of another sub-folder. I have tried forwarding the relevant email and attachment into other inboxes but no luck. The files are automatically generated and sent to the different sub-folders and only vary by a single letter in their title

Any help much is appreciated
There are no comments posted here yet
Load More
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations