Want to highlight a helpful answer? Upvote!

Did someone help you, or did an answer or User Tip resolve your issue? Upvote by selecting the upvote arrow. Your feedback helps others! Learn more about when to upvote >

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

Applescript to save mail attachments failing in Mountain Lion

Hi,


I got Mountain Lion the other day and found that Mail.app still has a bug whereby it can corrupt messages on an Exchange server sometimes when removing attachments.


To that end I'm trying to learn Applescript to do several things;

1- Create a script, run through a rule, to save attachments.

2- Create a script to move a message to a local folder, remove the attachments and then move the message back into my exchange inbox.


I'm afraid I'm falling at the first hurdle. I wrote a script that works as a stand-alone script, but the minute I put in the mail rule handler it ceases to work.


Initially it was failing because 'path tohome folder' was returning a sandboxed path (Users/me/Library/Containers/com.apple.mail/Data).


I worked around that with a bit of sed to strip out the extra path. Not sure if that was the right thing to do, but it was 2am...


After doing that the following script seemed to work. However today I am finding that it gets as far as trying to save the file and fails- despute having the correct attachment name and path name.


Can anyone tell me why the save isn't happening? It definitely gets into the 'try' loop and fails at the point it tries to save.


using terms from application "Mail"

on perform mail action with messagestheselectedMessages

-- get the home folder

set sandboxedhomeFolder to (path tohome folder)

-- strip out the stupid sandboxed rubbish in the folder name

set homeFolder to (do shell script "echo " & sandboxedhomeFolder & " | sed 's/Librar.*//'")

-- add on the desired attachments folder

set attachmentsFolder to homeFolder & "Documents:3 Month Holding Folder"

tell application "Mail"

repeat with theMessage in theselectedMessages

-- get the sender's name

set senderName to extract name fromtheMessage's sender

repeat with theAttachment in theMessage's mail attachments

set originalName to name of theAttachment

-- name the file with the sender's name as well as the attachment name

set savePath to attachmentsFolder & ":" & senderName & "-" & originalName

try

-- Save the attachment

-- ** the code seems to get this far and then doesn't actually save the

-- ** file in the location indicated

savetheAttachmentinsavePath

end try

end repeat

end repeat

end tell

end perform mail action with messages

end using terms from

Posted on Jul 27, 2012 9:42 AM

Reply
52 replies

Aug 22, 2012 9:27 PM in response to Screaming.Pict

I have a similar problem, and can't figure out how to implement the solution into my own script. Here's the basis of what I'm using, and it fails:


(*

Just trying to get the attachments to save to somewhere.

*)


using terms fromapplication "Mail"


onperform mail action with messagesselectedMsgs


tellapplication "Mail"

repeat with counter from 1 to (count of selectedMsgs)


setmsgtoitemcounterofselectedMsgs

set theAttachments to (count of mail attachments of msg)

say "There are " & theAttachments & " attachments."


repeatwithattach_counterfrom 1 totheAttachments


setthefilenametoSaveAttachments(nameofmail attachmentattach_counterofmsg)


--set theid to id of mail attachment attach_counter of msg--I don't think you need this.


savemail attachmentattach_counterofmsginthefilename--The full path is returned from the handler, and the file is saved.


endrepeat


endrepeat


endtell


endperform mail action with messages

endusing terms from

-------------

onSaveAttachments(x) --This creates the path to the documents folder to save the attachment, then adds the name of the file.

set dp to (path to documents folder as Unicode text) & x


returndp

endSaveAttachments


-- If run as an ordinary script, instead of directly from the Scripts

-- menu, it will call the default handler instead.

using terms fromapplication "Mail"


onrun

tell application "Mail" to set sel to selection


tellmetoperform mail action with messages (sel)


endrun

endusing terms from

Aug 23, 2012 10:00 AM in response to biggerfish

So what I needed to do was collect attachments sent to a specific inbox, save the attachment and combine the attachements (pdf) into one large pdf. Here's the automator process which I saved as a service.


service receives no input in mail


get selected mail mailboxes

get selected mailboxes


get attachments from mail messages


combine PDF pages

combine by appending


name single item

name single item

name: baseline only to: blahblahblah


move finder items

to: destination folder


get specified finder items

temp (the temp directory that we set up at the beginning)


move finder items to trash

Sep 9, 2012 12:59 PM in response to Screaming.Pict

This script works but i need to be able to have it rename the files a they come in and add a sequencial numbering. I can put a name in the subject line of the emails. What do I add to this script?


