Hoppa till huvudinnehåll

Hur skriver man automatiskt ut bilagor när e-postmeddelanden kommer in i Outlook?

Den här handledningen visar en metod för att kombinera ett VBA-skript och en Outlook-regel för att hjälpa dig att automatiskt skriva ut bilagor till vissa e-postmeddelanden när de kommer till Outlook.


Skriv ut bilagor automatiskt när vissa e-postmeddelanden kommer

Om du antar att du vill skriva ut bilagor av inkommande e-postmeddelanden från en viss avsändare automatiskt. Du kan göra enligt följande för att få det gjort.

Steg 1: Skapa ett skript i Outlook

Först måste du skapa ett VBA-skript i Outlook.

1. Starta din Outlook, tryck på andra + F11 samtidigt för att öppna Microsoft Visual Basic för applikationer fönster.

2. I Microsoft Visual Basic för applikationer fönster, dubbelklicka på Project1 > Microsoft Outlook-objekt > ThisOutlookSession att öppna ThisOutlookSession (kod) och kopiera sedan följande kod till detta kodfönster.

VBA-kod 1: Skriv automatiskt ut bilagor (alla typer av bilagor) när mejl kommer in

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

Notera: Den här koden stöder utskrift av alla typer av bilagor som tas emot i e-postmeddelanden. Om du bara vill skriva ut den angivna typen av bilaga, såsom pdf-filer, använd följande VBA-kod.

VBA-kod 2: Skriv ut automatiskt den angivna typen av bilagor när e-postmeddelanden kommer

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

Anmärkningar:

1. Innan du använder denna VBA-kod för att endast skriva ut pdf-filen i de inkommande e-postmeddelandena måste du först ladda ner och installera Adobe Acrobat Reader och ställ in den som standard pdf-läsare på din dator.
2. I raden Fall "pdf", snälla ändras "pdf" till filtillägget du vill skriva ut.

3. Gå vidare och klicka verktyg > Referenser. I poppar upp Referenser – Projekt1 dialogrutan, kolla på Microsoft Scripting Runtime och klicka sedan på OK knapp.

4. Spara koden och tryck på andra + Q för att stänga Microsoft Visual Basic för applikationer fönster.

Notera: Se till att Aktivera alla makron alternativet är aktiverat i din Outlook. Du kan markera det här alternativet genom att följa stegen nedan.

Steg 2: Bygg en regel för att använda skriptet

Efter att ha lagt till VBA-skriptet i Outlook måste du skapa en regel för att använda skriptet baserat på vissa villkor.

1. Gå till fliken Hem, klicka regler > Hantera regler och varningar.

2. I Regler och varningar dialogrutan, klicka på Ny regel för att skapa en regel.

Tips: Om du har lagt till flera e-postkonton till din Outlook, vänligen ange ett konto i Tillämpa ändringar på den här mappen rullgardinsmenyn där du vill tillämpa regeln. Annars kommer det att tillämpas på inkorgen för det för närvarande valda e-postkontot.

3. I den första Regelguiden dialogrutan väljer du Använd regel för meddelanden jag får i steg 1 rutan och klicka sedan på Nästa.

4. På sekunden Regelguiden dialogrutan måste du:

4.1) Ange ett eller flera villkor i steg 1 box enligt dina behov;
I det här fallet vill jag bara skriva ut bilagorna i inkommande e-postmeddelanden från en angiven avsändare. Här kollar jag från människor eller offentlig grupp låda.
4.2) Klicka på det understrukna värdet i steg 2 ruta för att redigera villkoret;
4.3) Klicka Nästa. Se skärmdump:

5. I det tredje Regelguiden i dialogrutan måste du konfigurera enligt följande.

5.1) I Steg 1: Välj åtgärdssektion, kolla kör ett skript låda;
5.2) I steg 2 klickar du på den understrukna texten "ett skript";
5.3) I öppningen Välj skript dialogrutan klickar du på namnet på VBA-koden du lade till ovan och klickar sedan OK;
5.4) Klicka på Nästa knapp. Se skärmdump:

Tips: Om "kör ett skript”-alternativet saknas i din Regelguiden, kan du visa den genom att följa metoden som nämns i den här artikeln: återställ saknad Kör ett skript-pption i Outlook-regeln.

6. Sedan en till Regelguiden dyker upp och frågar efter undantag. Du kan välja undantagen om det behövs, annars klickar du på Nästa knapp utan några val.

