Saltar al contenido principal

¿Cómo imprimir archivos adjuntos automáticamente cuando llegan correos electrónicos a Outlook?

Este tutorial demuestra un método para combinar una secuencia de comandos de VBA y una regla de Outlook para ayudarlo a imprimir automáticamente los archivos adjuntos de ciertos correos electrónicos cuando llegan a Outlook.


Imprima automáticamente archivos adjuntos cuando lleguen ciertos correos electrónicos

Supongamos que desea imprimir automáticamente los archivos adjuntos de los correos electrónicos entrantes de un determinado remitente. Puede hacer lo siguiente para hacerlo.

Paso 1: crea un script en Outlook

En primer lugar, debe crear un script VBA en Outlook.

1. Inicie su Outlook, presione el otro + F11 teclas simultáneamente para abrir el Microsoft Visual Basic para aplicaciones ventana.

2. En el Microsoft Visual Basic para aplicaciones ventana, haga doble clic en Proyecto1 > Objetos de Microsoft Outlook > Esta sesión de Outlook para abrir el ThisOutlookSession (Código) y luego copie el siguiente código en esta ventana de código.

Código VBA 1: imprima automáticamente los archivos adjuntos (todos los tipos de archivos adjuntos) cuando lleguen los correos electrónicos

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

Nota: Este código admite la impresión de todo tipo de archivos adjuntos recibidos en correos electrónicos. Si desea imprimir solo el tipo de archivo adjunto especificado, como archivos pdf, aplique el siguiente código VBA.

Código VBA 2: imprima automáticamente el tipo especificado de archivos adjuntos cuando lleguen los correos electrónicos

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 solo el archivo pdf en los correos electrónicos entrantes, primero debe descargar e instalar Adobe Acrobat Reader y configúrelo como el lector de PDF predeterminado en su computadora.
2. En la fila Caso "pdf", por favor cambia "pdf" a la extensión de archivo que desea imprimir.

3. Continúe y haga clic Herramientas > Referencias. En el apareciendo Referencias – Proyecto1 cuadro de diálogo, verifique Tiempo de ejecución de secuencias de comandos de Microsoft cuadro, y luego haga clic en el OK del botón.

4. Guarde el código y presione la otro + Q llaves para cerrar el Microsoft Visual Basic para aplicaciones ventana.

Nota: Por favor, asegúrese de que Habilitar todas las macros La opción está habilitada en su Outlook. Puede marcar esta opción siguiendo los pasos que se muestran a continuación.

Paso 2: cree una regla para usar el script

Después de agregar la secuencia de comandos de VBA en Outlook, debe crear una regla para usar la secuencia de comandos según ciertas condiciones.

1. Vaya a la pestaña Inicio, haga clic en Reglas > Administrar reglas y alertas.

2. En el Reglas y Alertas cuadro de diálogo, haga clic en Nueva regla botón para crear una regla.

Consejos: Si ha agregado varias cuentas de correo electrónico a su Outlook, especifique una cuenta en el Aplicar cambios a esta carpeta lista desplegable donde desea aplicar la regla. De lo contrario, se aplicará a la bandeja de entrada de la cuenta de correo electrónico seleccionada actualmente.

3. En el primero Asistente de reglas cuadro de diálogo, seleccione Aplicar regla sobre los mensajes que recibo existentes Paso 1 cuadro, y luego haga clic Siguiente.

4. En el segundo Asistente de reglas cuadro de diálogo, debe:

4.1) Especificar una o más condiciones en el Paso 1 caja de acuerdo a sus necesidades;
En este caso, quiero imprimir solo los archivos adjuntos en los correos electrónicos entrantes de un remitente específico. Aquí reviso el de personas o grupo público encajonar.
4.2) Haga clic en el valor subrayado en el Paso 2 cuadro para editar la condición;
4.3) Click Siguiente. Ver captura de pantalla:

5. En el tercero Asistente de reglas cuadro de diálogo, debe configurarlo de la siguiente manera.

5.1) en el Paso 1: Seleccione la sección de acción(es), comprueba la ejecutar un script caja;
5.2) en el Paso 2 sección, haga clic en el texto subrayado "un guión";
5.3) En la apertura Seleccionar guion cuadro de diálogo, haga clic en el nombre del código VBA que agregó anteriormente y luego haga clic en Aceptar;
5.4) Haga clic en Siguiente botón. Ver captura de pantalla:

Consejos: Si el "ejecutar un scriptfalta la opción ” en su Asistente de reglas, puede mostrarlo siguiendo el método mencionado en este artículo: restaurar la aplicación Ejecutar un script faltante en la regla de Outlook.