using terms from application "Mail"

on perform mail action with messages matching_messages

--set report_type to ":throughput"

set folder_path to "Macintosh HD:Users:jkinder:Downloads:Mail Attach" -- & report_type

set file_path to (folder_path & ":")

tell application "Mail"

set the num_messages to the count of matching_messages

-- display dialog "0. Found " & num_messages & " messages!"

repeat with i from 1 to the num_messages

set this_message to (item i of matching_messages)

tell this_message

-- display dialog "1. Processing \"" & (subject of this_message) & "\" which has " & (count of mail attachments of this_message) & " attachment(s)."

repeat with z from 1 to the (count of mail attachments of this_message)

set theAttachment to item z of (mail attachments of this_message)

-- display dialog "2. Got attachment " & (name of theAttachment)

with timeout of 10 seconds

set myname to do shell script "whoami"

-- display dialog "3.Trying to save " & (name of theAttachment) & " to the path " & (file_path & (name of theAttachment) as string) & " as user " & myname

try

save theAttachment in (file_path & name of theAttachment)

on error number errNum

display dialog "ERROR: problem saving file, ernum: " & errNum

error number -128 --User Ended error; this should stop script execution

end try

end timeout

end repeat

end tell

end repeat

end tell

end perform mail action with messages

end using terms from



Thank you, JD

Sep 10, 2012 9:02 AM in response to JerryDale

JD are you using Mountain Lion and the newest version of Mail? I can't get your script to run on my machine at all - I still get the -10000 error trying to save attachments from Mail.


tellapplication "Mail"


set folder_path to "Macintosh HD:Users:richg:BigPromotions:2012 ClientProjects:SavedAtt"


setfile_pathto (folder_path & ":")

set matching_messages to item 1 of (get selection)


setthenum_messagestothecountofmatching_messages


display dialog "0. Found " & num_messages & " messages!"


repeat with i from 1 to the num_messages


setthis_messageto (itemiofmatching_messages)


tellthis_message


display dialog "1. Processing \"" & (subject of this_message) & "\" which has " & (count of mail attachments of this_message) & " attachment(s)."


repeat with z from 1 to the (count of mail attachments of this_message)


settheAttachmenttoitemzof (mail attachmentsofthis_message)


display dialog "2. Got attachment " & (name of theAttachment)



withtimeoutof 30 seconds

set myname to do shell script "whoami"

display dialog "3.Trying to save " & (name of theAttachment) & " to the path " & (file_path & (name of theAttachment) as string) & " as user " & myname

try


savetheAttachmentin (file_path & nameoftheAttachment)

on error number errnum

display dialog "ERROR: problem saving file, ernum: " & errnum


errornumber -128 --User Ended error; this should stop script execution

end try


endtimeout


endrepeat


endtell


endrepeat

endtell


How do I save the attachment "as a user"?

Sep 10, 2012 10:04 AM in response to Screaming.Pict

Hi, Yes i am on Mountain Lion and have been working on setting this up. The script works on my computer but it saves all the attachments as the same name so it overright the last image. How do I tell it to rename the image with what is in the subject line and add the date and time stamp? Here is the script again:


using terms from application "Mail"

on perform mail action with messages matching_messages

--set report_type to ":throughput"

set folder_path to "Macintosh HD:Users:jkinder:Downloads:Mail Attach" -- & report_type

set file_path to (folder_path & ":")

tell application "Mail"

set the num_messages to the count of matching_messages

-- display dialog "0. Found " & num_messages & " messages!"

repeat with i from 1 to the num_messages

set this_message to (item i of matching_messages)

tell this_message

-- display dialog "1. Processing \"" & (subject of this_message) & "\" which has " & (count of mail attachments of this_message) & " attachment(s)."

repeat with z from 1 to the (count of mail attachments of this_message)

set theAttachment to item z of (mail attachments of this_message)

-- display dialog "2. Got attachment " & (name of theAttachment)

with timeout of 10 seconds

set myname to do shell script "whoami"

-- display dialog "3.Trying to save " & (name of theAttachment) & " to the path " & (file_path & (name of theAttachment) as string) & " as user " & myname

try

save theAttachment in (file_path & name of theAttachment)

on error number errNum

display dialog "ERROR: problem saving file, ernum: " & errNum

error number -128 --User Ended error; this should stop script execution

end try

end timeout

end repeat

end tell

end repeat

end tell

end perform mail action with messages

end using terms from


