Save attachments from Mountain Lion Mail

I have a script that processes PDF email faxes and PDF attachments received via Mail.

This broke completely in Mountain Lion.

The part that broke is this:

save first mail attachment of This_Message in The_File with replacing

Error received is:

error "Mail got an error: AppleEvent handler failed." number -10000

I’ve seen lost of posts online about these errors, but no definitive fix.

Hi,

actually the save command in Mail has no replacing parameter

Thanks Stefan - the save command doesn’t work without the “with replacing” that part either…

Is there another way to save an attachment to a specific location from a message?

Hi

Just following up this thread. Anyone worked out how to save files in Mountain Lion Mail?

Actually, I am looking to do a script to open the attachments in Acrobat, but gather you have to save them first.

Problem is that the Mail save command appears not to work, as biggerfish has discovered.

Or am I wrong? Is there a way to save attachments in Mountain Lion Mail?

Thanks

You may find interesting code in this script writen to help an user which wanted to save attachments in a rtfd file whose text part is the message itself.
In this case, the mails to treat were stored in a dedicated mailbox.
I leave the change of this feature as an exercise :wink:


####################################################
#
property useMessageDate : true
# true = extracts the date from the body of the message and stamp the file with it
# false = use the current date-time to stamp the file with it
#
property substractTimeToGMT : true
# true = substract time to GMT from dates
# false = doesn't substract time to GMT
#
property stampWithShell : true
# true = use Shell script to build date-time stamp
# false = use horodateur to build date-time stamp
#
property stampTheMessages : true
# true = insert date-time stamp in fileMessages names
# false = leave fileMessages names without stamp
#
property moveToFinalStorage : true
# true = move the fileMessages to the folder "final_storage"
#		(where they may conflict if you stamp them according to "date received")
# false = leave the fileMessages on the Desktop
#		(where they may conflict if you run the script twice with no stamp)
#
####################################################

property ptd : missing value

#
# For safe, activate GUIScripting if it's not already active.
#
my activateGUIscripting()
beep 1
tell application "SystemUIServer"
	activate
	display dialog "CAUTION !" & return & "Don't move the cursor while the script is running." giving up after 30
end tell
set ptd to path to desktop as text
my SubRoutine1()
set path2FinalFolder to missing value
set ptd to missing value

#=====

on SubRoutine1()
	local Cyclethroughmessages, wName
	
	tell application "Mail"
		activate
		{}
		try
			messages of mailbox "* items to shift" as list
		end try
	end tell # Mail
	
	repeat with Cyclethroughmessages in reverse of result
		#
		# This loop isn't entered if grabbing the messages failed or returned an empty list.
		#
		tell application "Mail"
			activate
			set selected mailboxes of message viewers to mailbox "* items to shift"
			set the selected messages of message viewers to Cyclethroughmessages
			
			set wName to name of window 1
			#
			# Extracts date received from the message.
			# May be replaced by date which is the same than date sent.
			#
			{date received, count (every mail attachment)} of Cyclethroughmessages
			my SubRoutine2(wName, result)
		end tell # Mail
	end repeat
end SubRoutine1

#=====

on SubRoutine2(windowName, {date_received, nb_Attachments})
	local nameOfFileMessage, theExt
	# step 1, save the message on the Desktop.
	# The next steps are executed if the message
	# embed attachments which aren't passed in the rtfd file.
	# step 2, save the attachments in a folder on the Desktop.
	# step 3, move the attachment from the folder to the rtfd document
	# step 4, move the message file in the dedicated folder.
	
	set nameOfFileMessage to my saveTheMessage(windowName)
	if nameOfFileMessage ends with ".rtf" then
		set theExt to ".rtf"
		# here if there was no attachment !
	else
		set theExt to ".rtfd"
		#
		# step 2 The file message is a rtfd one. Check if it contain the attachment files.
		#
		# Grab the count of attachment files existing in the rtfd package.
		# Substract 1 because the count is :
		# 1 (for the TXT.rtf file) + count attachment files
		#
		tell application "System Events"
			(count every disk item of disk item (ptd & nameOfFileMessage)) - 1
		end tell
		if result ≠ nb_Attachments then
			#
			# Attachment files weren't embedded !
			# Save the full set in a folder on the Desktop.
			#
			my saveAndPassAttachments(windowName, nameOfFileMessage)
			
		end if # result ≠  nb_Attachments
	end if # nameOfFileMessage ends with .	
	
	#
	#  Step 4, move the file path2FileMessage to its final location.
	#
	if moveToFinalStorage then
		if stampTheMessages then
			set stampedName to my stampMessageFile(nameOfFileMessage, date_received, theExt)
			my moveMessageToFinalStorage(stampedName, date_received, theExt)
			# the stamped message is in final_storage
		else
			my moveMessageToFinalStorage(nameOfFileMessage, date_received, theExt)
			# the bare message is in final_storage
		end if # stampTheMessages
	else
		if stampTheMessages then
			set stampedName to my stampMessageFile(nameOfFileMessage, date_received, theExt)
			# the stamped message is on the Desktop
		else
			# the bare message is on the Desktop
		end if # stampTheMessages
	end if # moveToFinalStorage