7. I det sista Regelguidenmåste du ange ett namn för regeln och klicka sedan på Finish knapp.

8. Sedan återgår den till Regler och varningar dialogrutan kan du se regeln du skapade listad inuti, klicka på OK för att avsluta alla inställningar.

Från och med nu, när ett e-postmeddelande från den angivna personen tas emot, kommer de bifogade filerna att skrivas ut automatiskt.


Relaterade artiklar

Skriv endast ut bilagor från ett e-postmeddelande eller valda e-postmeddelanden i Outlook
I Outlook kan du skriva ut mejlen, men har du skrivit ut bilagorna endast från ett mejl eller valda mejl i Outlook? Den här artikeln introducerar knepen för att lösa det här jobbet.

Skriv bara ut meddelanderubriken för ett e-postmeddelande i Outlook
När du skriver ut ett e-postmeddelande i Outlook kommer det att skriva ut både meddelandehuvud och meddelandetext i e-postmeddelandet. Men i vissa speciella fall kan du bara behöva skriva ut meddelandehuvudet med ämne, avsändare, mottagare etc. Den här artikeln kommer att introducera två lösningar för att göra det.

Skriv ut en kalender i ett specificerat/anpassat datumintervall i Outlook
Normalt, när du skriver ut en kalender i månadsvy i Outlook, kommer den automatiskt att välja månaden som innehåller det aktuella valda datumet. Men du kan behöva skriva ut kalendern inom ett anpassat datumintervall, såsom 3 månader, halvår, etc. Den här artikeln presenterar lösningen för dig.

Skriv ut en kontakt med bild i Outlook
Normalt skrivs inte ut en kontakts bild när kontakten skrivs ut i Outlook. Men ibland blir det mer imponerande att skriva ut en kontakt med bilden. Den här artikeln kommer att presentera några lösningar för att få det gjort.

Skriv ut ett urval av ett e-postmeddelande i Outlook
Om du fick ett e-postmeddelande och upptäckte att det finns ett urval av e-postinnehållet måste skrivas ut istället för att skriva ut hela meddelandet, vad skulle du göra? Egentligen kan Outlook hjälpa dig att uppnå denna operation med hjälp av webbläsare, till exempel Firefox och Internet Explorer. Här tar jag till exempel webbläsarna. Se följande handledning.

Fler artiklar om "utskrift i Outlook"...


Bästa kontorsproduktivitetsverktyg

Kutools för Outlook - Över 100 kraftfulla funktioner för att överladda din Outlook

🤖 AI Mail Assistant: Instant proffs-e-postmeddelanden med AI-magi – ett klick för geniala svar, perfekt ton, flerspråkig behärskning. Förvandla e-post utan ansträngning! ...

📧 Email Automation: Frånvaro (tillgänglig för POP och IMAP)  /  Schemalägg Skicka e-post  /  Auto CC/BCC enligt regler när du skickar e-post  /  Automatisk vidarebefordran (avancerade regler)   /  Lägg automatiskt till hälsning   /  Dela automatiskt e-postmeddelanden med flera mottagare i individuella meddelanden ...

📨 Email Management: Hämta enkelt e-postmeddelanden  /  Blockera bluff-e-postmeddelanden av ämnen och andra  /  Ta bort duplicerade e-postmeddelanden  /  Avancerad Sökning  /  Konsolidera mappar ...

📁 Bilagor ProBatch Spara  /  Batch lossa  /  Batchkomprimera  /  Automatisk sparning   /  Auto Lossa  /  Automatisk komprimering ...

🌟 Gränssnittsmagi: 😊 Fler vackra och coola emojis   /  Öka din Outlook-produktivitet med flikar  /  Minimera Outlook istället för att stänga ...

👍 Underverk med ett klick: Svara alla med inkommande bilagor  /   E-postmeddelanden mot nätfiske  /  🕘Visa avsändarens tidszon ...

👩🏼‍🤝‍👩🏻 Kontakter och kalender: Lägg till kontakter i grupp från valda e-postmeddelanden  /  Dela upp en kontaktgrupp till individuella grupper  /  Ta bort påminnelser om födelsedag ...

Över 100 funktioner Vänta på din utforskning! Klicka här för att upptäcka mer.

Läs mer       Gratis nedladdning      Inköp
 

 

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