Ir para o conteúdo principal

Como imprimir anexos automaticamente quando os emails chegam ao Outlook?

Este tutorial demonstra um método para combinar um script VBA e uma regra do Outlook para ajudá-lo a imprimir automaticamente anexos de determinados emails quando eles chegam ao Outlook.


Imprima anexos automaticamente quando determinados e-mails chegarem

Supondo que você queira imprimir anexos de e-mails recebidos de um determinado remetente automaticamente. Você pode fazer o seguinte para fazê-lo.

Etapa 1: criar um script no Outlook

Em primeiro lugar, você precisa criar um script VBA no Outlook.

1. Inicie o Outlook, pressione o outro + F11 simultaneamente para abrir o Microsoft Visual Basic para Aplicações janela.

2. No Microsoft Visual Basic para Aplicações janela, clique duas vezes em Project1 > Objetos do Microsoft Outlook > Esta sessão do Outlook para abrir o ThisOutlookSession (Código) window e, em seguida, copie o código a seguir para esta janela de código.

Código VBA 1: Imprima anexos automaticamente (todos os tipos de anexos) quando os e-mails chegarem

Sub AttachementAutoPrint(Item As Outlook.MailItem)
'Updated by Extendoffice 20230223
  Dim xFS As FileSystemObject
  Dim xTempFolder As String
  Dim xAtt As Attachment
  Dim xShell As Object
  Dim xFolder As Object, xFolderItem As Object
  Dim xFileName As String
  On Error GoTo xError
  If Item.Attachments.Count = 0 Then Exit Sub
  Set xFS = New FileSystemObject
  xTempFolder = xFS.GetSpecialFolder(TemporaryFolder)
  xTempFolder = xTempFolder & "\ATMP" & Format(Item.ReceivedTime, "yyyymmddhhmmss")
  If Not xFS.FolderExists(xTempFolder) Then
    MkDir (xTempFolder)
  End If
  Set xShell = CreateObject("Shell.Application")
  Set xFolder = xShell.NameSpace(0)
  For Each xAtt In Item.Attachments
    If IsEmbeddedAttachment(xAtt) = False Then
      xFileName = xTempFolder & "\" & xAtt.FileName
      xAtt.SaveAsFile (xFileName)
      Set xFolderItem = xFolder.ParseName(xFileName)
      xFolderItem.InvokeVerbEx ("print")
    End If
  Next xAtt
  Set xFS = Nothing
  Set xFolder = Nothing
  Set xFolderItem = Nothing
  Set xShell = Nothing
xError:
  If Err <> 0 Then
    MsgBox Err.Number & " - " & Err.Description, , "Kutools for Outlook"
    Err.Clear
  End If
Exit Sub
End Sub

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

Observação: Este código suporta a impressão de todos os tipos de anexos recebidos em e-mails. Se você deseja imprimir apenas o tipo de anexo especificado, como arquivos pdf, aplique o seguinte código VBA.

Código VBA 2: Imprima automaticamente o tipo de anexo especificado quando os e-mails chegarem

Sub AttachementAutoPrint(Item As Outlook.MailItem)
'Updated by Extendoffice 20230223
  Dim xFS As FileSystemObject
  Dim xTempFolder As String
  Dim xAtt As Attachment
  Dim xShell As Object
  Dim xFolder As Object, xFolderItem As Object
  Dim xFileType As String, xFileName As String
  On Error GoTo xError
  If Item.Attachments.Count = 0 Then Exit Sub
  Set xFS = New FileSystemObject
  xTempFolder = xFS.GetSpecialFolder(TemporaryFolder)
  xTempFolder = xTempFolder & "\ATMP" & Format(Item.ReceivedTime, "yyyymmddhhmmss")
  If Not xFS.FolderExists(xTempFolder) Then
    MkDir (xTempFolder)
  End If
  Set xShell = CreateObject("Shell.Application")
  Set xFolder = xShell.NameSpace(0)
  For Each xAtt In Item.Attachments
    If IsEmbeddedAttachment(xAtt) = False Then
      xFileName = xAtt.FileName
      xFileType = LCase$(Right$(xFileName, VBA.Len(xFileName) - VBA.InStrRev(xFileName, ".")))
      xFileName = xTempFolder & "\" & xFileName
      Select Case xFileType
        Case "pdf"   'change "pdf" to the file extension you want to print
          xAtt.SaveAsFile (xFileName)
          Set xFolderItem = xFolder.ParseName(xFileName)
          xFolderItem.InvokeVerbEx ("print")
      End Select
    End If
  Next xAtt
  Set xFS = Nothing
  Set xFolder = Nothing
  Set xFolderItem = Nothing
  Set xShell = Nothing