end SubRoutine2

#=====

on saveTheMessage(window_Name)
	local theNameOfFileMessage
	
	activate application "Mail"
	tell application "System Events" to tell process "Mail" to tell window window_Name
		#
		# Step 1, save the message on the Desktop
		#
		# Issue the shortcut for "Save As."
		keystroke "s" using {command down, shift down}
		repeat until exists sheet 1
			delay 0.1
		end repeat
		tell sheet 1
			keystroke "d" using {command down, shift down} # to save on the Desktop
			try
				if value of checkbox 1 of group 1 = 0 then click checkbox 1 of group 1
			end try
			tell group 1 to tell pop up button 1
				click
				repeat
					try
						name of menu item 1 of menu 1 # try to grab the name of the menu item appearing in the "button"
						exit repeat # exit when the pop up button is activated, the grabbed name is the "displayed" one
					on error
						delay 0.1
					end try
				end repeat
				--name of menu items of menu 1
				--> {"Format texte enrichi", "Format texte", "Source du message brut"}
				#
				# The list is always displaying the names of menu items in this order
				# so there is no need to know the localized name of the menu item.
				#
				click menu item 1 of menu 1
			end tell # group 1 (of sheet 1).
			set theNameOfFileMessage to value of text field 1
			--name of buttons
			--> {"Enregistrer", "Nouveau dossier", "Annuler"}
			click button 1 # Click the button "Save"
		end tell # sheet 1
	end tell # System Events.Mail.window
	#
	# Loop to be sure that the TextEdit file is written on disk
	#
	tell application "System Events"
		repeat until exists disk item (ptd & theNameOfFileMessage)
			delay 0.1
		end repeat
	end tell # System Events
	
	return theNameOfFileMessage
end saveTheMessage

#=====

