Saving mail attachment

Hi everyone,

Sorry, I’m not big on Applescript and am still learning.

I currently use the following script i cobbled together from bits and pieces from this site to save an attachment i receive a few times a day from a supplier.

Currently the attachment retains it name when it is saved to my desktop, but for my needs, I need the attachment to be renamed xxxxxxx.xls every time its received.

The script is attached - Any help to get this happening would be appreciated. If the item has a static name I can have it imported automatically into my filemaker 6.

Thanks in advance

using terms from application "Mail"
	on perform mail action with messages theMessages
		tell application "Finder" to set ptd to (path to desktop folder) as string
		repeat with theMessage in theMessages
			set theAttachment to first item of theMessage's mail attachments
			set theAttachmentFileName to ptd & theAttachment's name
			save theAttachment in theAttachmentFileName
		end repeat
	end perform mail action with messages
end using terms from

Hi and welcome,

try this.
if you’re going to save the attachment to a folder, where a file with the same name already exists
an error occurs. Therefore the script saves the file using the original file name
and renames it with a shell command


myName : "xxxxxxxxxx.als"

using terms from application "Mail"
	on perform mail action with messages theMessages
		set ptd to path to desktop -- save textfiles directly on desktop - this may not be what you want.
		repeat with theMessage in theMessages -- loop through the messages sent by Mail
			tell contents of theMessage
				if (count (mail attachments)) > 0 then
					set theAttachment to first item of mail attachments -- this will crash if there are no attachments in the message
					set theAttachmentFileName to theAttachment's name -- replace quoted text with your desired path
					save theAttachment in (ptd as text) & theAttachmentFileName
					do shell script "/bin/mv " & quoted form of ((POSIX path of ptd) & theAttachmentFileName) & space & quoted form of ((POSIX path of ptd) & myName)
				end if
			end tell
		end repeat
	end perform mail action with messages
end using terms from


Note: It’s interesting to know, that a rule script works also without any additional Mail tell block

That works a treat, thank you.

This would be because the the applescript is being run as a rule in Mail, so mail already know the script will be handling the single message that triggered it… (Well thats my take)

Also to note, this works in 10.4 but not 10.3

I also had to move the name of the file down to the command and couldn’t have the variable outside the tell