Перейти к основному содержанию

Как автоматически печатать вложения при поступлении писем в Outlook?

В этом руководстве демонстрируется метод объединения сценария VBA и правила Outlook, который поможет вам автоматически печатать вложения определенных электронных писем, когда они поступают в Outlook.


Автоматически печатать вложения при получении определенных электронных писем

Предположим, вы хотите автоматически печатать вложения входящих писем от определенного отправителя. Вы можете сделать следующее, чтобы сделать это.

Шаг 1. Создайте сценарий в Outlook.

Во-первых, вам нужно создать скрипт VBA в Outlook.

1. Запустите Outlook, нажмите другой + F11 клавиши одновременно, чтобы открыть Microsoft Visual Basic для приложений окно.

2. в Microsoft Visual Basic для приложений окно, двойной щелчок по Project1 > Объекты Microsoft Outlook > Эта сессия Outlook для открытия ThisOutlookSession (Код) окно, а затем скопируйте следующий код в это окно кода.

Код VBA 1: автоматически печатать вложения (все типы вложений) при получении электронных писем.

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

Примечание: Этот код поддерживает печать всех типов вложений, полученных в электронных письмах. Если вы хотите печатать только вложения указанного типа, например файлы PDF, примените следующий код VBA.

Код VBA 2: автоматически печатать вложения указанного типа при получении электронных писем

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

Заметки:

1. Прежде чем применять этот код VBA для печати только pdf-файла во входящих сообщениях электронной почты, сначала необходимо загрузить и установить Adobe Acrobat Reader и установите его в качестве программы для чтения PDF по умолчанию на вашем компьютере.
2. В очереди Кейс "pdf", пожалуйста измените "ПДФ" к расширению файла, который вы хотите напечатать.

3. Продолжайте и нажмите Инструменты > Рекомендации. В всплывающем Рекомендации – Проект1 диалоговое окно, проверьте Среда выполнения сценариев Microsoft поле, а затем щелкните OK .

4. Сохраните код и нажмите другой + Q ключи, чтобы закрыть Microsoft Visual Basic для приложений окно.

Примечание: Убедитесь, что Включить все макросы опция включена в вашем Outlook. Вы можете проверить эту опцию, выполнив шаги, показанные ниже.

Шаг 2: Создайте правило для использования скрипта

После добавления сценария VBA в Outlook необходимо создать правило для использования сценария на основе определенных условий.

1. Перейдите на вкладку Главная, нажмите Правила > Управление правилами и предупреждениями.

2. в Правила и предупреждения диалогового окна, нажмите Новое правило кнопку, чтобы создать правило.

Советы: Если вы добавили несколько учетных записей электронной почты в Outlook, укажите учетную запись в Применить изменения к этой папке выпадающий список, где вы хотите применить правило. В противном случае он будет применен к папке «Входящие» текущей выбранной учетной записи электронной почты.

3. В первом Мастер правил диалоговое окно, выберите Применить правило для сообщений, которые я получаю в Шаг 1 и нажмите Далее.

4. В секунду Мастер правил диалоговое окно, вам необходимо:

4.1) Укажите одно или несколько условий в Шаг 1 коробка в соответствии с вашими потребностями;
В этом случае я хочу печатать только вложения во входящих сообщениях электронной почты от указанного отправителя. Вот, я проверяю от людей или публичной группы пунктом.
4.2) Щелкните подчеркнутое значение в Шаг 2 поле для редактирования условия;
4.3) Нажмите Далее. Смотрите скриншот:

5. В третьем Мастер правил диалоговое окно необходимо настроить следующим образом.

5.1). Шаг 1. Выберите раздел действий., проверить запустить сценарий коробка;
5.2). Шаг 2 раздел, нажмите на подчеркнутый текст «сценарий»;
5.3) В открытии Выбрать сценарий диалоговом окне щелкните имя кода VBA, который вы добавили выше, а затем щелкните ОК;
5.4) Нажмите Следующая кнопка. Смотрите скриншот:

Советы: Если «запустить сценарий” отсутствует в вашем Мастер правил, вы можете отобразить его, следуя методу, упомянутому в этой статье: восстановить отсутствующую pption Run A Script в правиле Outlook.