on saveAndPassAttachments(window_Name, name_FileMessage)
	local PrintDateTimeName, newFolderPath, path2FileMessage, wCreate, dName, errmsgg
	#
	# Attachment files weren't embedded !
	# Save the full set in a folder on the Desktop.
	#
	# Create a unique name for the temporary folder
	#
	if stampWithShell then
		set PrintDateTimeName to my dateTimeStamp()
	else
		if substractTimeToGMT then
			set PrintDateTimeName to my horoDateur((current date) - (time to GMT))
		else
			set PrintDateTimeName to my horoDateur(current date)
		end if # substractTimeToGMT
	end if # stampWithShell
	set newFolderPath to ptd & PrintDateTimeName # folder with attachments files.
	set path2FileMessage to ptd & name_FileMessage
	activate application "Mail"
	tell application "System Events"
		tell process "Mail"
			tell menu bar 1 to tell menu bar item 3 to tell menu 1
				--name of menu items
				(*{
01 - "Nouveau message",
02 - "Nouvelle fenêtre de visualisation",
03 - "Ouvrir Message",
04 - missing value,
05 - "Fermer",
06 - "Fermer toutes les fenêtres",
07 - "Enregistrer",
08 - "Enregistrer sous.",
09 - "Enregistrer comme modèle.",
10 - missing value,
11 - "Joindre des fichiers.",
12 - "Enregistrer les pièces jointes.", <<<<==================
13 - "Coup d'œil sur les pièces jointes.",
14 - missing value,
15 - "Ajouter un compte.",
16 - "Importer des boîtes aux lettres.",
17 - missing value,
18 - "Imprimer."
}*)
				click menu item 12 # Click menu item "Save attachments."
			end tell # menu bar 1 .
			
			tell window window_Name
				repeat
					delay 0.2
					if exists sheet 1 then exit repeat
				end repeat
				tell sheet 1
					keystroke "d" using {command down, shift down} # to save on the Desktop
					--name of buttons 
					--> {"Enregistrer", "Nouveau dossier", "Annuler"}
					click button 2 # Click the button "New Folder"
				end tell # sheet 1
			end tell # window window_Name
			
			repeat
				try
					delay 0.1
					set wCreate to (name of first window whose subrole is "AXSystemDialog")
					exit repeat
				end try
			end repeat
			tell window wCreate
				keystroke PrintDateTimeName # Type the name of the folder to create
				--name of buttons
				--> {"Créer", "Annuler"}
				click button 1 # Click the button "Create" (the new folder)
			end tell # window wCreate
			delay 0.2
			tell window window_Name to tell sheet 1
				--name of buttons
				--> {"Enregistrer", "Nouveau dossier", "Annuler"}
				click button 1 # Click the button "Save"
			end tell # window window_Name
		end tell # process
		
		repeat until (exists folder newFolderPath)
			delay 0.1
		end repeat
	end tell # System Events
	#
	# Step 3
	# Move the attachments from the temp folder to the rtfd document.
	# I dislike the Finder but to open a folder and copy its contents, there is no alternative
	#
	tell application "Finder"
		activate # REQUIRED to issue the keystrokes
		open folder newFolderPath
		delay 0.2 # The Finder is lazy so this delay may be useful
		
		tell application "System Events" to tell application process "Finder"
			keystroke "a" using {command down} # "Select All" (the files which were attached)
			delay 0.2
			keystroke "c" using {command down} #  "Copy" (to clipboard)
		end tell # System Events.
		delay 0.2
		close window PrintDateTimeName
	end tell # Finder
	
	try
		set dName to ""
		tell application "TextEdit"
			activate
			#
			# the dictionary states that the descriptor must be an alias but file is a valid one
			#
			open file path2FileMessage
			repeat
				try
					delay 0.25
					set dName to name of front document
					if dName = name_FileMessage then exit repeat
				end try
			end repeat
			#
			# The loop inserted a delay linked to the document size
			# Now, we are sure that the document is really open ;-)
			#
			tell front document
				make new paragraph at after last paragraph with data return & return & return
			end tell # Front document
			activate application "TextEdit" # REQUIRED to issue key code and keystroke
			tell application "System Events" to tell application process "TextEdit"
				#
				#  Move the cursor to then end of the document !
				#
				key code 125 using {command down}
				delay 0.4 # A delay is required here !
				#
				#  Paste the file(s) at the end of the document.
				#
				keystroke "v" using {command down}
			end tell # System Events.
			close document dName with saving
		end tell # TextEdit
	on error errmsg
		try
			tell application "TextEdit" to close document dName with saving
		end try
		tell application "SystemUIServer" to display dialog errmsg
	end try
	#
	# Use a shell script because from time to time, System Events fails to delete the folder.	
	#
	do shell script "rm -R " & quoted form of POSIX path of newFolderPath
	
end saveAndPassAttachments

--=====

on stampMessageFile(nameOf_FileMessage, the_Date, the_Ext)
	if useMessageDate then
		if substractTimeToGMT then
			my horoDateur(the_Date - (time to GMT))
		else
			my horoDateur(the_Date)
		end if # substractTimeToGMT
	else
		if stampWithShell then
			my dateTimeStamp()
		else if substractTimeToGMT then
			my horoDateur((current date) - (time to GMT))
		else
			my horoDateur(current date)
		end if #stampWithShell
	end if # useMessageDate
	set finalName to (text 1 thru -(1 + (count the_Ext)) of nameOf_FileMessage) & space & result & the_Ext
	
	tell application "System Events"
		set name of disk item (ptd & nameOf_FileMessage) to finalName
	end tell # System Events
	
	return finalName
