Folder action to rename and process emails

I am trying to create a small office document management system that would do the following. I would drag an email as an .eml file from Outlook into a folder on the Desktop. Upon receiving the file, the Action would do the following:


1. Add today's date to the beginning of the existing filename.

2. Ask me for the client code.

3. Add the client code at the end of the existing filename.


I have started with Rename Finder Items: Add Date. The system does append the date to the filename, however, instead of doing it once, it inserts the date 20 or so times.


Then when I insert the Ask for Text and assign to a variable ("Client code"), which later added through the Rename Finder, nothing happens.


Oh, I tried to include the code:


tell application "Client Code and Rename"

activate

end tell


But it just does not work. Please help me to put it together. Thanks.

MacBook Pro, Mac OS X (10.6.5), 2 GHz Intel Core Duo, 2 GB

Posted on Sep 9, 2018 2:44 AM

Reply

Similar questions

9 replies

Sep 9, 2018 8:54 PM in response to rccharles

I may have misunderstood what your approach. I'd have to see the code to comment more. People usually post a picture of the automator script.


R

How to show us a screen image. Avoid personal identification.

on the Mac you do:

command + shift + 3 Will take entire screen. You hear a click.

command + shift + 4 Lets you decide what to take. Mouse pointer changes. Move mouse to upper left corner of desire image. Hold down left mouse key where to start image. Drag mouse to lower left of where you want to stop image. Release mouse.


You will get a file starting with Screen Shot ... .png on the desktop. example:

Screen Shot 2016-09-20 at 2.27.47 PM



User uploaded file


click on camera icon.


another window will appear.


click on Browse button


An open file panel appears. Select the file.


User uploaded file


After selection a file, I have this screen showing.


User uploaded file

Click on file you wish to select. Click on the Open button.


You come back to Select an Image. Cclick on Insert Image button. You may have to scroll down to see Insert Image button.

alternative explanation: https://discussions.apple.com/docs/DOC-6917

Sep 16, 2018 11:56 AM in response to rccharles

Here is how to create an Applescript Application.


To keep you on your toes, I use a different applescript app for this example of how to create an applescript app and save it to a different place.



(*

https://discussions.apple.com/thread/3033221?tstart=30

Required:


Turn on accessability GUI in system preferences.

Optional:
--------
Full Key Codes
http://www.versiontracker.com/dyn/moreinfo/macosx/21215


youpi or iKey
   youpi and iKey are keystroke remapping programs.
   youpi, the free version, works fairly well for me in Mac OS 10.4 although not officially supported.
http://www.versiontracker.com/dyn/moreinfo/macosx/11485&vid=75326
   iKey is the paid version
http://www.scriptsoftware.com/ikey/

*)

on run
    -- Write a message into the event log.
    -- To see, run this applescript in Sript Editor. Click on Event Log tab at bottom of screen.
    -- Click run.
    log "  --- Starting on " & ((current date) as string) & " --- "

    set fromApp to "Safari"
    set toApp to "TextEdit"

    --- We have arrived.


    say "we are beginning now."

    -- Start your application
    tell application fromApp
        activate
    end tell

    delay 1

    say "copy data to clipboard"

    tell application "System Events"
        tell process fromApp


            keystroke "c" using command down
            delay 2

        end tell
    end tell


    -- Start your application
    tell application toApp
        activate
    end tell

    delay 5
    tell application "System Events"
        tell process fromApp
            --  open file menu
            keystroke return
            keystroke return
            keystroke return

            keystroke "v" using command down

        end tell
    end tell

    say "good news, We are done."

end run


The first thing that you need to do is to make the text into an AppleScript program.


Start the Script Editor

/Applications/Utilities/Script Editor.app


Copy the script text to the Script editor.


Save the text to a file as an application and do not check any of the boxes below.



User uploaded file


If you want access to the script from your Script Menu, move the script (the saved script application file) to your ~/Library/Scripts folder. You can also drag it to your Dock or make an alias for it on the Desktop.


To debug, run the script within the Applescript Editor. Click on the event log tab at the bottom of the window. Click on the run icon. The results from the log statement will be shown at the bottom of the screen.


User uploaded file

Sep 16, 2018 4:55 PM in response to mityay_ch

I always underestimate the amount of work it will take 😎. I'm curious. I wanted to learn more about appescript. Nearly all of it was copied from other applescripts. Unfortunately, after pasting things together, the coded didn't fit together as well as I had hopped. Only findExtension and findFreeName were new subroutines. findExtension was copied. findFreeName was coverted code from another Applescript I wrote.


I'm retired so I have more time. More of the higher point members are retired than not. I consider this volunteer work.


Oh, I did find a mistake 👿 in findFreeName.


if clearCount > 3 then


should be something like


if clearCount > 300 then


R

Sep 10, 2018 1:52 AM in response to rccharles