6. Luego otro Asistente de reglas aparece pidiendo excepciones. Puede seleccionar las excepciones si es necesario, de lo contrario, haga clic en el Siguiente botón sin ninguna selección。

7. En el último Asistente de reglas, debe especificar un nombre para la regla y luego hacer clic en el Acabado del botón.

8. Luego vuelve al Reglas y Alertas cuadro de diálogo, puede ver la regla que creó enumerada dentro, haga clic en el OK botón para finalizar toda la configuración.

A partir de ahora, cuando se reciba un correo electrónico de la persona especificada, los archivos adjuntos se imprimirán automáticamente.


Artículos relacionados

Solo imprima los archivos adjuntos de un correo electrónico o correos electrónicos seleccionados en Outlook
En Outlook, puede imprimir los correos electrónicos, pero ¿imprimió los archivos adjuntos solo de un correo electrónico o correos electrónicos seleccionados en Outlook? Este artículo presenta los trucos para resolver este trabajo.

Imprimir solo el encabezado del mensaje de un correo electrónico en Outlook
Al imprimir un correo electrónico en Outlook, se imprimirá tanto el encabezado como el cuerpo del mensaje en el correo electrónico. Sin embargo, en algunos casos especiales, es posible que solo necesite imprimir el encabezado del mensaje con el asunto, el remitente, los destinatarios, etc. Este artículo presentará dos soluciones para hacerlo.

Imprima un calendario en un rango de fechas específico/personalizado en Outlook
Normalmente, al imprimir un calendario en la vista Mes de Outlook, automáticamente seleccionará el mes que contiene la fecha seleccionada actualmente. Sin embargo, es posible que deba imprimir el calendario dentro de un rango de fechas personalizado, como 3 meses, la mitad del año, etc. Este artículo le presentará la solución.

Imprimir un contacto con imagen en Outlook
Normalmente, la imagen de un contacto no se imprimirá al imprimir el contacto en Outlook. Pero a veces será más impresionante imprimir un contacto con su imagen. Este artículo presentará algunas soluciones para hacerlo.

Imprimir una selección de un correo electrónico en Outlook
Si recibió un mensaje de correo electrónico y descubrió que hay una selección del contenido del correo electrónico que debe imprimirse en lugar de imprimir el mensaje completo, ¿qué haría? De hecho, Outlook puede ayudarlo a lograr esta operación con la ayuda de navegadores de Internet, como Firefox e Internet Explorer. Aquí tomaré los navegadores de Internet, por ejemplo. Consulte los siguientes tutoriales.

Más artículos sobre "imprimir en Outlook"...


Las mejores herramientas de productividad de oficina

Kutools para Outlook - Más de 100 potentes funciones para potenciar tu perspectiva

🤖 Asistente de correo AI: Correos electrónicos profesionales instantáneos con magia de IA: respuestas geniales con un clic, tono perfecto y dominio multilingüe. ¡Transforme el correo electrónico sin esfuerzo! ...

📧 Automatización de correo electrónico: Fuera de la oficina (disponible para POP e IMAP)  /  Programar envío de correos electrónicos  /  CC/CCO automático según reglas al enviar correo electrónico  /  Reenvío automático (reglas avanzadas)   /  Agregar saludo automáticamente   /  Divida automáticamente correos electrónicos de múltiples destinatarios en mensajes individuales ...

📨 Gestión de correo electrónico: Recuperar correos electrónicos fácilmente  /  Bloquear correos electrónicos fraudulentos por sujetos y otras personas  /  Eliminar correos electrónicos duplicados  /  Búsqueda Avanzada  /  Consolidar carpetas ...

📁 Archivos adjuntos profesionalesGuardar lote  /  Separación de lotes  /  Comprimir por lotes  /  Ahorro automático   /  Desconexión automática  /  Autocompresión ...

???? Interfaz mágica: 😊Más emojis bonitos y geniales   /  Aumente su productividad en Outlook con vistas con pestañas  /  Minimizar Outlook en lugar de cerrar ...

👍 Maravillas con un clic: Responder a todos los archivos adjuntos entrantes  /   Correos electrónicos antiphishing  /  🕘Mostrar zona horaria del remitente ...

👩🏼‍🤝‍👩🏻 Contactos y calendario: Agregar por lotes contactos de correos electrónicos seleccionados  /  Dividir un grupo de contactos en grupos individuales  /  Eliminar recordatorios de cumpleaños ...

Mas de Características 100 ¡Espere su exploración! Haga clic aquí para descubrir más.

Leer Mas       Descargar gratis      Comprar
 

 

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