xError:
  If Err <> 0 Then
    MsgBox Err.Number & " - " & Err.Description, , "Kutools for Outlook"
    Err.Clear
  End If
  Exit Sub
End Sub

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

Notas:

1. Antes de aplicar este código VBA para imprimir apenas o arquivo pdf nos e-mails recebidos, primeiro você precisa baixar e instalar Adobe Acrobat Reader e defina-o como o leitor de pdf padrão em seu computador.
2. Na linha Caso "pdf", Por favor, mude "pdf" para a extensão de arquivo que você deseja imprimir.

3. Vá em frente e clique Ferramentas > Referências. No surgimento Referências - Projeto1 caixa de diálogo, verifique a Tempo de execução de scripts da Microsoft e, em seguida, clique no OK botão.

4. Salve o código e pressione o outro + Q chaves para fechar o Microsoft Visual Basic para Aplicações janela.

Observação: Certifique-se de que o Habilitar todas as macros opção está habilitada no seu Outlook. Você pode marcar esta opção seguindo as etapas mostradas abaixo.

Etapa 2: criar uma regra para usar o script

Depois de adicionar o script VBA no Outlook, você precisa criar uma regra para usar o script com base em determinadas condições.

1. Vá para a guia Início, clique em Regras > Gerenciar regras e alertas.

2. No Regras e Alertas caixa de diálogo, clique no botão Nova regra botão para criar uma regra.

Dicas: Se você adicionou várias contas de email ao seu Outlook, especifique uma conta no Aplicar alterações a esta pasta lista suspensa onde você deseja aplicar a regra. Caso contrário, ele será aplicado à caixa de entrada da conta de e-mail selecionada no momento.

3. No primeiro Assistente de regras caixa de diálogo, selecione Aplicar regra nas mensagens que recebo no Passo 1 caixa e, em seguida, clique em Avançar.

4. Na segunda Assistente de regras caixa de diálogo, você precisa:

4.1) Especifique uma ou mais condições no Passo 1 caixa de acordo com suas necessidades;
Nesse caso, quero imprimir apenas os anexos nos e-mails recebidos de um remetente especificado. Aqui, eu verifico o de pessoas ou grupo público caixa.
4.2) Clique no valor sublinhado na Passo 2 caixa para editar a condição;
4.3) Clique Avançar. Veja a imagem:

5. No terceiro Assistente de regras caixa de diálogo, você precisa configurar da seguinte maneira.

5.1) No Etapa 1: selecione a seção de ação(ões), Verifica a execute um script caixa;
5.2) No Passo 2 seção, clique no texto sublinhado “um script”;
5.3) Na abertura Selecione o script caixa de diálogo, clique no nome do código VBA que você adicionou acima e, em seguida, clique em ESTÁ BEM;
5.4) Clique no Próximo botão. Veja a imagem:

Dicas: Se oexecute um script” está faltando no seu Assistente de regras, você pode exibi-lo seguindo o método mencionado neste artigo: restaurar a pption Executar um script ausente na regra do Outlook.

6. Depois outro Assistente de regras aparece pedindo exceções. Você pode selecionar as exceções, se necessário, caso contrário, clique no botão Próximo botão sem nenhuma seleção。

7. No último Assistente de regras, você precisa especificar um nome para a regra e, em seguida, clicar no botão Acabamento botão.

8. Em seguida, ele retorna para o Regras e Alertas caixa de diálogo, você pode ver a regra que você criou listada dentro, clique no OK botão para terminar todas as configurações.

