MacOS – how to auto download a certain attachment in mail

applescriptemailmacosmail.app

I have looked on stack exchange and other sites for a simple applescript. I have found more complex scripts that it's hard for me to understand (not knowing a lot about the applescript syntax). So, here's my dilemma:

I need to automatically download an attachment (i.e. named "blank expense report") to a specific folder (i.e. "Inbox"). That's it. I can setup the mail rule with parameters to find the attachment I'm looking for:

enter image description here

I just need a simple script to download the attachment.

I have looked at these but just got confused trying to alter them and actually messed up some non-essential files on my computer. So, I'll stop copying and pasting code and just ask for some help.

Questions I looked at before this.

Save attachments from Mail.app based on subject

Automatically Save Attachments in Mail.app in 10.8 Mountain Lion

Best Answer

This is an edited version — quite possibly not the best one — of the script shown in this answer to the Automatically Save Attachments in Mail.app in 10.8 Mountain Lion thread, I've tested it and it works:

using terms from application "Mail"
    on perform mail action with messages theMessages for rule theRule
        tell application "Mail"
            repeat with eachMessage in theMessages
                repeat with theAttachment in eachMessage's mail attachments
                    set attachmentName to name of theAttachment
                    if attachmentName is "blank expense report" then
                        set savePath to "Macintosh HD:Users:yourUsername:Inbox:" & attachmentName
                        try
                            save theAttachment in file (savePath)
                            on error err
                            display display "The Following Error Occurred:" & err
                        end try
                    end if
                end repeat
            end repeat
        end tell
    end perform mail action with messages
end using terms from

This script will save the attachment named "blank expense report" in a named "Inbox" at Machintosh HD:Users:yourUsername:Inbox. Be sure to change the value of savePath variable accordingly to your needs.