Hi, thank you for taking time to respond. Here are actions I've inserted. The idea is:


1. Drag .eml from Outlook to the folder Incoming

2. When asked, enter the Client code

3. Append the Client code to the end of the existing filename

3. Have today's date in YYMMDD added to the front of the filename

4. Move the file with the changed name to the folder Outgoing


User uploaded fileUser uploaded fileUser uploaded file



As a bonus point, I would like to have focus on the Client code field when it comes up. I figured out how to add it to the Application I've created (aptly called "Client code and rename") but I don't know how to change it for the Folder action.


User uploaded file


Thank you.

Sep 14, 2018 7:16 PM in response to mityay_ch

I'm not too much into automator. I developed an applescript approach. What you do is drop the file you want to rename them move onto the icon for this applescript.


(* 
  Demonstration of how dropping files on AppleScript icon works.  Shows how to debug via on run path. Shows items added to folder.
  
 Save as an Application Bundle.  Don't check anything.

 Shows log statement.

 It is easier to diagnose problems with debug information. I suggest adding log statements to your script to see what is going on.  Here is an example.
    
For testing, run in the Script Editor.
    1) Click on the Event Log tab to see the output from the log statement
    2) Click on Run


Author: rccharles

https://discussions.apple.com/thread/8529411

1. Add today's date to the beginning of the existing filename.

2. Ask me for the client code.

3. Add the client code at the end of the existing filename.

       Copyright 2018 rccharles  
      
       Permission is hereby granted, free of charge, to any person obtaining a copy  
       of this software and associated documentation files (the "Software"), to deal  
       in the Software without restriction, including without limitation the rights  
       to use, copy, modify, merge, publish, distribute, sublicense, and/or sell  
       copies of the Software, and to permit persons to whom the Software is  
       furnished to do so, subject to the following conditions:  
        
       The above copyright notice and this permission notice shall be included in all  
       copies or substantial portions of the Software.  
        
       THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR  
       IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,  
       FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE  
       AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER  
       LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,  
       OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE  
       SOFTWARE. 

 *)


-- Gets invoked here when you run in AppleScript editor.

on run
    --  debug lines
    set desktopPath to (path to desktop) as string
    
    -- here is a log statment.
    log "desktopPath = " & desktopPath
    
    -- Be sure to select a file on your DESKTOP.
    set see to choose file with prompt "Select a file to standardize then move"
    -- Simulate dropped items list.
    set dropped_items to {see}
    
    common(dropped_items)
    
end run



-- Gets invoked here when something is dropped on the folder
-- Folder actions.

on adding folder items to this_folder after receiving added_items
    
    common(added_items)
    
end adding folder items to



-- Gets invoked here when something is dropped on this AppleScript icon
-- which will be the expected method

on open dropped_items
    
    common(dropped_items)
    
end open



