Apple Intelligence now features Image Playground, Genmoji, Writing Tools enhancements, seamless support for ChatGPT, and visual intelligence.

Apple Intelligence has also begun language expansion with localized English support for Australia, Canada, Ireland, New Zealand, South Africa, and the U.K. Learn more >

You can make a difference in the Apple Support Community!

When you sign up with your Apple Account, you can provide valuable feedback to other community members by upvoting helpful replies and User Tips.

Looks like no one’s replied in a while. To start the conversation again, simply ask a new question.

Script to PDF email and merge with attachments

Not sure if this is the right forum for this. Does anyone know of a script that can PDF a message in Apple Mail and merge with the PDF attachments in the email and save to Desktop?


Thanks!



iMac 27″, macOS 10.12

Posted on Jun 18, 2021 8:38 AM

Reply
Question marked as Top-ranking reply

Posted on Jun 21, 2021 8:19 AM

Rather than let this go unanswered, Apple Mail has no AppleScript dictionary support to export a selected Mail message as PDF.


Although one can likely extract the PDF attachments from the selected message, other than sorting them alphabetically, there would be no way to control the order in which the attachments are merged with the message PDF (if it were to exist), and there is no PDF merging code in AppleScript.


As it turns out, I was bored yesterday, and I did write some AppleScript/Objective-C code that allows a user to select n-tuple PDF documents and merge them to another PDF of a user-defined name. This is a moot point though based on the first paragraph's limitations.

8 replies
Question marked as Top-ranking reply

Jun 21, 2021 8:19 AM in response to chrisbarrett

Rather than let this go unanswered, Apple Mail has no AppleScript dictionary support to export a selected Mail message as PDF.


Although one can likely extract the PDF attachments from the selected message, other than sorting them alphabetically, there would be no way to control the order in which the attachments are merged with the message PDF (if it were to exist), and there is no PDF merging code in AppleScript.


As it turns out, I was bored yesterday, and I did write some AppleScript/Objective-C code that allows a user to select n-tuple PDF documents and merge them to another PDF of a user-defined name. This is a moot point though based on the first paragraph's limitations.

Jun 25, 2021 10:07 AM in response to chrisbarrett

Here's a script that may do something close enough to what you wanted, using "gui" scripting (slow and clunky, but apparently the only option here):


This could probably be improved by possible integration with VikingOSX's pdf merging script, should he choose to post that.


-- saves selected Mail message as pdf

set saveFolderPath to "~/Desktop/"

tell application "Mail"
	set theSel to selection
	set theMessage to item 1 of theSel
	activate -- needed for gui-scripting
	
	--print the message to pdf
	tell application "System Events"
		tell process "Mail"
			click menu item "Print…" of menu "File" of menu bar 1
			repeat until exists sheet 1 of window 1
				delay 3 -- increase if needed
			end repeat
			tell splitter group 1 of sheet 1 of window 1
				click menu button "PDF"
				click menu item "Save as PDF" of menu 1 of menu button "PDF"
			end tell
			repeat until exists button "Save" of sheet 1 of sheet 1 of window 1
				delay 0.02
			end repeat
			keystroke "g" using {command down, shift down}
			repeat until exists combo box 1 of sheet 1 of sheet 1 of sheet 1 of window 1
				delay 0.02
			end repeat
			tell sheet 1 of sheet 1 of sheet 1 of window 1
				set value of combo box 1 to saveFolderPath
				click button "Go"
			end tell
			click button "Save" of sheet 1 of sheet 1 of window 1
			delay 0.5
			repeat while exists button "Cancel" of sheet 1 of window 1
				delay 0.2
			end repeat
		end tell
	end tell
	
	-- save the attachments -- (only need this if they are not visible inline?)
	repeat with anAttachment in mail attachments of theMessage
		-- set attachName to name of anAttachment
		try
			save theAttachment in POSIX file saveFolderPath
		end try
	end repeat
end tell



Tested in Big Sur 11.4, Apple Mail 14.0. The 'delay' times may need tweaking on other machines.


SG




Jun 25, 2021 9:06 PM in response to VikingOSX

Yes, GUI scripts are to be avoided if possible. I was surprised to find Mail doesn't allow a better solution. This one does seem to work on my setup, though. (The message prints, though I may have something wrong about grabbing and saving attachments separately). Any chance of posting your pdf-merge script?


SG

Jun 26, 2021 6:08 AM in response to SGIII

Here is the AppleScript that allows a user to select multiple PDF (in the order they are to be merged), and then that result is written to a separate PDF. I am presently revising the code to append subsequent selected PDF to the first PDF and write the merge to the first PDF. This was adapted from Objective-C.


(*
  merge_pdf.applescript
  
  Prompt user for PDF filenames to merge using the ⌘-key for multiple selection.
  PDF will be merged in the order of their selection and written to an arbitrary
  PDF filename on the Desktop.
  
  Tested: macOS 11.4
  VikingOSX, 2021-06-24, Apple Support Communities, No warranty/support implied.
*)

use AppleScript version "2.4" -- Yosemite (10.10) or later
use framework "Foundation"
use scripting additions

property NSString : a reference to current application's NSString
property NSURL : a reference to current application's NSURL
property PDFDocument : a reference to current application's PDFDocument

set merged_pdf to (NSString's stringWithString:"~/Desktop/merged.pdf")'s stringByStandardizingPath()

set msg to "Select multiple PDF using the ⌘-key in the order of your merge preference."
set pdfList to (choose file with prompt msg of type {"com.adobe.pdf"} default location (path to desktop) with multiple selections allowed)

set outurl to NSURL's fileURLWithPath:(POSIX path of (item 1 of pdfList))
set outpdf to PDFDocument's alloc()'s initWithURL:outurl
set lastPage to outpdf's pageCount()
set pdfList to rest of pdfList

repeat with pdfdoc in pdfList
    set thisURL to (NSURL's fileURLWithPath:((POSIX path of pdfdoc) as text))
    set thisPDF to (PDFDocument's alloc()'s initWithURL:thisURL)

    repeat with n from 1 to thisPDF's pageCount()
        set this_page to (thisPDF's pageAtIndex:(n - 1))
        outpdf's insertPage:this_page atIndex:lastPage
        set lastPage to outpdf's pageCount()
    end repeat
end repeat
outpdf's writeToFile:merged_pdf
return



Jun 26, 2021 6:58 AM in response to chrisbarrett

Both SGIII and I are apprehensive about providing what is termed a GUI script to force Apple Mail to either Export as PDF or Print to PDF, a currently selected message. GUI scripting is dependent on names and locations of visual elements in the application not changing, and should Apple modify Apple Mail in the future, and those application elements change, then the script breaks. A glass jaw analogy.


Let's assume we can automate a selected message into a PDF. And that we can extract its PDF attachments too. Ideally, all of these need to be saved to the same folder location. I have just posted code that can merge PDF, and SGIII may find a way to glue a complete solution together for you as my time is limited.

Script to PDF email and merge with attachments

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple Account.