end stampMessageFile

--=====

on moveMessageToFinalStorage(final_Name)
	local p2docs, nameFinalFolder, path2FinalFolder, finalName
	
	set p2docs to path to documents folder as text
	set nameFinalFolder to "final_storage Æ’"
	set path2FinalFolder to p2docs & nameFinalFolder
	tell application "System Events"
		if not (exists folder path2FinalFolder) then make new folder at end of folder p2docs with properties {name:nameFinalFolder}
	end tell # System Events
	
	quoted form of POSIX path of (ptd & final_Name)
	do shell script "mv " & result & space & quoted form of POSIX path of path2FinalFolder
end moveMessageToFinalStorage

#=====

on dateTimeStamp()
	if substractTimeToGMT then
		return (do shell script "date -u +%Y-%m-%d" & character id 160 & "%H%M%SZ")
	else
		return (do shell script "date +%Y-%m-%d" & character id 160 & "%H%M%SZ")
	end if # substractTimeToGMT
end dateTimeStamp

#=====

on horoDateur(une_date)
	tell une_date to return (((its year) * 10000 + (its month) * 100 + (its day)) as text) & "_" & text 2 thru -1 of ((1000000 + (its hours) * 10000 + (its minutes) * 100 + (its seconds)) as text)
end horoDateur

#=====

on activateGUIscripting()
	(* to be sure than GUI scripting will be active *)
	tell application "System Events"
		if not (UI elements enabled) then set (UI elements enabled) to true
	end tell
end activateGUIscripting

#=====

Yvan KOENIG (VALLAURIS, France) mardi 16 octobre 2012 18:28:18

Thanks, Yvan

I see that you adopted a GUI solution. Is the save command definitively borked under Mail in Mountain Lion.

Here is my (much more modest) script:)

set destinationFolder to "Test:"
tell application "Mail"
	set selected_messages to selection
	repeat with cont1 from 1 to count (selected_messages)
		set theAttachments to every mail attachment of item cont1 of selected_messages
		repeat with cont2 from 1 to count (theAttachments)
			set saveAttachment to item cont2 of theAttachments
			save saveAttachment in destinationFolder & name of saveAttachment with replacing
		end repeat
	end repeat
end tell

tell application "Finder" to open every file in folder destinationFolder using application file id "com.adobe.Acrobat.Pro"

Trouble is the save command throws an appleEvent handler failed error.

I’d prefer to avoid GUI scripting if at all possible, but if that is the only solution…

Every attempt (save GUI scripting - I have not tried it yet) I have made to deal with Mail attachments in Mountain Lion (through version 10.8.2) has utterly failed.

I filed a bug report last week, no response yet.

I think I have the answer.

There seems to be some sandboxing problem. When you change the destination folder to a subfolder in the Downloads folder (I had it on my Desktop previously), it all works magically.

set destinationFolder to "MacBook Pro:Users:macbook:Downloads:Acrobat:"
tell application "Mail"
	set selected_messages to selection
	repeat with cont1 from 1 to count (selected_messages)
		set theAttachments to every mail attachment of item cont1 of selected_messages
		repeat with cont2 from 1 to count (theAttachments)
			set saveAttachment to item cont2 of theAttachments
			save saveAttachment in (destinationFolder & name of saveAttachment) -- with replacing
		end repeat
	end repeat
end tell

tell application "Finder" to open every file in folder destinationFolder using application file id "com.adobe.Acrobat.Pro"

Using the Downloads folder is not a deal breaker for me, so I am going to run with this.

Cheers

… and for those who may have the same need … my final script:

set destinationFolder to "MacBook Pro:Users:macbookwork:Downloads:Acrobat:"
set listOfAttachments to {}
tell application "Mail"
	set selected_messages to selection
	repeat with cont1 from 1 to count (selected_messages)
		set theAttachments to every mail attachment of item cont1 of selected_messages
		repeat with cont2 from 1 to count (theAttachments)
			set saveAttachment to item cont2 of theAttachments
			set saveName to destinationFolder & name of saveAttachment
			save saveAttachment in saveName with replacing
			set listOfAttachments to listOfAttachments & (saveName as alias)
		end repeat
	end repeat