on common(dropped_items)
    -- Required by debug routine.     
    global debugRunning
    set debugRunning to ""
    -- final destination folder in Home folder
    set finalDestination to "ArchivedMail"
    set longWait to 20
    
    -- Write a message into the event log.
    debugLog("  ------ Starting on " & ((current date) as string) & " ------ " & getMyName())
    log "class = " & class of dropped_items
    
    if (count of dropped_items) = 0 then
        log "odd no messages to process."
        display dialog "Odd, no messages to process." giving up after longWait
        return 1
    end if
    
    set pathToHome to (path to home folder) as string
    set destPath to pathToHome & finalDestination & ":"
    debugLog("pathToHome  is " & pathToHome & " destPath is " & destPath)
    
    -- make final destination folder
    try
        tell application "Finder"
            set newfolder to make new folder at pathToHome with properties {name:finalDestination}
            my debugLog("Created  final destination folder " & pathToHome & finalDestination)
        end tell
    on error errMsg number n
        -- It's ok if the folder already exits [ -48 ]. Put out warning for all other errors.    
        if n is not -48 then
            set commonError to "on error " & destPath & finalDestination & " errMsg is " & errMsg & " number is " & n
            display dialog commonError giving up after longWait
            my debugLog(commonError)
            return 3
        end if
    end try
    
    
    
    
    repeat with thisItem in dropped_items
        
        debugLog("here is something that we got as input: " & (thisItem as text))
        
        tell application "Finder"
            set startTime to current date
            log "day is " & day of startTime & "; month is " & ((month of startTime) as integer) & "; year is " & year of startTime
            
            set currentName to name of thisItem
            log "currentName is " & currentName
            set sourcePath to container of thisItem
            log "sourcePath is " & sourcePath
            set thisItemsExtension to get name extension of file thisItem
            set extension_length to length of (thisItemsExtension)
        end tell
        
        
        log "thisItemsExtension is " & thisItemsExtension & "; extension_length is " & extension_length
        --set companyCode to "AAA"
        display dialog "Enter you company code for " & currentName default answer ""
        set companyCode to text returned of result
        log "companyCode is " & companyCode
        
        set prefix to ((month of startTime) as integer) & "-" & day of startTime & "-" & year of startTime
        log "prefix is " & prefix
        
        repeat 1 times -- simulate continue        
            
            set new_name to ((prefix & "--" & characters 1 through (-2 - extension_length) of currentName) & "--" & companyCode & "." & thisItemsExtension) as text
            
            -- debuggin' to see if we got the right name
            my debugLog("Parms for rename.  destPath is " & destPath & " new_name is " & new_name)
            try
                set theName to my findFreeName(sourcePath, destPath, new_name) as text
            on error wrongText number n
                display dialog wrongText & " with " & n & "   will move on to next item, if it exists."
                exit repeat
            end try
            log "newly found theName is " & theName & "; class is " & class of theName
            log "thisItem is " & (thisItem as text)
            try
                tell application "Finder"
                    set name of thisItem to theName
                end tell
            on error msg number n
                set theErrorMsg to theName & " may already exist [ " & msg & " error number is " & n & " ].  Skipping"
                display dialog theErrorMsg giving up after 5
                debugLog(theErrorMsg)
                
            end try
            
            -- actually a folder, but good enough
            if my fileExists(destPath) then
                tell application "Finder"
                    try
                        -- from file filename path to full folder name path :-(.
                        set sourceFile to (thisItem as text)
                        set movedLocation to move thisItem to destPath
                        
                        my debugLog("moved " & sourceFile & " to destPath is " & destPath)
                    on error msg number n
                        set outMsg to "Got error message while moving " & currentName & " to " & destPath & return & "message is " & msg & return & "number is " & n
                        my debugLog(outMsg)
                        display dialog outMsg giving up after longWait
                        -- might as well try the next attachment 
                        exit repeat -- look at next message. simulate iterate here.                                     
                    end try
                end tell
            else
                -- very bad, folder doesn't exist as expected.
                set theErrorMsg to "very bad, folder  " & destPath & " doesn't exist as expected."
                my debugLog(theErrorMsg)
                display dialog theErrorMsg giving up after longWait
                exit repeat -- look at next message. simulate iterate here.     
            end if
            
        end repeat -- one time to make like a continue statmen
        
    end repeat
    
    
end common

(* =================== Subroutines ================== *)
-- ------------------------------------------------------  
(*
*)
on appendToFile(fileId, theData)
    
    local theSize, writeWhere
    
    set theSize to (get eof fileId)
    set writeWhere to theSize + 1 as integer
    write theData to fileId starting at writeWhere
    
end appendToFile

-- ------------------------------------------------------  
(* 
 debug(<string>)
 Write messages to a log file.

  -- Need to place these two lines in the calling routine. 
    global debugRunning
    set debugRunning to ""
 -- references appendToFile()    
  -- example:
    debug("start program. Reading from " & listOfFiles) 

*)
on debug(theMessage)
    
    
    global debugRunning
    local theSize, startupDiskName, pathToLog, fileReference
    
    set pathToLog to (path to home folder as text) & "changeFileNameLog.txt"
    -- log "pathToLog is " & pathToLog
    
    try
        -- Complete the path.
        set pathToLog to pathToLog as text
        set fileReference to (open for access file pathToLog ¬
            with write permission)
        
        if debugRunning = "" then
            set theSize to (get eof fileReference)
            if theSize > 0 then
                appendToFile(fileReference, " " & return)
            end if
            appendToFile(fileReference, "   --- debug on " & ((current date) as string) & "   --- " & return)
            set debugRunning to "running"
        end if
        -- log "theMessage " & theMessage
        -- display dialog "in debug..." & return & "theMessage " & theMessage giving up after 3
        appendToFile(fileReference, theMessage & return)
        
        close access fileReference
        tell application "Finder"
            set the creator type of the file pathToLog ¬
                to "R*ch"
        end tell
    on error mes number n
        try
            set commonErr to "error ... " & mes & " error number is " & n
            log commonErr
            close access fileReference
            display dialog commonErr giving up after 4
        end try
        
    end try
    -- log "end of debug"
end debug

-- ------------------------------------------------------ 
(*
write log message to script editor log and to our file log 
*)
on debugLog(theMessage)
    log "debugLog: " & theMessage
    return debug(theMessage)
end debugLog

-- ------------------------------------------------------  
(* 
Yvan Koenig
https://macscripter.net/viewtopic.php?id=43133
*)
on findExtension(fileName)
    set saveTID to AppleScript's text item delimiters
    set AppleScript's text item delimiters to {"."}
    set theExt to last text item of fileName
    set AppleScript's text item delimiters to saveTID
    --log "theExt is " & theExt
    if theExt ends with ":" then set theExt to text 1 thru -2 of theExt
    --log "theExt is " & theExt
    return theExt
end findExtension

-- ------------------------------------------------------  
(*
  ideas from:
  https://stackoverflow.com/questions/3469389/applescript-testing-for-file-existence
  
 use the alias way. 
*)
on fileExists(theFile) -- (String) as Boolean
    (* "System Events" and "Finder" checking for file existance revealed problems. l*)
    log "in fileExists"
    set debugging to true
    if debugging then log "  fileExists: theFile is " & (theFile as text)
    try
        set theAlias to theFile as alias
        set theExistance to true
    on error errMsg number n
        if debugging then log "  fileExists: n is " & n
        -- File or folder doesn't exist. 
        if n is not -43 then
            set commonError to "on error the errMsg is " & errMsg & " number is " & n
            if debugging then log "  fileExists: " & commonError
            display dialog commonError giving up after 10
            -- cause grief above.
            error "Failure of alias." number -1
        else
            set theExistance to false
        end if
    end try
    if debugging then log "  fileExists: theExistance is " & theExistance
    return theExistance
end fileExists

-- ------------------------------------------------------
(*
  find free name in source and target folder
*)
on findFreeName(sourcePath, targetPath, fileName)
    log "findFreeName: sourcePath is " & (sourcePath as text) & " sourcePath is " & (targetPath as text) & "  fileName is " & fileName
    log "sourcePath of class = " & class of sourcePath & "sourcePath of class = " & class of sourcePath & "fileName of class = " & class of fileName
    set longWait to 20
    
    -- set new_name to (prefix & "--" & characters 1 through (-2 - extension_length) of currentName) & "--" & companyCode & "." & name extension of file thisItem as text
    
    
    
    set clearCount to 0
    set theExtension to my findExtension(fileName)
    tell application "Finder"
        set justName to characters 1 through (-2 - (length of theExtension)) of fileName
    end tell
    log "findFreeName: theExtension is " & theExtension & "; justName is " & justName
    
    set sourceFile to (sourcePath as text) & fileName
    set targetFile to (targetPath as text) & fileName
    log "sourceFile is " & sourceFile & "; targetFile is " & targetFile
    try
        
        repeat while my fileExists(sourceFile) or fileExists(targetFile)
            log "findFreeName: looping" & " clearCount is " & clearCount
            if clearCount > 3 then
                set commonError to "findFreeName: could not find free name when searching for  "
                set commonError to commonError & fileName & ". clearCount is " & clearCount & " clean up  folders. "
                set commonError to commonError & return & (sourceFile as text) & return & (targetFile as text)
                my debugLog(commonError)
                
                -- have to throw an error to get out of this repeat. Could have set a switch I guess. 
                display dialog commonError giving up after longWait
                error "cannot find free file name" number 8110
            end if
            set clearCount to clearCount + 1
            log "findFreeName: clearCount is " & clearCount
            set fileName to justName & " #"
            log "findFreeName: fileName is " & fileName
            set fileName to fileName & (clearCount as text)
            log "findFreeName: fileName is " & fileName
            set fileName to fileName & "."
            log "findFreeName: fileName is " & fileName
            set fileName to fileName & (theExtension as text)
            log "findFreeName: fileName is " & fileName
            
            set sourceFile to (sourcePath as text) & fileName
            set targetFile to (targetPath as text) & fileName
            log "sourceFile is " & sourceFile & "; targetFile is " & targetFile
            -- my debugLog("findFreeName: searching for free name. " & fileName & " clearCount is " & clearCount & return & " destPath is " & destPath)
        end repeat -- while  
    on error errMsg number n
        log "error of some type"
        --display dialog errMsg & " with " & n
        if n is not 8110 then
            set displayFileName to fileName as text
            set commonError to "findFreeName: attempting to create free filename " & displayFileName & return & " on error the errMsg is " & errMsg & " number is " & n
            display dialog commonError giving up after longWait
            my debugLog(commonError)
            return "" -- hopefully this will never happen.  Haven't implement extensiver error recovery.
        else
            error "cannot find free file name. returning." number 8110
            
        end if
        
    end try
    log "findFreeName: return from findFreeName is " & fileName
    return fileName
    
end findFreeName

-- ------------------------------------------------------
(*
    modified to let the extension be.

    by mklement0
    https://stackoverflow.com/questions/5770384/how-find-the-file-name-of-an-executing-applescript
*)
on getMyName()
    local myAlias, myName
    tell application "System Events"
        set myAlias to path to me -- alias to the file/bundle of the running script
        set myName to name of myAlias -- filename with extension, if any.
        -- leave extension alone. 
    end tell
    return myName
end getMyName

This thread has been closed by the system or the community team. You may vote for any posts you find helpful, or search the Community for additional answers.

Folder action to rename and process emails

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