Save attachments from Mail.app based on subject issues

applescriptemailmail.appscanning

What I am trying to do: I have to scan some personal writing that I do for my mentor to review, I have 3 types of writing J,F,W. I use my scanner to send them via email (it's a work thing so I can't change it). I had this idea this morning that I could put the code in the subject line on the scanner and then have a rule to process the emails and file them in the correct folder for me.

I found and reused the script in the post Save attachments from Mail.app based on subject
, answer from markhunte

I am using Mail in MacOSX 10.13.6

In order to do testing, I commented out the mail rule function.

My testing is just from me to manually select the messages in the mail app (will convert to rule once working).

One thing I can't get my head around is the first time it saves the file it does not rename the file. You will see that I have used logs to help me figure this out. On the first run of the script, the IF statement thinks the folder exists and so does not rename the file, rerun the script and it renames it correctly.

Feeling a little confused, help would be really appreciated.

My email has subject lines with one letter in them (I do that when I scan documents to make it easier). The attachment name is always scan.pdf

Directory with scans

There does appear to be an issue with the codeList as well, it does not find the first item in the List (hence why I have J twice), not a big deal currently.

    (*using terms from application "Mail"
    on perform mail action with messages theMessages for rule theRule*)

set codeList to {"J", "F", "W", "O", "J"}
set subFolder to ""
set theDate to do shell script "date +%Y_%m_%d_%H%M%S"
--set ruleName to name of theRule


-- The folder to save the attachments in (must already exist)
tell application "Finder" to set attachmentsFolder to ((path to home folder as text) & "Desktop") as text

tell application "Mail"
    set theMessages to the selected messages of the front message viewer
    --set theMessage to first item of theMessages

    repeat with eachMessage in theMessages
        set theSubject to subject of eachMessage
        repeat with i from 1 to number of items in codeList
            set this_item to item i of codeList
            if theSubject contains this_item then

                set subFolder to this_item
                log "Found subject match " & this_item

            else
                -- display dialog "no subject " & this_item
                log "no subject " & this_item

            end if

        end repeat
        if (count of (eachMessage's mail attachments)) > 0 then
            log "Number of attachments is " & (count of (eachMessage's mail attachments))
            try

                tell application "Finder"

                    if not (exists folder subFolder of folder attachmentsFolder) then
                        make new folder at attachmentsFolder with properties {name:subFolder}
                    end if
                end tell
                -- Save the attachment
                repeat with theAttachment in eachMessage's mail attachments

                    set originalName to name of theAttachment
                    set savePath to attachmentsFolder & ":" & subFolder & ":" & originalName

                    tell application "Finder"
                        if (exists file originalName of folder subFolder of folder attachmentsFolder) then
                            set savePath to attachmentsFolder & ":" & subFolder & ":" & theDate & "_" & subFolder & "_" & originalName
                            log "File will be saved to path: " & attachmentsFolder & ":" & subFolder & ":" & theDate & "_" & subFolder & "_" & originalName
                        else
                            log "Found that file path already exits: " & attachmentsFolder & ":" & subFolder & ":" & theDate & "_" & subFolder & "_" & originalName
                        end if
                    end tell
                    try
                        save theAttachment in file (savePath)
                        log "saved file to " & savePath
                    end try
                end repeat
            on error error_message number error_number

            end try
        else
            log "Number of attachments is " & (count of (eachMessage's mail attachments))
        end if
    end repeat

end tell
(*end perform mail action with messages
end using terms from*)

Best Answer

I found it. The first setting of savePath does not have the extra code to rename the file (for whatever reason). I also got some start of week code included to create dynamic week folders.

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

Now: set savePath to attachmentsFolder & ":" & subFolder & ":" & theDate & "_" & originalName

Full Code:

 # https://apple.stackexchange.com/a/82085/301868
-- (markhunte)


(*using terms from application "Mail"
    on perform mail action with messages theMessages for rule theRule*)

set codeList to {"J", "F", "W", "O", "J"}
set MainFolder to "Desktop" -- After the current users home dir
set subFolder to ""
set theDate to do shell script "date +%Y_%m_%d_%H%M%S"
--set ruleName to name of theRule

-- Sean Korzdorfer
-- 2013-01-21
-- Fork of benwaldie Current Week Range TextExpander snippet: https://gist.github.com/4583398

set theDateW to (current date)
set theStartDate to theDateW
repeat until weekday of theStartDate = Wednesday
    set theStartDate to theStartDate - 1 * days
end repeat


-- Original Script Date Formatting:
-- set theDate to (short date string of theStartDate) & " - " & (short date string of theEndDate)
set theDateW to (year of theStartDate as string) & "-" & (my add_zero(month of theStartDate as integer)) & "-" & (my add_zero(day of theStartDate as integer))

on add_zero(theNumber)
    if theNumber < 10 then
        return "0" & (theNumber as string)
    else
        return theNumber as string
    end if
end add_zero

-- The folder to save the attachments in (must already exist)
tell application "Finder" to set attachmentsFolder to ((path to home folder as text) & MainFolder) as text

tell application "Mail"
    set theMessages to the selected messages of the front message viewer
    --set theMessage to first item of theMessages

    repeat with eachMessage in theMessages
        set theSubject to subject of eachMessage
        repeat with i from 1 to number of items in codeList
            set this_item to item i of codeList
            if theSubject contains this_item then
                set subFolder to theDateW
                log "Found subject match " & this_item

            else
                log "no subject " & this_item
            end if

        end repeat
        if (count of (eachMessage's mail attachments)) > 0 then
            log "Number of attachments is " & (count of (eachMessage's mail attachments))
            try

                tell application "Finder"

                    if not (exists folder subFolder of folder attachmentsFolder) then
                        make new folder at attachmentsFolder with properties {name:subFolder}
                    end if
                end tell
                -- Save the attachment
                repeat with theAttachment in eachMessage's mail attachments

                    set originalName to name of theAttachment
                    set savePath to attachmentsFolder & ":" & subFolder & ":" & theDate & "_" & originalName

                    tell application "Finder"
                        if (exists file originalName of folder subFolder of folder attachmentsFolder) then
                            set savePath to attachmentsFolder & ":" & subFolder & ":" & theDate & "_" & originalName
                            log "File will be saved to path: " & attachmentsFolder & ":" & subFolder & ":" & theDate & "_" & originalName
                        else
                            log "Found that file path already exits: " & attachmentsFolder & ":" & subFolder & ":" & theDate & "_" & originalName
                        end if
                    end tell
                    try
                        save theAttachment in file (savePath)
                        log "saved file to " & savePath
                    end try
                end repeat
            on error error_message number error_number

            end try
        else
            log "Number of attachments is " & (count of (eachMessage's mail attachments))
        end if
    end repeat

end tell
(*end perform mail action with messages
end using terms from*)