With a lot of help I managed to get a script working that saves emails as PDF’s and attachments.
When I upgraded to Lion I now get an error when the script tries to save the attachment “AppleEvent Handler failed.” number -10000.
This is the script.
any suggestions greatly appreciated
--This script is underdevelopment 7/13/2011 to take a selected email message save it as a PDF file and then save any attachments to the same folder with the file name given to the email plus name of attachment. Now numners files sequentially so rather tahn 1,11 we have 1,2 etc but willrun into a problem when it gets to 9
global listOfFiles, filecount, Subject_, destinationFolder, d
activate application "Finder"
tell application "Finder"
set destinationFolder to (choose folder)
set listOfFiles to the name of every file in destinationFolder
set filecount to count every item in listOfFiles
end tell
activate application "Mail" --Brings window to the front
tell application "Mail"
set themsg to selection
if (count of themsg) is less than 1 then --Makes sure a message has been selected in mail box
display dialog "Please select a message in Mail before running this script."
else
set themsg to item 1 of themsg
set theMsgCount to {}
tell themsg
set Subject_ to subject of item 1 of themsg
set Sender_ to sender of item 1 of themsg
set Recipients_ to to recipients
set Recipients_ to address of first recipient of item 1 of themsg
set Sender_ to extract name from Sender_
set brkpos to offset of "@" in Recipients_ --Finds position of start of URL in email address
--display dialog "Break " & brkpos
set Recipients_ to characters 1 through (brkpos - 1) of Recipients_
display dialog "Sent to " & Recipients_ & return & "Sent by " & Sender_
set theMsgCount to mail attachments of themsg
set theMsgCount to count every mail attachment of themsg
set Subject_ to text returned of (display dialog "From " & Sender_ & return & "Proposed file name is in the box" & return & "Select OK or start typing to erase and change" & return & "and then Select OK" buttons {"OK", "Change"} default button "OK" default answer Subject_)
set Subject_ to my FixFileName(Subject_) --Calls handler to strip bad characters
set Subject_ to my Filename(Subject_) --Calls handler to check for duplicate names
activate application "Mail" --Brings window to the front
end tell
my FileasPDF() --Calls handler to process the save part of routine
set AttachNumber to 0
repeat with att from 1 to count every mail attachment of themsg
set AttachNumber to AttachNumber + 1
set att to name of mail attachment att of themsg as string
set att2 to (((count (every character in Subject_))) - 4)
--set att2 to characters 1 thru att2 of Subject_
set att3 to characters -1 thru -4 of att --Gets last 4 characters of attachment name
--display dialog Subject_ & " Attach" & AttachNumber & att3 as string
set attachname to Subject_ & " Attach" & AttachNumber & att3 as string
set destinationFolder to destinationFolder as string
save mail attachment att of themsg in (POSIX path of destinationFolder) & attachname
end repeat
set check to the button returned of (display dialog "Delete " & return & Subject_ & return & " from Mail " buttons {"Yes", "No"} default button 1)
if check = "Yes" then
delete themsg
else
set check to the button returned of (display dialog "Standard proceduer is to flag the message to show it has been saved" & return buttons {"yes", "No"} default button 1)
if check = "Yes" then
tell application "Mail"
activate
tell application "System Events"
tell process "mail"
keystroke "l" using {command down, shift down}
end tell
end tell
end tell
end if
end if
end if
end tell
------------------------------------------
on FileasPDF()
tell application "System Events"
tell process "Mail"
keystroke "p" using command down
repeat until exists sheet 1 of window 1
delay 0.2
end repeat
tell sheet 1 of window 1
click menu button "PDF"
repeat until exists menu 1 of menu button "PDF"
delay 0.02
end repeat
click menu item "Save as PDF." of menu 1 of menu button "PDF"
end tell
repeat until exists window "Save"
delay 0.2
end repeat
tell window "Save"
keystroke "g" using {command down, shift down}
repeat until exists sheet 1
delay 0.2
end repeat
tell sheet 1
--Subject_Added Peter to test how to pass file name
set value of text field 1 to POSIX path of destinationFolder & "/" & Subject_
click button "Go"
end tell
repeat while exists sheet 1
delay 0.2
end repeat
click button "Save"
end tell
end tell
end tell
end FileasPDF
-----------------------------------------
on FixFileName(str) --Deletes characters that cannot be used in file names
--display dialog "Check Filename for duplicates"
--display dialog "Fixed str " & str
set fixed_string to {}
set bad_char to {":", "/"}
repeat with c from 1 to (count every character in str)
if bad_char contains (character c of str) then
set end of fixed_string to "-"
else
set end of fixed_string to (character c of str)
end if
end repeat
fixed_string as string
set str to fixed_string
end FixFileName
---------------------------------------
on Filename(str) --Has to iterate through every file name twice
tell application "Finder"
set fileCheck to str & ".pdf" --assigns to fileCheck name passed by handler (str) and adds the PDF extentsion
repeat with lof1 from 1 to filecount --1st Iteration will be fileCheck 2nd fileCheck1 3rd fileCheck2 etc
repeat with lof from 1 to filecount --once for each file in listoffiles
if fileCheck as string = item lof of listOfFiles as string then --fileCheck file name is same as one in the list of files
set str to str as string
try --to see if fileCheck has as last character a number
if (character -1 of str) as number ≥ 1 then --checks if last character in filecheck is a number
set filecheck2 to (length of str) - 1 --no of characters in fileCheck excluding the number
set fileCheck3 to (character -1 of str) + 1 --increase vaue last number in fileCheck
set str to (characters 1 thru filecheck2) of str & fileCheck3 --resets str by concatenating original string plus number
end if --str now has name plus a number
on error --file name and proposed file matched but last char not number therefore add number
set str to str & 1
end try
set fileCheck to str & ".PDF" --resets fileCheck to new string with extension
exit repeat --match found exits to next loop
end if
--no match goes to next iteration this repeat to check entire list of files against filecheck
end repeat --goes to next iteration of first repeat
end repeat
set Subject_ to str
end tell
end Filename
-----------------------------------------
on ParseName(str) --Takes attachment name and strips extension not in use
set d to AppleScript's text item delimiters
set AppleScript's text item delimiters to "."
set str to every text item of str as list
set AppleScript's text item delimiters to " "
set str to every text item of str as text
set strcnt to count of words in str
set str3 to {}
set ext1 to last word of str
if strcnt is greater than 2 then
repeat with n from 1 to strcnt - 1
set str2 to word n of str
set str3 to str3 & str2
end repeat
else
set str3 to word 1 of str
display dialog "In Parse Name " & str3
end if
set str3 to str3 as string
set str to my replaceChars(str3)
end ParseName
---------------------------------
on replaceChars(thisText) --Removes spaces not in use called from ParseName
set d to AppleScript's text item delimiters
set AppleScript's text item delimiters to the " "
set the itemList to every text item of thisText
set AppleScript's text item delimiters to the ""
set thisText to the itemList as string
set AppleScript's text item delimiters to ""
return thisText
set AppleScript's text item delimiters to d
end replaceChars
It is puzzling.
I too am running Lion. I tried your script and it worked perfectly.
It sounds like there is a problem with your Mail, maybe something is set wrong…
I have repaired permissions and i will do it again. Thanks for taking the time to reply what settings in mail are you thinking of?
Well, your script uses keystroke commands, of which can be changed, whether consciously or accidentally.
But it still seems very odd…
Do you know which part of the script is having the problem? That would help!
To find when an error occurs in a script click the “Events” button at the bottom of AppleScript Editor, next to the Replies button.
Hi L
It happens when it goes to save the attachment saves the email itself OK.
This is the bit of code where it goes pear shape.
set AttachNumber to 0
repeat with att from 1 to count every mail attachment of themsg
set AttachNumber to AttachNumber + 1
set att to name of mail attachment att of themsg as string
set att2 to (((count (every character in Subject_))) - 4)
--set att2 to characters 1 thru att2 of Subject_
set att3 to characters -1 thru -4 of att --Gets last 4 characters of attachment name
--display dialog Subject_ & " Attach" & AttachNumber & att3 as string
set attachname to Subject_ & " Attach" & AttachNumber & att3 as string
--set destinationFolder to destinationFolder as string
save mail attachment att of themsg in (POSIX path of destinationFolder) & attachname
end repeat
And this is the event report.
get POSIX path of alias “My Passport:Documents:Quantum Strategies:Correspondence:2011 :Peake:”
→ “/Volumes/My Passport/Documents/Quantum Strategies/Correspondence/2011 /Peake”
set value of text field 1 of sheet 1 of window “Save” of process “Mail” to “/Volumes/My Passport/Documents/Quantum Strategies/Correspondence/2011 /Peake/drill1”
click button “Go” of sheet 1 of window “Save” of process “Mail”
→ button “Go” of sheet 1 of window “Save” of application process “Mail”
exists sheet 1 of window “Save” of process “Mail”
→ false
click button “Save” of window “Save” of process “Mail”
→ button “Save” of window “Save” of application process “Mail”
end tell
tell application “Mail”
count every mail attachment of message id 259 of mailbox “OIL/Peake” of account “MobileMe”
→ 1
get name of mail attachment 1 of message id 259 of mailbox “OIL/Peake” of account “MobileMe”
→ “A-51 Y-Sd 7-11.doc”
save mail attachment “A-51 Y-Sd 7-11.doc” of message id 259 of mailbox “OIL/Peake” of account “MobileMe” in “/Volumes/My Passport/Documents/Quantum Strategies/Correspondence/2011 /Peake/drill1 Attach1.doc”
→ error number -10000
Result:
error “Mail got an error: AppleEvent handler failed.” number -10000
As you can see the first save which goes through the handler “FileasPDF” works.
I have repaired permissions also dragged mail of of the library and restarted it again. I do not have any extensions on Mail.
Interestingly I had set up the applescript to run through Spark so I could hot key it. The key combination is ALT +1 when I use that I do not get the appleEvent handler failed but it does not complete the script.
This appears in the Terminal log which I assume is related.
7/28/11 1:42:23.010 PM Mail: An exception was thrown during execution of an NSScriptCommand…
That’s why it worked for me- The message I ran it on didn’t have an attachment!!!
I am still trying to fix it, but have narrowed down to one certain line of code.
When this line of your script is run:
save mail attachment att of themsg in (POSIX path of destinationFolder) & attachname
The error returned is “AppleEvent Handler failed.”
But if that line is run like this:
save mail attachment (att of themsg) in (POSIX path of destinationFolder) & attach name
Or like this:
set p to mail attachment att of themsg
save mail attachment pg in (POSIX path of destinationFolder) & attachname
The error is “Mail got an error: Can’t make att of message id 109 of mailbox "INBOX" of account "Yahoo!" into type specifier.”
I looked in Mail’s scripting dictionary, and mail attachments do respond to the save command.
The save command includes the “as” property, which needs a native file type, but I do not know if that is required to save something.
EDIT It seems mail attachments can’t be called by name…
Hi Layne
Thanks for all your help.
I think the problem is to do with Lion as from 7/13/2011 it worked just fine until I upgraded to Lion and presto no attachment save. I had not specified the file type but as you can see I had stripped the extension and added that to a new attachment name. So if was a word document it would have doc extension a PDF file then PDF and so on.
Peter
Peter,
I looked on another thread and StefanK was having the same problem. There has tobe a bug with the “save” command.
Guess we have to wait for Apple to fix that.
do you think opening the attachment then using the save as command might help?
Peter
Using GUI scripting like the first part of your script would probably work.
Do you have an application such as UIElementsInspector?
Not sure I understand when you say GUI like the beginning of the script, as I said at the oust I have had a lot of help putting this together and was very happy when it was working. guess I should have known better than to upgrade.
Anyway did not have the UIElementsInspecotor so downloaded it. When I hover over a mail it gives me details of that message but cannot see anything about the attachment , how did you think I could use this please?
GUI scripting, as in
tell application "System Events"
tell process "Mail"
click menu item 1 of menu 4 of menu bar 1
end tell
end tell
Use UIElementsInspector to find the hierarchy of UI items, such as a button or a menu item. What i mention was find a way to save an attachment manually and then lay down the code.Here is a GUI tutorial.
I must be getting more stupid by the minute I think I figured out what you meant and adapted your scrip to do something simple like open the message as follows.
tell application "Mail"
set themsg to selection
if (count of themsg) is less than 1 then --Makes sure a message has been selected in mail box
display dialog "Please select a message in Mail before running this script."
else
tell application "System Events"
tell process "Mail"
click menu item 4 of menu 3 of menu bar 1
end tell
end tell
activate "Mail"
end if
end tell
It runs OK but does not open the message. The event panel shows the following.
tell application “Mail”
get selection
→ {message id 259 of mailbox “OIL/Peake” of account “MobileMe”}
end tell
tell application “System Events”
click menu item 4 of menu 3 of menu bar 1 of process “Mail”
→ menu item “Open Message” of menu “File” of menu bar item “File” of menu bar 1 of application process “Mail”
end tell
tell application “Mail”
activate
end tell
Thank you again for your help. If opening would work I see what you mean as menu item 11 is save attachment.
Peter
Got his from the GUI tutorial you provided and adapted it open messages. Which works just fine.
-this from http://www.macosxautomation.com/applescript/uiscripting/index.html with slight adaptation opens mail message ok next step to save attachments
my do_menu("Mail", "File", "Open Message")
on do_menu(app_name, menu_name, menu_item)
try
-- bring the target application to the front
tell application app_name
activate
end tell
tell application "System Events"
tell process app_name
tell menu bar 1
tell menu bar item menu_name
tell menu menu_name
click menu item menu_item
end tell
end tell
end tell
end tell
end tell
return true
on error error_message
return false
end try
end do_menu
When I change “Open message” to “Save Attachments” this is what I get
tell application “Mail”
activate
end tell
tell application “System Events”
click menu item “Save Attachments” of menu “File” of menu bar item “File” of menu bar 1 of process “Mail”
→ error number -1728 from «class menI» “Save Attachments” of «class menE» “File” of «class mbri» “File” of «class mbar» 1 of «class prcs» “Mail”
end tell
Result:
false
Guess it is going to be more difficult than I thought. thanks
Peter
I once had a similar error. Try:
tell application "Mail"
activate
end tell
tell application "System Events"
tell process "Mail"
click menu item "Save Attachments" of menu "File" of menu bar 1
end tell
end tell
No good with that I am afraid. This is the result.
tell application “Mail”
activate
end tell
tell application “System Events”
click menu item “Save Attachments” of menu “File” of menu bar 1 of process “Mail”
→ error number -1728 from «class menI» “Save Attachments” of «class menE» “File” of «class mbar» 1 of «class prcs» “Mail”
Result:
error “System Events got an error: Can’t get menu item "Save Attachments" of menu "File" of menu bar 1 of process "Mail".” number -1728 from menu item “Save Attachments” of menu “File” of menu bar 1 of process “Mail”
I got the script to work. Our mistake was forgetting that the three periods at the end of “Save Attachments…” are actually part of the title…
Add this script to yours:
set theFolder to (choose folder) --choose folder to save attachments (i did this just so my script would work)
tell application "Mail" to activate
tell application "System Events"
tell process "Mail"
--here's where your script went slightly wrong. The three periods after "Save Attachments" are part of the name
click menu item "Save Attachments." of menu "File" of menu bar 1
delay 0.2
keystroke "g" using {command down, shift down} --open go to folder sheet
delay 0.2
tell sheet 1 of sheet 1 of window 1
set value of text field 1 to POSIX path of theFolder --the go to folder text field
end tell
tell sheet 1 of window 1 --this automatically switches to the first sheet again
click button "Save" -- the button on the first sheet
end tell
end tell
end tell
(* You can then replace the shaky part of your original script with this ^^^^^ *)
Hi Layne
sorry I did not reply yesterday but I still cannot get this to work I get an error message. that Mail cannot save the message. When I increase the delay after keystroke “g” using etc I see a go to folder box and the text is ~/Library/Preferences/ByHost/ which I do not understand. when I have a look in that folder there is nothing in it created today.
The log looks like this.
tell application “AppleScript Editor”
choose folder
→ alias “Macintosh HD:Users:mitch:Desktop:MailTest:”
end tell
tell application “Mail”
activate
end tell
tell application “System Events”
click menu item “Save Attachments.” of menu “File” of menu bar 1 of process “Mail”
→ menu item “Save Attachments.” of menu “File” of menu bar item “File” of menu bar 1 of application process “Mail”
keystroke “g” using {command down, shift down}
set value of text field 1 of sheet 1 of sheet 1 of window 1 of process “Mail” to POSIX path of alias “Macintosh HD:Users:mitch:Desktop:MailTest:”
click button “Save” of sheet 1 of window 1 of process “Mail”
→ button “Save” of sheet 1 of window “Peake ” MobileMe (62 messages)” of application process “Mail”
end tell
Result:
button “Save” of sheet 1 of window “Peake ” MobileMe (62 messages)” of application process “Mail” of application “System Events”
If your computer is slower (more applications running) then there will need to be a longer delay.
As for the error, I am not sure what you mean. You said there was an error saving a message, but the script saves the attachments of a message. If there are no attachments, there is an error.
As for the folder go-to box it doesn’t matter what is says; the script fills it with the appropriate path. Don’t worry about the strange folder. There are a lot of hidden odd folders on your comouter.
Sorry not clear it says it cannot save the attachment I did make sure the message I was testing had an attachment.
.
Just reloaded your script as I had been modifying the original one and now get a new error.
tell application “AppleScript Editor”
choose folder
→ alias “Macintosh HD:Users:mitch:Desktop:MailTest:”
end tell
tell application “Mail”
activate
end tell
tell application “AppleScript Editor”
«event prcsclic» «class menI» “Save Attachments.” of «class menE» “File” of «class mbar» 1 of «class prcs» “Mail”
→ menu item “Save Attachments.” of menu “File” of menu bar item “File” of menu bar 1 of application process “Mail”
«event prcskprs» “g” given «class faal»:{command down, shift down}
set «class valL» of «class txtf» 1 of «class sheE» 1 of «class sheE» 1 of window 1 of «class prcs» “Mail” to «class posx» of alias “Macintosh HD:Users:mitch:Desktop:MailTest:”
→ error number -1728 from «class posx» of alias “Macintosh HD:Users:mitch:Desktop:MailTest:”
Result:
error “System Events got an error: Can’t set POSIX path of alias "Macintosh HD:Users:mitch:Desktop:MailTest:" to POSIX path of alias "Macintosh HD:Users:mitch:Desktop:MailTest:".” number -10006 from POSIX path of alias “Macintosh HD:Users:mitch:Desktop:MailTest:”
I will repair permissions and start again.
thanks
Peter