A partir de agora, quando um e-mail da pessoa especificada for recebido, os arquivos anexados serão impressos automaticamente.


Artigos relacionados

Imprimir apenas anexos de um e-mail ou e-mails selecionados no Outlook
No Outlook, você pode imprimir os emails, mas imprimiu os anexos apenas de um email ou emails selecionados no Outlook? Este artigo apresenta os truques para resolver este trabalho.

Imprimir apenas o cabeçalho da mensagem de um e-mail no Outlook
Ao imprimir um email no Outlook, ele imprimirá o cabeçalho e o corpo da mensagem no email. No entanto, em alguns casos especiais, pode ser necessário imprimir o cabeçalho da mensagem com o assunto, remetente, destinatários, etc. Este artigo apresentará duas soluções para isso.

Imprimir um calendário em um intervalo de datas especificado/personalizado no Outlook
Normalmente, ao imprimir um calendário no modo de exibição de mês no Outlook, ele selecionará automaticamente o mês que contém a data selecionada no momento. Mas talvez seja necessário imprimir o calendário dentro de um intervalo de datas personalizado, como 3 meses, metade do ano etc. Este artigo apresentará a solução para você.

Imprimir um contato com imagem no Outlook
Normalmente, a imagem de um contato não será impressa ao imprimir o contato no Outlook. Mas às vezes, será mais impressionante imprimir um contato com sua foto. Este artigo apresentará algumas soluções alternativas para fazer isso.

Imprimir uma seleção de um email no Outlook
Se você recebeu uma mensagem de e-mail e descobriu que há uma seleção do conteúdo do e-mail que precisa ser impresso em vez de imprimir a mensagem inteira, o que você faria? Na verdade, o Outlook pode ajudá-lo a realizar essa operação com a ajuda de navegadores de internet, como o Firefox e o Internet Explorer. Aqui, pegarei os navegadores da Internet, por exemplo. Por favor, veja os seguintes tutoriais.

Mais artigos sobre "impressão no 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 (22)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
Kan deze script ook gemaakt worden voor het verzenden van emails, dat je dan automatisch de bijlage kan laten afdrukken ?
This comment was minimized by the moderator on the site
Hello, thank you very much for the scripts, very useful indeed!
What if we wanted to print all attachments in an email in Outlook 365 web instead? Are there ways to try this?
This comment was minimized by the moderator on the site
Hi is there a way to print the email body including sender details and subject line in the script please. I pretty much need email and attachment printed out please.
This comment was minimized by the moderator on the site
Hi Mani,

If you want to print an email body including sender details and subject line, I suggest you try the Advanced Print feature of Kutools for Outlook. It can help you solve the problem easily.
https://www.extendoffice.com/images/stories/comments/comment-picture-zxm/advanced-print.png?1696644946
This comment was minimized by the moderator on the site
First of all, thanks a lot for these useful VBA scripts!
My situation is as follows: I usually receive a number of emails with 2 pdf files each. One pdf file, let's call it example1.pdf, needs to be printed only once, but the second pdf file, let's call it example2.pdf, needs to be printed 3 times. The example2.pdf does not necessarily always have the same name, but there are only around 2-4 name variants, so if it were possible to tell the script to look out for a few keywords I think it would work. Is this possible?
Oh, and would it be possible to also tell the script to print the example1.pdf file as duplex?
Thanks for your help.
This comment was minimized by the moderator on the site
Hi There, thanks for publishing this

I have followed the instructions above and are running the script to print all attachments delivered.

we typically receive these in batches of 5-8 and when testing i am getting 4 out of 5 prints with one failing with error 75. All PDF's have different names and are on separate emails/ the attachements can be opened manually fine so i assume theres an issue when it tries to copy this to the temp directory. Do you have any idea how we can resolve this?
This comment was minimized by the moderator on the site
Same problem here. After a couple of emails received during a short time, it can print 3-4 pdf, but after the error 75 appear, nothing print in the same batch of mails.
This comment was minimized by the moderator on the site
Hi Gabriel,
After testing, we have reproduced the problem you encountered. the VBA scripts have been updated in the post. Please give them a try. Thanks for your feedback.
This comment was minimized by the moderator on the site
Love this script! How about if I get an email with multiple pdfs and want one copy of each. Currently when I get 3 pdf's attached, it prints the final one, 3 times, and the other 2 do not get printed. Thanks for any help!
This comment was minimized by the moderator on the site
Hi val,