thanks

Oct 14, 2012 11:14 PM in response to Screaming.Pict

I think you're hitting the same wall as people are describing in this other thread, where I also posted the result of my debugging: https://discussions.apple.com/thread/4186119?answerId=19501549022#19501549022


In short: there seems to be a bug in 10.8 Mail.app. The Applescript rules get incoming POP messages in an invisible "incoming messages" mailbox, but when Applescript tries to iterate over the mailbox messages, the mailbox is empty. And that's because the mail is already in your inbox, not in the "incoming mesages" mailbox.


Feel free to post a bug report to Apple: http://www.apple.com/feedback/macosx.html

Oct 15, 2012 6:54 AM in response to Niko Nyman

Not sure if this is significant, but I was actually running my script off of an Exchange server.


I've since moved on and am using some Exchange server side rules combined with an Automator script to do what I want. It's not quite as elegant, but it takes care of my needs.


Thanks for the other thread link.

Nov 28, 2012 6:44 PM in response to Screaming.Pict

I could really use some help here. I have no idea how to use applescript but I could really use this to download attachments. I've tried everything I can find to build an applescript to download messages but nothing works. I have Mountain Lion and I can't get any script at all to do anything. All I want to do is download attachments to a specific folder.


Does anyone have a complete applescript that does that?


Thanks

Dec 1, 2012 11:38 AM in response to Niko Nyman

The script works for me. Just needs to be saved to correct spot in library and you can save your files ONLY to Downloads folder (whatever subfolder you want to create must be in Downloads) it will not save it into documents.


just make sure you create new folder in Downloads and replace insertYourFolder name


the script must be saved in Library > Application Scripts > com.apple.mail. Then it works flawlesly


on perform_mail_action(ruleData)


-- The folder to save the attachments in (must already exist)

set attachmentsFolder to ((path to home folder as text) & "Downloads:InsertYourFolder") as text


-- Save in a sub-folder based on the name of the rule in Mail

--set subFolder to name of |Rule| of ruleData as text

set subFolder to "Production Sheets" as text

tell application "Finder"

if not (existsfoldersubFolder of folderattachmentsFolder) then


makenewfolderatattachmentsFolderwith properties {name:subFolder}

end if

end tell


-- Get incoming messages that match the rule

tell application "Mail"

set selectedMessages to |SelectedMessages| of ruleData

repeat with theMessage in selectedMessages



-- Get the date the message was sent

set {year:y, month:m, day:d, hours:h, minutes:min} to theMessage's date sent

set timeStamp to ("" & y & "-" & my pad(m as integer) & "-" & my pad(d) & "-" & my pad(h) & "-" & my pad(min))



-- Save the attachment

repeat with theAttachment in theMessage's mail attachments

set originalName to name of theAttachment

set savePath to attachmentsFolder & ":" & subFolder & ":" & timeStamp & " " & originalName


end repeat

end repeat

end tell


end perform_mail_action



this works for me just fine. No issues whatsoever. Hope that helps

Dec 3, 2012 2:40 PM in response to jbublik

This one works for me as well - probably easier


using terms from application "Mail"

on perform mail action with messagestheselectedMessages

set attachmentsFolder to "Macintosh HD:Users:YourUserName:Downloads:YourNew Folder"

tell application "Mail"

repeat with theMessage in theselectedMessages


-- get the sender's name

set senderName to extract name fromtheMessage's sender

repeat with theAttachment in theMessage's mail attachments

set originalName to name of theAttachment


-- name the file with the sender's name as well as the attachment name

set savePath to attachmentsFolder & ":" & senderName & "-" & originalName

try


-- Save the attachment


-- ** the code seems to get this far and then doesn't actually save the


-- ** file in the location indicated


savetheAttachmentinsavePath

end try

end repeat

end repeat

end tell

end perform mail action with messages

end using terms from


It saves to one folder I specify in Downloads - that's functionality I want, it does not create subfolders

Hope that helps.

Dec 6, 2012 3:54 AM in response to jbublik

jbublik, are you sure you're running Mountain Lion / OS X 10.8?


The on perform_mail_action(ruleData) syntax in your first example is deprecated in 10.8 Mail and does nothing; in effect the perform_mail_action handler is never executed.


Your second example uses the current on perform mail action with messages syntax, but fails on 10.8 just the way I described here: https://discussions.apple.com/thread/4186119?answerId=19501549022#19501549022

Applescript to save mail attachments failing in Mountain Lion

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