6. Затем еще один Мастер правил всплывает запрос на исключения. Вы можете выбрать исключения, если это необходимо, в противном случае нажмите кнопку Следующая кнопка без выбора。

7. В последний Мастер правил, необходимо указать имя правила, а затем нажать кнопку Завершить .

8. Затем он возвращается в Правила и предупреждения диалоговое окно, вы можете увидеть созданное вами правило в списке, щелкните OK кнопку, чтобы завершить все настройки.

Отныне при получении электронного письма от указанного лица вложенные файлы будут распечатываться автоматически.


Статьи по теме

Печатать вложения только из одного электронного письма или выбранных электронных писем в Outlook
В Outlook вы можете распечатать электронные письма, но распечатали ли вы вложения только из одного электронного письма или выбранных электронных писем в Outlook? В этой статье представлены приемы решения этой задачи.

Печатать только заголовок сообщения электронной почты в Outlook
При печати электронного письма в Outlook он печатает как заголовок сообщения, так и тело сообщения в электронном письме. Однако в некоторых особых случаях вам может потребоваться просто распечатать заголовок сообщения с указанием темы, отправителя, получателей и т. д. В этой статье представлены два решения для этого.

Печать календаря в указанном/настраиваемом диапазоне дат в Outlook
Обычно при печати календаря в режиме просмотра «Месяц» в Outlook автоматически выбирается месяц, содержащий текущую выбранную дату. Но вам может потребоваться распечатать календарь в пределах пользовательского диапазона дат, например, 3 месяца, полгода и т. д. Эта статья познакомит вас с решением.

Распечатать контакт с изображением в Outlook
Обычно изображение контакта не распечатывается при печати контакта в Outlook. Но иногда эффектнее будет распечатать контакт с его изображением. В этой статье будут представлены некоторые обходные пути, чтобы это сделать.

Распечатать выборку электронной почты в Outlook
Если вы получили сообщение электронной почты и обнаружили, что необходимо распечатать часть содержимого электронной почты вместо печати всего сообщения, что бы вы сделали? На самом деле Outlook может помочь вам выполнить эту операцию с помощью интернет-браузеров, таких как Firefox и Internet Explorer. В качестве примера я возьму Интернет-браузеры. Пожалуйста, посмотрите следующие руководства.

Еще статьи про "печать в Outlook"...


Лучшие инструменты для офисной работы

Kutools for Outlook - Более 100 мощных функций для улучшения вашего Outlook

🤖 Почтовый помощник с искусственным интеллектом: Мгновенные профессиональные электронные письма с помощью магии искусственного интеллекта: гениальные ответы одним щелчком мыши, идеальный тон, многоязычное владение. Преобразуйте электронную почту без особых усилий! ...

???? Автоматизация электронной почты: Нет на месте (доступно для POP и IMAP)  /  Расписание отправки писем  /  Автоматическое копирование/скрытая копия по правилам при отправке электронной почты  /  Автопересылка (расширенные правила)   /  Автоматическое добавление приветствия   /  Автоматически разделять электронные письма от нескольких получателей на отдельные сообщения ...

📨 Управление электронной почтой: Легко вспоминать электронные письма  /  Блокировка мошеннических писем от субъектов и других лиц  /  Удалить повторяющиеся электронные письма  /  Поиск  /  Объединение папок ...

📁 Вложения ProПакетное сохранение  /  Пакетное отсоединение  /  Пакетное сжатие  /  Автосохранение   /  Авто отсоединение  /  Автоматическое сжатие ...

???? Магия интерфейса: 😊Больше красивых и крутых смайлов   /  Повысьте производительность Outlook с помощью представлений с вкладками  /  Свернуть Outlook вместо закрытия ...

???? Чудеса в один клик: Ответить всем с входящими вложениями  /   Антифишинговые письма  /  🕘Показать часовой пояс отправителя ...

👩🏼‍🤝‍👩🏻 Контакты и календарь: Пакетное добавление контактов из выбранных писем  /  Разделить группу контактов на отдельные группы  /  Удалить напоминания о днях рождения ...

Более Особенности 100 Ждем вашего исследования! Нажмите здесь, чтобы узнать больше.

 

 

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