Sorry for the inconvenience.
Which VBA code are you applying? VBA code 1 or VBA code 2? Do the three PDF attachments have the same name? And which Outlook version are you using?
I have tested the codes and they worked well in my case. I need to know more specific about your issue.
This comment was minimized by the moderator on the site
Is it possible to specify the printer that should be used (not the system default printer)?
I need to print 2 types of documents on 2 different printers....
Thanks for your help!
This comment was minimized by the moderator on the site
Hi Simon,
Thank you for your comment. After trying with various methods, I can't seem to get this to work. Sorry for the inconvenience.
This comment was minimized by the moderator on the site
Hello, kindly I need help, I can't integrate the script for printing pdf only.
I activated everything, the first script for generic printing works perfectly (or almost: printing pdf attachments once printed acrobat reader remains open in the background), but the specific script for pdf does not work. Thanks for posting the scripts and for any help.
Good day
This comment was minimized by the moderator on the site
Hi Marco041,
There was something wrong with the code and it has been updated. Please give it a try.
Note: we have no way to prevent Acrobat Reader from being opened because we need to use it to open the pdf document for the next print job.
Thank you for your feedback.
Sub AttachementAutoPrint(Item As Outlook.MailItem)
'Updated by Extendoffice 20220920
  Dim xFS As FileSystemObject
  Dim xTempFolder As String
  Dim xAtt As Attachment
  Dim xShell As Object
  Dim xFolder As Object, xFolderItem As Object
  Dim xFileType As String, xFileName As String
  On Error GoTo xError
  Set xFS = New FileSystemObject
  xTempFolder = xFS.GetSpecialFolder(TemporaryFolder)
  xTempFolder = xTempFolder & "\ATMP" & Format(Now, "yyyymmddhhmmss")
  MkDir (xTempFolder)
  'Set Item = Application.ActiveExplorer.Selection.Item(1)
  Set xShell = CreateObject("Shell.Application")
  Set xFolder = xShell.NameSpace(0)
  For Each xAtt In Item.Attachments
    xFileName = xAtt.FileName
    xFileType = LCase$(Right$(xFileName, VBA.Len(xFileName) - VBA.InStrRev(xFileName, ".")))
    xFileName = xTempFolder & "\" & xFileName
    xAtt.SaveAsFile (xFileName)
    Select Case xFileType
      Case "pdf"   'change "pdf" to the file extension you want to print
        Set xFolderItem = xFolder.ParseName(xFileName)
        xFolderItem.InvokeVerbEx ("print")
    End Select
  Next xAtt
'xFS.DeleteFolder (xTempFolder)
Set xFS = Nothing
Set xFolder = Nothing
Set xFolderItem = Nothing
Set xShell = Nothing
xError:
  If Err <> 0 Then
    MsgBox Err.Number & " - " & Err.Description, , "Kutools for Outlook"
    Err.Clear
  End If
Exit Sub
End Sub
This comment was minimized by the moderator on the site
Bonjour question pour vous j'ai fait les étapes pour cela mais dans les règle de message de mon outlook je ne voit pas que je peux utilisé un script
This comment was minimized by the moderator on the site
Hi STEPHANE CADORETTE,
If the “run a script” option is missing in your Rules Wizard, you can display it by following the method mentioned in this article: restore missing Run A Script pption in Outlook rule.
This comment was minimized by the moderator on the site
Bonjour moi j'ai un petit soucie lorsque j'ai fait et refait les étapes mais lorsque je créer ma règle je n'Ai pas l'option run a script.
This comment was minimized by the moderator on the site
Hi Stéphane,
If the “run a script” option is missing in your Rules Wizard, you can display it by following the method mentioned in this article: restore missing Run A Script pption in Outlook rule.
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