end tell

tell application "Finder" to open listOfAttachments using application file id "com.adobe.Acrobat.Pro"

Hello I tested the script (of course with an other destination folder).
Alas, the instruction :
save saveAttachment in saveName with replacing
fails with the message :

error “Erreur dans Mail : Le gestionnaire AppleEvent a échoué.” number -10000

I add that the attached file is a rtfd one.
Additional tests showed that your code is able to save flat files but fails when attachments are packages.

Yvan KOENIG (VALLAURIS, France) mardi 16 octobre 2012 21:16:48

At an asker request, the posted script was tested and behaved flawlessly upon a lot of different kinds of attachments.

About your bug report, be patient.
Today I received feedback related to a problem reported on 2011/09/30.
The problem was related to Lion annd the feedback asked if the problem is solved in 10.8.2 :rolleyes:

Yvan KOENIG (VALLAURIS, France) mardi 16 octobre 2012 21:19:53

Yvan, I guess the save command cannot handle rtfd. Hope it was working for you with other files.

Would be nice if the save command was “repaired” by Apple.

The script was written to help an user whose attachments are often packages/folders (rtfd are packages).
This is why I used GUI Scripting.

Your code behaved well when I used it with flat attachments, in fact I tested with rtf ones.

Of course it would be fine if the feature was fixed by Apple but I am accustomed to problems striking during years so I try to build scripts allowing to work on bugged apps :wink:

Yvan KOENIG (VALLAURIS, France) mercredi 17 octobre 2012 11:51:56

I am able to save PDF attachments to a subfolder of my Downloads folder; thank you very much for devising this workaround!

I have updated the bug report I filed with Apple to let them know as well.

Hello Craig

Are you speaking of one page or multipages PDFs ?

If I remember well what I got during my tests, the save message was able to save the one page PDFs as vell as RTF attachments but failed to pass multipages PDFs and packages / folders / zip files.

Yvan KOENIG (VALLAURIS, France) jeudi 25 octobre 2012 23:09:31

All the PDFs that I work with for this particular script are one- or two-page documents. As far as I can tell, all PDF attachments were successfully copied over to the appropriate subfolder as directed by the script.

Here is the pertinent code:

tell application "Mail"
	set The_Messages to every message in mailbox "Lab"
	set messageCount to (count The_Messages)
        my logit("PRS06 sees " & (messageCount as rich text) & " message(s)", "phxLog")
	if messageCount > 0 then
		try
			repeat with This_Message in The_Messages
				set receivedDate to date received of This_Message
				set today_folder to my CheckOrMakeFolder(receivedDate)
				set subjectText to (get This_Message's subject) as rich text
				set Report_name to ((every word of subjectText) as rich text) & ".pdf"
				set Report_file_Path to my checkFileName(today_folder, Report_name)
				set labReportFile to first mail attachment of This_Message
                                my logit(("Atch File:" & (labReportFile's name)), "phxLog")
				save labReportFile in Report_file_Path
				move This_Message to mailbox "LabSavedPDF"
			end repeat
		on error errText number errNum
			my logit(("Error: " & errText & errNum), "phxLog")
		end try
		delete every message in mailbox "Lab"
	else
		my logit("No Messages to process", "phxLog")
	end if
end tell
----------------------------------------------------------------------
on CheckOrMakeFolder(dateObject)
	set a to dateObject's short date string
	--display dialog a
	set aa to (my EnsureTwoDigitMonthString(a's word 1) & "." & a's word 2 & "." & a's word 3) as string
	set dp to (path to downloads folder as text) & "Cathouse:" & aa & ":" --Make new folder for Paystubs based on date received
	tell application "Finder" to if not (exists folder dp) then do shell script "mkdir -p " & quoted form of POSIX path of dp
	dp
end CheckOrMakeFolder
----------------------------------------------------------------------
to EnsureTwoDigitMonthString(mo_Number)
	set month_String to characters -2 thru -1 of ("0" & mo_Number)
	return month_String
end EnsureTwoDigitMonthString
----------------------------------------------------------------------
on checkFileName(fDir, fName) --This returns the entire path, not just the filename
	try
		set f to (fDir & fName) as alias
		set {name:Nm, name extension:Ex} to info for f
		if Ex is missing value then set Ex to ""
		if Ex is not "" then set Nm to text 1 thru ((count Nm) - (count Ex) - 1) of Nm
		set idx to 0
		repeat
			set idx to idx + 1
			set checkName to (fDir & Nm & "_" & (idx as string) & "." & Ex)
			try
				checkName as alias
			on error
				return checkName
			end try
		end repeat
	on error
		return (fDir & fName)
	end try
end checkFileName
----------------------------------------------------------------------
to logit(log_string, log_file)
	--display dialog log_string
	do shell script ¬
		"echo `date '+%Y-%m-%d %T: '`\"" & (log_string as text) & ¬
		"\" >> $HOME/Library/Logs/" & log_file & ".log"
end logit

Hello craig

I tried your script.

The source mailbox contained a single mail with two PDFs attached.
Only one attachment was stored in the dedicated folder

I made an other attempt with a mail entitled blahblahblah containing these three attachments :
2012-09-18T18.28.29.png, Tout savoir sur le courrier électronique.pages, Flip4Mac-User-Guide.pdf

The script issued an error and, in the dedicated folder I got a file entitled blahblahblah.pdf which can’t be open by Preview.

Here is the log report with the first mail :

tell application “Mail”
get every message of mailbox “* items to shift”
→ {message id 81057 of mailbox “* items to shift”}
end tell
tell current application
do shell script “echo date '+%Y-%m-%d %T: '"PRS06 sees 1 message(s)" >> $HOME/Library/Logs/phxLog.log”
→ “”
end tell
tell application “Mail”
get date received of message id 81057 of mailbox “* items to shift”
→ date “vendredi 26 octobre 2012 11:48:57”
end tell
tell current application
path to downloads folder as text
→ “Macintosh HD:Users:userAccount:Downloads:”
end tell
tell application “Finder”
exists folder “Macintosh HD:Users:userAccount:Downloads:Cathouse:26.10.2012:”
→ false
end tell
tell current application
do shell script “mkdir -p ‘/Users/userAccount/Downloads/Cathouse/26.10.2012/’”
→ “”
end tell
tell application “Mail”
get subject of message id 81057 of mailbox “* items to shift”
→ “avec deux pdf”
get mail attachment 1 of message id 81057 of mailbox “* items to shift”
→ mail attachment id “2” of message id 81057 of mailbox “* items to shift”
get name of mail attachment id “2” of message id 81057 of mailbox “* items to shift”
→ “20120824_115101_t4r1interieurrdcavenant50612068756800162701032011-copyright-bh copie 2.pdf”
end tell
tell current application
do shell script “echo date '+%Y-%m-%d %T: '"Atch File:20120824_115101_t4r1interieurrdcavenant50612068756800162701032011-copyright-bh copie 2.pdf" >> $HOME/Library/Logs/phxLog.log”
→ “”
end tell
tell application “Mail”
save mail attachment id “2” of message id 81057 of mailbox “* items to shift” in “Macintosh HD:Users:userAccount:Downloads:Cathouse:26.10.2012:avecdeuxpdf.pdf”
move message id 81057 of mailbox “* items to shift” to mailbox “LabSavedPDF”
end tell

Here is the log report with the second mail :

tell application “Mail”
get every message of mailbox “* items to shift”
→ {message id 81042 of mailbox “* items to shift”, message id 81041 of mailbox “* items to shift”, message id 81032 of mailbox “* items to shift”, message id 81035 of mailbox “* items to shift”, message id 81034 of mailbox “* items to shift”, message id 81033 of mailbox “* items to shift”}
end tell
tell current application
do shell script “echo date '+%Y-%m-%d %T: '"PRS06 sees 6 message(s)" >> $HOME/Library/Logs/phxLog.log”
→ “”
end tell
tell application “Mail”
get date received of message id 81042 of mailbox “* items to shift”
→ date “mardi 2 octobre 2012 15:14:32”
end tell
tell current application
path to downloads folder as text
→ “Macintosh HD:Users:userAccount:Downloads:”
end tell
tell application “Finder”
exists folder “Macintosh HD:Users:userAccount:Downloads:Cathouse:02.10.2012:”
→ true
end tell
tell application “Mail”
get subject of message id 81042 of mailbox “* items to shift”
→ “blahblahblah”
get mail attachment 1 of message id 81042 of mailbox “* items to shift”
→ mail attachment id “2.2” of message id 81042 of mailbox “* items to shift”
get name of mail attachment id “2.2” of message id 81042 of mailbox “* items to shift”
→ “2012-09-18T18.28.29.png”
end tell
tell current application
do shell script “echo date '+%Y-%m-%d %T: '"Atch File:2012-09-18T18.28.29.png" >> $HOME/Library/Logs/phxLog.log”
→ “”
end tell
tell application “Mail”
save mail attachment id “2.2” of message id 81042 of mailbox “* items to shift” in “Macintosh HD:Users:userAccount:Downloads:Cathouse:02.10.2012:blahblahblah.pdf”
move message id 81042 of mailbox “* items to shift” to mailbox “LabSavedPDF”
get date received of message id 81041 of mailbox “* items to shift”
→ date “mardi 2 octobre 2012 15:14:32”
end tell
tell current application
path to downloads folder as text
→ “Macintosh HD:Users:userAccount:Downloads:”
end tell
tell application “Finder”
exists folder “Macintosh HD:Users:userAccount:Downloads:Cathouse:02.10.2012:”
→ true
end tell
tell application “Mail”
get subject of message id 81041 of mailbox “* items to shift”
→ “blahblahblah”
end tell
tell current application
info for alias “Macintosh HD:Users:userAccount:Downloads:Cathouse:02.10.2012:blahblahblah.pdf” given «class Krtn»:{name:“Nm”, name extension:“Ex”}
→ {name:“blahblahblah.pdf”, creation date:date “vendredi 26 octobre 2012 11:41:00”, modification date:date “vendredi 26 octobre 2012 11:41:00”, size:22271, folder:false, alias:false, package folder:false, visible:true, extension hidden:true, name extension:“pdf”, displayed name:“blahblahblah.pdf”, default application:alias “Macintosh HD:Applications:Preview.app:”, kind:“Portable Document Format (PDF)”, file type:“file creator:“type identifier:“com.adobe.pdf”, locked:false, busy status:false, short version:””, long version:“”}
end tell
tell application “Mail”
get mail attachment 1 of message id 81041 of mailbox “* items to shift”
→ mail attachment id “2.2” of message id 81041 of mailbox “* items to shift”
get name of mail attachment id “2.2” of message id 81041 of mailbox “* items to shift”
→ “2012-09-18T18.28.29.png”
end tell
tell current application
do shell script “echo date '+%Y-%m-%d %T: '"Atch File:2012-09-18T18.28.29.png" >> $HOME/Library/Logs/phxLog.log”
→ “”
end tell
tell application “Mail”
save mail attachment id “2.2” of message id 81041 of mailbox “* items to shift” in “Macintosh HD:Users:userAccount:Downloads:Cathouse:02.10.2012:blahblahblah_1.pdf”
move message id 81041 of mailbox “* items to shift” to mailbox “LabSavedPDF”
get date received of message id 81032 of mailbox “* items to shift”
→ date “mardi 2 octobre 2012 11:10:37”
end tell
tell current application
path to downloads folder as text
→ “Macintosh HD:Users:userAccount:Downloads:”
end tell
tell application “Finder”
exists folder “Macintosh HD:Users:userAccount:Downloads:Cathouse:02.10.2012:”
→ true
end tell
tell application “Mail”
get subject of message id 81032 of mailbox “* items to shift”
→ “one package numbers file”
get mail attachment 1 of message id 81032 of mailbox “* items to shift”
→ mail attachment id “1” of message id 81032 of mailbox “* items to shift”
get name of mail attachment id “1” of message id 81032 of mailbox “* items to shift”
→ “en-tête graphique.numbers”
end tell
tell current application
do shell script “echo date '+%Y-%m-%d %T: '"Atch File:en-tête graphique.numbers" >> $HOME/Library/Logs/phxLog.log”
→ “”
end tell
tell application “Mail”
save mail attachment id “1” of message id 81032 of mailbox “* items to shift” in “Macintosh HD:Users:userAccount:Downloads:Cathouse:02.10.2012:onepackagenumbersfile.pdf”
→ error number -10000
end tell
tell current application
do shell script “echo date '+%Y-%m-%d %T: '"Error: Erreur dans Mail : Le gestionnaire AppleEvent a échoué.-10000" >> $HOME/Library/Logs/phxLog.log”
→ “”
end tell
Résultat :
“”

Given that, I’m a bit skeptical.

Yvan KOENIG (VALLAURIS, France) vendredi 26 octobre 2012 12:02:53

Yvan:

Understood. My script is designed specifically for laboratory reports that get emailed to me every day. Each email has a single attachment, which is why the script is only concerned with the first attachment:

set labReportFile to first mail attachment of This_Message

Since every attachment is a PDF document already, I simply rename the attached file (based on information in the subject line) and append the .pdf file extension:

set subjectText to (get This_Message's subject) as rich text
               set Report_name to ((every word of subjectText) as rich text) & ".pdf"

I believe those are the most likely portions of the script that would be giving you problems.

Good luck,

Hello Craig

I edited the main code to accomodate it to messages with multiple attachments


tell application "Mail"
	set The_Messages to every message in mailbox "* items to shift"
	set messageCount to (count The_Messages)
	my logit("PRS06 sees " & (messageCount as rich text) & " message(s)", "phxLog")
	if messageCount > 0 then
		try
			repeat with This_Message in The_Messages
				set receivedDate to date received of This_Message
				set today_folder to my CheckOrMakeFolder(receivedDate)
				set subjectText to (get This_Message's subject) as rich text
				set Report_name to ((every word of subjectText) as rich text)
				set nb_Attachments to count mail attachments of This_Message
				repeat with k from 1 to nb_Attachments
					set labReportFile to mail attachment k of This_Message
					set name_attachment to labReportFile's name
					set Report_file_Path to my checkFileName(today_folder, Report_name & "_" & name_attachment)
					my logit(("Atch File:" & name_attachment), "phxLog")
					save labReportFile in Report_file_Path
				end repeat
				move This_Message to mailbox "LabSavedPDF"
			end repeat
		on error errText number errNum
			my logit(("Error: " & errText & errNum), "phxLog")
		end try
		--delete every message in mailbox "Lab"
	else
		my logit("No Messages to process", "phxLog")
	end if
end tell

and of course got the « logical » behavior : flatfiles are correctly passed but packages aren’t.

The AppleScript save attachment code is really odd.
As GUIScripting is able to save attached packages, I guess that we aren’t facing a feature but a true bug.

Yvan KOENIG (VALLAURIS, France) vendredi 26 octobre 2012 17:07:32

Hi there

I am reverting in this thread as I need a little help.

As the above thread shows, we managed to get a script working to save attachments:

set destinationFolder to "MacBook Pro:Users:macbookwork:Downloads:Acrobat:"
set listOfAttachments to {}
tell application "Mail"
   set selected_messages to selection
   repeat with cont1 from 1 to count (selected_messages)
       set theAttachments to every mail attachment of item cont1 of selected_messages
       repeat with cont2 from 1 to count (theAttachments)
           set saveAttachment to item cont2 of theAttachments
           set saveName to destinationFolder & name of saveAttachment
           save saveAttachment in saveName with replacing ######## fails
           set listOfAttachments to listOfAttachments & (saveName as alias)
       end repeat
   end repeat
end tell

I am looking at adapting this so it works as an applescript rule under Mail. By that, I mean that I want my Mail rule to save all attachments if the subject contains “XXXX”. Under the Mail rules, I can have an applescript run when the subject in a received email meets the specified condition. But how to I have the script then act on the email just received? I do not need a loop, just need to act on the received email in question.

Any clues?

Would help too if the saving process did not overwrite any duplicate file. Any quick suggestion on how to achieve that would be good too:)