Advertisement
rccharles

backup of stackoverflowMain.scpt

Dec 17th, 2021
4,342
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. (*
  2.  
  3. Requirements:
  4.     https://discussions.apple.com/thread/8480829
  5.    
  6. Quick hints
  7. 1) Apple hids the User's library folder.  You will want to make it visible.
  8.   http://osxdaily.com/2013/10/28/show-user-library-folder-os-x-mavericks/
  9. 2) Place this Applescript in this folder with name ShortMailDownload.scpt.  You may not use the App extension.
  10.    "/Users/mac/Library/Application Scripts/com.apple.mail"    
  11. 2) The first "on" statement needs to be
  12.    on perform mail action with messages theMessages
  13. 3) Mail > Preferences... > Rules > Add Rule
  14.     "Perform the following actions"   [ buttons should be ]
  15.     "Run AppleScript" "ShortMailDownload"
  16.  
  17. Limitation: Yosemite, 10.10.5, Mail Version 8.2 (2104) only supports extracting one attachment. No problem in High Sierra, 10.13.6.
  18.  
  19. off topic.  Clicking on menu item:
  20. tell application "System Events" to click menu item "Date" of menu "Sort By" of menu item "Sort By" of menu "View" of menu bar item "View" of menu bar 1 of process "Mail"
  21.  
  22. Based on the example " Sample Rule Action Script.scpt" script in macOS 10.6.8 found in folder
  23. "/Library/Scripts /Library/Scripts/Mail Scripts/Rule Actions"
  24.   Sample Rule Action Script.scpt
  25.  
  26. I think "on perform mail action" needs to be the first "on" routine.
  27.  
  28. -- If run as an ordinary script, instead of directly from the Scripts
  29.     -- menu, it will call the default handler instead.
  30.     on r u n
  31.         tell application "Mail" to set selectedMessages to selection
  32.         tell me to perform mail action with messages (selectedMessages)
  33.     end r u n
  34.     http://hints.macworld.com/article.php?story=20070215145127300
  35.  
  36. There is lots of outdated advice on download attachments found by Google.
  37. https://stackoverflow.com/questions/39882312/how-to-download-an-attachment-from-mail-via-applescript-and-mail-rules
  38.  
  39.  
  40.        Copyright 2018 rccharles  
  41.      
  42.        Permission is hereby granted, free of charge, to any person obtaining a copy  
  43.        of this software and associated documentation files (the "Software"), to deal  
  44.        in the Software without restriction, including without limitation the rights  
  45.        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell  
  46.        copies of the Software, and to permit persons to whom the Software is  
  47.        furnished to do so, subject to the following conditions:  
  48.        
  49.        The above copyright notice and this permission notice shall be included in all  
  50.        copies or substantial portions of the Software.  
  51.        
  52.        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR  
  53.        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,  
  54.        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE  
  55.        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER  
  56.        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,  
  57.        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE  
  58.        SOFTWARE.  
  59.  
  60. *)
  61. on run
  62.     tell application "Mail"
  63.         try
  64.             set theSelectedMessages to selection
  65.             log "class of theSelectedMessages is " & class of theSelectedMessages
  66.             log "count of theSelectedMessages is " & (count of theSelectedMessages)
  67.         on error errMsg number n
  68.             display dialog "Silly, you need to select a message in Mail." & return & "on error the errMsg is " & errMsg & " number is " & n giving up after 8
  69.             return
  70.         end try
  71.         -- not used, don't know how to pass to perform ...
  72.         set theRule to {name:"dummyRule"}
  73.        
  74.         tell me to perform mail action with messages theSelectedMessages -- for  theRule
  75.        
  76.     end tell -- app "Mail"
  77. end run
  78. (**)
  79. using terms from application "Mail"
  80.     on perform mail action with messages theMessages --for rule theRule
  81.        
  82.         -- Suggest this code be the first "on" in file, no on r u n & no assumed on r u n either
  83.        
  84.         -- Required by debug routine.  
  85.         global debugRunning
  86.         set debugRunning to ""
  87.        
  88.         -- debug status for displaying messages in this routine.
  89.         set debugSwitch to true
  90.         log "debugSwitch is " & debugSwitch
  91.         -- initialize
  92.         set longWait to 20
  93.        
  94.         (*
  95.           Where to place files
  96.         *)
  97.         -- intermediate folder in Home folder
  98.         -- must be Downloads for later version of macOS
  99.         set intermediateDownloadFolder to "Downloads:"
  100.         -- Folder inside of Downloads folder
  101.         set intermediateSubFolder to "subFolderForMailDownload"
  102.         -- final destination folder in Home folder
  103.         set finalDestination to "Students"
  104.        
  105.         set startMsg to "perform mail with " & getMyName() & " ====== " & ((current date) as string) & " ====== perform mail "
  106.         my debugLog(startMsg)
  107.         --display dialog startMsg giving up after 2
  108.         set intermediateFolder to intermediateDownloadFolder & intermediateSubFolder
  109.         log "intermediateFolder is " & intermediateFolder
  110.        
  111.         if (count of theMessages) = 0 then
  112.             log "odd no messages to process."
  113.             display dialog "Odd, no messages to process." giving up after longWait
  114.             return 1
  115.         end if
  116.        
  117.         -- mail requires download to the Downloads or subfolders of Downloads
  118.         -- for some reason, this gets the path to this app when invoked by mail.
  119.         set pathToHome to (path to home folder) as string
  120.         log ("pathToHome  is " & pathToHome)
  121.         set listOfPathToHome to textToList(pathToHome, ":")
  122.         set pathToHome to item 1 of listOfPathToHome & ":" & item 2 of listOfPathToHome & ":" & item 3 of listOfPathToHome & ":"
  123.         log ("revised pathToHome is " & pathToHome)
  124.        
  125.         -- make intermediate folder
  126.         try
  127.             tell application "Finder"
  128.                 set newfolder to make new folder at (pathToHome & intermediateDownloadFolder) with properties {name:intermediateSubFolder}
  129.                 my debugLog("Created folder " & pathToHome & intermediateDownloadFolder & intermediateSubFolder)
  130.             end tell
  131.         on error errMsg number n
  132.             -- It's ok if the folder already exits [ -48 ]. Put out warning for all other errors.  
  133.             if n is not -48 then
  134.                 set commonError to "on error " & intermediateSubFolder & " the errMsg is " & errMsg & " number is " & n
  135.                 display dialog commonError giving up after longWait
  136.                 my debugLog(commonError)
  137.                 return 2
  138.             end if
  139.         end try
  140.        
  141.         -- make final destination folder
  142.         try
  143.             tell application "Finder"
  144.                 set newfolder to make new folder at pathToHome with properties {name:finalDestination}
  145.                 my debugLog("Created  final destination folder " & pathToHome & finalDestination)
  146.             end tell
  147.         on error errMsg number n
  148.             -- It's ok if the folder already exits [ -48 ]. Put out warning for all other errors.  
  149.             if n is not -48 then
  150.                 set commonError to "on error " & finalDestination & " errMsg is " & errMsg & " number is " & n
  151.                 display dialog commonError giving up after longWait
  152.                 my debugLog(commonError)
  153.                 return 3
  154.             end if
  155.         end try
  156.        
  157.        
  158.         tell application "Mail"
  159.             --activate
  160.             log "was activated"
  161.            
  162.             -- look throught the messages we selected.
  163.             repeat with aMessage in theMessages -- loop through each message
  164.                 log "class of aMessage is " & class of aMessage
  165.                
  166.                 -- get the senders email address
  167.                 set fromMail to aMessage's sender
  168.                 my debugLog("fromMail is " & fromMail)
  169.                
  170.                 -- Create folder for the individual student.
  171.                 -- ---- Set final target folder ---->
  172.                 set pathToStudents to pathToHome & finalDestination & ":"
  173.                 my debugLog("pathToStudents is " & pathToStudents)
  174.                 repeat 1 times -- sinulate continue
  175.                     try
  176.                         tell application "Finder"
  177.                             set newStudent to make new folder at pathToStudents with properties {name:fromMail}
  178.                             my debugLog("Created final destination subfolder " & pathToStudents & fromMail)
  179.                         end tell
  180.                     on error errMsg number n
  181.                         -- It's ok if the folder already exits [-48 ]. Put out warning for all other errors.
  182.                         if n is not -48 then
  183.                             set commonError to "attempting to create " & pathToStudents & fromMail & return & " on error the errMsg is " & errMsg & " number is " & n
  184.                             display dialog commonError giving up after longWait
  185.                             my debugLog(commonError)
  186.                             exit repeat -- look at next message. simulate iterate here.
  187.                         end if
  188.                     end try
  189.                    
  190.                     set pathToTheStudent to pathToStudents & fromMail & ":"
  191.                     my debugLog("pathToTheStudent is " & pathToTheStudent)
  192.                     -- repeat with aFile in aMessage's mail attachments
  193.                     -- set ourList to every mail attachment of aMessage                
  194.                     repeat with aFile in (mail attachments of aMessage)
  195.                         log "save aFile"
  196.                         repeat 1 times -- sinulate continue
  197.                            
  198.                             --if (downloaded of aFile) then -- check if file is already downloaded
  199.                             set attachmentName to name of aFile
  200.                             my debugLog("attachmentName is " & attachmentName)
  201.                             set {fileName, fileExt} to my getNameExt(attachmentName)
  202.                             log "fileName  is " & fileName & " fileExt  is " & fileExt
  203.                             -- ---- Intermediate folder target ---->
  204.                             -- apple changed mail to require the download to be in the downloads folder :-(
  205.                             set pathForDownload to pathToHome & intermediateFolder & ":"
  206.                            
  207.                             set clearCount to 0
  208.                             set destPath to pathForDownload & attachmentName
  209.                             set finalDestPath to pathToStudents & fromMail & ":" & attachmentName
  210.                             log "check for free name. clearCount is " & clearCount & return & " destPath is " & destPath & return & " finalDestPath is " & finalDestPath
  211.                            
  212.                             repeat while my fileExists(destPath) or my fileExists(finalDestPath)
  213.                                 set clearCount to clearCount + 1
  214.                                 log "clearCount is " & clearCount
  215.                                 set destPath to pathForDownload & fileName & "#" & clearCount & "." & fileExt
  216.                                 set finalDestPath to pathToStudents & fromMail & ":" & fileName & "#" & clearCount & "." & fileExt
  217.                                 log "searching for free name. clearCount is " & clearCount & return & " destPath is " & destPath & return & " finalDestPath is " & finalDestPath
  218.                             end repeat -- while  
  219.                             log "found. destPath is " & destPath
  220.                             save aFile in destPath as native format
  221.                             log "file was saved."
  222.                            
  223.                             -- move it right on to file location.
  224.                             -- debuggin to see if we got the right name
  225.                             my debugLog("Saved to intermediate.  destPath is " & destPath)
  226.                            
  227.                             if my fileExists(destPath) then
  228.                                 tell application "Finder"
  229.                                     try
  230.                                         -- from file filename path to full folder name path :-(.
  231.                                         move destPath to pathToTheStudent
  232.                                         my debugLog("saved to final folder pathToTheStudent is " & pathToTheStudent)
  233.                                     on error msg number n
  234.                                         set outMsg to "Got error message while moving " & destPath & " to " & pathToTheStudent & return & "message is " & msg & return & "number is " & n
  235.                                         my debugLog(outMsg)
  236.                                         display dialog outMsg giving up after longWait
  237.                                         -- might as well try the next attachment
  238.                                         exit repeat -- look at next message. simulate iterate here.                                    
  239.                                     end try
  240.                                 end tell
  241.                             else
  242.                                 -- very bad, folder doesn't exist as expected.
  243.                                 my debugLog("very bad, folder  " & destPath & " doesn't exist as expected.")
  244.                                 exit repeat -- look at next message. simulate iterate here.    
  245.                             end if
  246.                            
  247.                         end repeat -- one time to make like a continue statment
  248.                     end repeat -- next attached file
  249.                 end repeat -- continue
  250.             end repeat -- next message
  251.         end tell --tell app "Mail"
  252.         return 0
  253.     end perform mail action with messages
  254. end using terms from
  255.  
  256.  
  257. (* ======================== Subroutines ======================= *)
  258. -- ------------------------------------------------------  
  259. (*
  260. *)
  261. on appendToFile(fileId, theData)
  262.    
  263.     local theSize, writeWhere
  264.    
  265.     set theSize to (get eof fileId)
  266.     set writeWhere to theSize + 1 as integer
  267.     write theData to fileId starting at writeWhere
  268.    
  269. end appendToFile
  270.  
  271. -- ------------------------------------------------------  
  272. (*
  273.  debug(<string>)
  274.  Write messages to a log file.
  275.  
  276.   -- Need to place these two lines in the calling routine.
  277.     global debugRunning
  278.     set debugRunning to ""
  279.  -- references appendToFile()  
  280.   -- example:
  281.     debug("start program. Reading from " & listOfFiles)
  282.    
  283.    found here: /Users/mac/Documents/BJ\ Prior\ Years/BJ2004/sendmailapp2\ copy
  284.  
  285. *)
  286. on debug(theMessage)
  287.     -- return
  288.     global debugRunning
  289.     local theSize, startupDiskName, pathToLog, fileReference
  290.    
  291.     set pathToLog to (path to home folder as text) & "tryAttachmentsLog.txt"
  292.     -- log "pathToLog is " & pathToLog
  293.     -- display dialog "pathToLog is " & pathToLog giving up after 4
  294.    
  295.     try
  296.         -- Complete the path.
  297.         set pathToLog to pathToLog as text
  298.         set fileReference to (open for access file pathToLog ¬
  299.             with write permission)
  300.        
  301.         if debugRunning = "" then
  302.             set theSize to (get eof fileReference)
  303.             if theSize > 0 then
  304.                 appendToFile(fileReference, " " & return)
  305.             end if
  306.             appendToFile(fileReference, "   --- debug on " & ((current date) as string) & "   --- " & return)
  307.             set debugRunning to "running"
  308.         end if
  309.         -- log "theMessage " & theMessage
  310.         -- display dialog "in debug..." & return & "theMessage " & theMessage giving up after 3
  311.         appendToFile(fileReference, theMessage & return)
  312.        
  313.         close access fileReference
  314.         tell application "Finder"
  315.             set the creator type of the file pathToLog ¬
  316.                 to "R*ch"
  317.         end tell
  318.     on error mes number n
  319.         try
  320.             set commonErr to "error ... " & mes & " error number is " & n
  321.             log commonErr
  322.             close access fileReference
  323.             display dialog commonErr giving up after 4
  324.         end try
  325.        
  326.     end try
  327.     -- log "end of debug"
  328. end debug
  329.  
  330. (*
  331. write log message to script editor log and to our file log
  332. *)
  333. on debugLog(theMessage)
  334.     log "debugLog: " & theMessage
  335.     return debug(theMessage)
  336. end debugLog
  337.  
  338. -- ------------------------------------------------------  
  339. (*
  340.   ideas from:
  341.   https://stackoverflow.com/questions/3469389/applescript-testing-for-file-existence
  342.  
  343.  use the alias way.
  344. *)
  345. on fileExists(theFile) -- (String) as Boolean
  346.     (* "System Events" and "Finder" checking for file existance revealed problems. l*)
  347.     set debugging to false
  348.     if debugging then log "  fileExists: theFile is " & theFile
  349.     try
  350.         set theAlias to theFile as alias
  351.         set theExistance to true
  352.     on error errMsg number n
  353.         if debugging then log "  fileExists: n is " & n
  354.         -- File or folder doesn't exist.
  355.         if n is not -43 then
  356.             set commonError to "on error the errMsg is " & errMsg & " number is " & n
  357.             if debugging then log "  fileExists: " & commonError
  358.             display dialog commonError giving up after 10
  359.             -- cause grief above.
  360.             error "Failure of alias." number -1
  361.         else
  362.             set theExistance to false
  363.         end if
  364.     end try
  365.     if debugging then log "  fileExists: theExistance is " & theExistance
  366.     return theExistance
  367. end fileExists
  368.  
  369. (*
  370.   Philip Regan
  371.   https://stackoverflow.com/questions/3469389/applescript-testing-for-file-existence
  372. *)
  373. (*on fileExists(theFile) -- (String) as Boolean
  374.     tell application "System Events"
  375.         if exists file theFile then
  376.             return true
  377.         else
  378.             return false
  379.         end if
  380.     end tell
  381. end fileExists*)
  382.  
  383. -- ------------------------------------------------------
  384. (*
  385.    Yvan Koenig
  386.    https://macscripter.net/viewtopic.php?id=43133
  387.    with mods for no extension present
  388.    
  389. *)
  390. on getExt(theName)
  391.     if (offset of "." in theName) is greater than 0 then
  392.         set saveTID to AppleScript's text item delimiters
  393.         set AppleScript's text item delimiters to {"."}
  394.         set theExt to last text item of theName
  395.         set AppleScript's text item delimiters to saveTID
  396.         if theExt ends with ":" then set theExt to text 1 thru -2 of theExt
  397.     else
  398.         set theExt to ""
  399.     end if
  400.     return theExt
  401. end getExt
  402.  
  403. -- ------------------------------------------------------
  404. (*
  405.     Input: a file with or without an extension.
  406.     hhas
  407.     https://forums.macrumors.com/threads/applescript-to-get-file-name.927338/
  408.    
  409.     may not work with folders with extensions like apps.
  410.    
  411.     Test cases:
  412.                 set fileName to " "                  
  413.                 set fileExt to my getExt(attachmentName)
  414.                 log "fileName  is " & fileName & " fileExt  is " & fileExt
  415.                 set fileExt to my getExt("testfileNo")
  416.                 log "fileName  is " & fileName & " fileExt  is " & fileExt
  417.                 set fileExt to my getExt("path:to:testfileNo:")
  418.                 log "fileName  is " & fileName & " fileExt  is " & fileExt
  419.                 log ">>>>>>>>>>>>>>>>>>>>>>"
  420.                 set {fileName, fileExt} to my getNameExt(attachmentName)
  421.                 log "fileName  is " & fileName & " fileExt  is " & fileExt
  422.                 set {fileName, fileExt} to my getNameExt("testfileNo")
  423.                 log "fileName  is " & fileName & " fileExt  is " & fileExt
  424.                 set {fileName, fileExt} to my getNameExt("path:to:testfileNo:")
  425.                 log "fileName  is " & fileName & " fileExt  is " & fileExt
  426. *)
  427. on getNameExt(fileName)
  428.     set saveTID to AppleScript's text item delimiters
  429.     set AppleScript's text item delimiters to "."
  430.     if fileName contains "." then
  431.         set {displayName, nameExt} to {text 1 thru text item -2, text item -1} of fileName
  432.     else
  433.         set {displayName, nameExt} to {fileName, ""}
  434.     end if
  435.     set AppleScript's text item delimiters to saveTID
  436.    
  437.     return {displayName, nameExt}
  438. end getNameExt
  439. -- ------------------------------------------------------
  440. (*
  441.     modified to let the extension be.
  442.  
  443.     by mklement0
  444.     https://stackoverflow.com/questions/5770384/how-find-the-file-name-of-an-executing-applescript
  445. *)
  446. on getMyName()
  447.     local myAlias, myName
  448.     tell application "System Events"
  449.         set myAlias to path to me -- alias to the file/bundle of the running script
  450.         set myName to name of myAlias -- filename with extension, if any.
  451.         -- leave extension alone.
  452.     end tell
  453.     return myName
  454. end getMyName
  455.  
  456. -- ------------------------------------------------------
  457. (*
  458.    ls_l is list file with options  
  459.   the format is best for debuging.
  460.  
  461.   example usage:
  462.   set {fileExists, fromUnix} to ls_l(attachmentNamePath, "-l")
  463.   log "attachmentNamePath fileExists is " & fileExists & return & " fromUnix is " & fromUnix
  464.  
  465.   *)
  466. on ls_l(attachmentNamePath, options)
  467.     --log "ls_l"
  468.     --log options
  469.    
  470.     set unixAttachmentNamePath to POSIX path of attachmentNamePath
  471.     --log "unixDesktopPath = " & unixAttachmentNamePath
  472.    
  473.     set quotedUnixAttachmentNamePath to quoted form of unixAttachmentNamePath
  474.     --log "quoted form is " & quotedUnixAttachmentNamePath
  475.     try
  476.         set fromUnix to do shell script "ls " & options & " " & quotedUnixAttachmentNamePath
  477.         set fromUnix to "ls " & options & return & fromUnix
  478.         set fileExists to true
  479.     on error errMsg number n
  480.         set fromUnix to "ls " & options & "  error..." & errMsg & " with number " & n
  481.         set fileExists to false
  482.        
  483.     end try
  484.     return {fileExists, fromUnix}
  485. end ls_l
  486.  
  487. -- ------------------------------------------------------
  488. (*
  489. textToList seems to be what you are trying to do
  490.   thisText is the input string
  491.   delim is what to split on
  492.  
  493.   returns a list of strings.  
  494.  
  495. - textToList was found here:
  496. - http://macscripter.net/viewtopic.php?id=15423
  497.  
  498. *)
  499.  
  500. on textToList(thisText, delim)
  501.     set resultList to {}
  502.     set {tid, my text item delimiters} to {my text item delimiters, delim}
  503.    
  504.     try
  505.         set resultList to every text item of thisText
  506.         set my text item delimiters to tid
  507.     on error
  508.         set my text item delimiters to tid
  509.     end try
  510.     return resultList
  511. end textToList
  512.  
  513.  
  514. -----------------------------------------------------------------------------
  515.  
  516. (*
  517.  
  518. Requirements:
  519.     https://discussions.apple.com/thread/8480829
  520.    
  521. Quick hints
  522. 1) Apple hids the User's library folder.  You will want to make it visible.
  523.   http://osxdaily.com/2013/10/28/show-user-library-folder-os-x-mavericks/
  524. 2) Place this Applescript in this folder with name ShortMailDownload.scpt.  You may not use the App extension.
  525.    "/Users/mac/Library/Application Scripts/com.apple.mail"    
  526. 2) The first "on" statement needs to be
  527.    on perform mail action with messages theMessages
  528. 3) Mail > Preferences... > Rules > Add Rule
  529.     "Perform the following actions"   [ buttons should be ]
  530.     "Run AppleScript" "ShortMailDownload"
  531.  
  532. Limitation: Yosemite, 10.10.5, Mail Version 8.2 (2104) only supports extracting one attachment. No problem in High Sierra, 10.13.6.
  533.  
  534. off topic.  Clicking on menu item:
  535. tell application "System Events" to click menu item "Date" of menu "Sort By" of menu item "Sort By" of menu "View" of menu bar item "View" of menu bar 1 of process "Mail"
  536.  
  537. Based on the example " Sample Rule Action Script.scpt" script in macOS 10.6.8 found in folder
  538. "/Library/Scripts /Library/Scripts/Mail Scripts/Rule Actions"
  539.   Sample Rule Action Script.scpt
  540.  
  541. I think "on perform mail action" needs to be the first "on" routine.
  542.  
  543. -- If run as an ordinary script, instead of directly from the Scripts
  544.     -- menu, it will call the default handler instead.
  545.     on r u n
  546.         tell application "Mail" to set selectedMessages to selection
  547.         tell me to perform mail action with messages (selectedMessages)
  548.     end r u n
  549.     http://hints.macworld.com/article.php?story=20070215145127300
  550.  
  551. There is lots of outdated advice on download attachments found by Google.
  552. https://stackoverflow.com/questions/39882312/how-to-download-an-attachment-from-mail-via-applescript-and-mail-rules
  553.  
  554.  
  555.        Copyright 2018 rccharles  
  556.      
  557.        Permission is hereby granted, free of charge, to any person obtaining a copy  
  558.        of this software and associated documentation files (the "Software"), to deal  
  559.        in the Software without restriction, including without limitation the rights  
  560.        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell  
  561.        copies of the Software, and to permit persons to whom the Software is  
  562.        furnished to do so, subject to the following conditions:  
  563.        
  564.        The above copyright notice and this permission notice shall be included in all  
  565.        copies or substantial portions of the Software.  
  566.        
  567.        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR  
  568.        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,  
  569.        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE  
  570.        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER  
  571.        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,  
  572.        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE  
  573.        SOFTWARE.  
  574.  
  575. *)
  576. (*  Uncomment when you want to debug this script in the Script Editor. Go into Mail and select a message. Run this script.
  577. (*on run
  578.     tell application "Mail"
  579.         try
  580.             set theSelectedMessages to selection
  581.             log "class of theSelectedMessages is " & class of theSelectedMessages
  582.             log "count of theSelectedMessages is " & (count of theSelectedMessages)
  583.         on error errMsg number n
  584.             display dialog "Silly, you need to select a message in Mail." & return & "on error the errMsg is " & errMsg & " number is " & n giving up after 8
  585.             return
  586.         end try
  587.         -- not used, don't know how to pass to perform ...
  588.         set theRule to {name:"dummyRule"}
  589.        
  590.         tell me to perform mail action with messages theSelectedMessages -- for  theRule
  591.        
  592.     end tell -- app "Mail"
  593. end run
  594. *)
  595. (**)
  596. using terms from application "Mail"
  597.     on perform mail action with messages theMessages --for rule theRule
  598.        
  599.         -- Suggest this code be the first "on" in file, no on r u n & no assumed on r u n either
  600.        
  601.         -- Required by debug routine.  
  602.         global debugRunning
  603.         set debugRunning to ""
  604.        
  605.         -- debug status for displaying messages in this routine.
  606.         set debugSwitch to true
  607.         log "debugSwitch is " & debugSwitch
  608.         -- initialize
  609.         set longWait to 20
  610.        
  611.         (*
  612.           Where to place files
  613.         *)
  614.         -- intermediate folder in Home folder
  615.         -- must be Downloads for later version of macOS
  616.         set intermediateDownloadFolder to "Downloads:"
  617.         -- Folder inside of Downloads folder
  618.         set intermediateSubFolder to "subFolderForMailDownload"
  619.         -- final destination folder in Home folder
  620.         set finalDestination to "Students"
  621.        
  622.         set startMsg to "perform mail with " & getMyName() & " ====== " & ((current date) as string) & " ====== perform mail "
  623.         my debugLog(startMsg)
  624.         --display dialog startMsg giving up after 2
  625.         set intermediateFolder to intermediateDownloadFolder & intermediateSubFolder
  626.         log "intermediateFolder is " & intermediateFolder
  627.        
  628.         if (count of theMessages) = 0 then
  629.             log "odd no messages to process."
  630.             display dialog "Odd, no messages to process." giving up after longWait
  631.             return 1
  632.         end if
  633.        
  634.         -- mail requires download to the Downloads or subfolders of Downloads
  635.         -- for some reason, this gets the path to this app when invoked by mail.
  636.         set pathToHome to (path to home folder) as string
  637.         log ("pathToHome  is " & pathToHome)
  638.         set listOfPathToHome to textToList(pathToHome, ":")
  639.         set pathToHome to item 1 of listOfPathToHome & ":" & item 2 of listOfPathToHome & ":" & item 3 of listOfPathToHome & ":"
  640.         log ("revised pathToHome is " & pathToHome)
  641.        
  642.         -- make intermediate folder
  643.         try
  644.             tell application "Finder"
  645.                 set newfolder to make new folder at (pathToHome & intermediateDownloadFolder) with properties {name:intermediateSubFolder}
  646.                 my debugLog("Created folder " & pathToHome & intermediateDownloadFolder & intermediateSubFolder)
  647.             end tell
  648.         on error errMsg number n
  649.             -- It's ok if the folder already exits [ -48 ]. Put out warning for all other errors.  
  650.             if n is not -48 then
  651.                 set commonError to "on error " & intermediateSubFolder & " the errMsg is " & errMsg & " number is " & n
  652.                 display dialog commonError giving up after longWait
  653.                 my debugLog(commonError)
  654.                 return 2
  655.             end if
  656.         end try
  657.        
  658.         -- make final destination folder
  659.         try
  660.             tell application "Finder"
  661.                 set newfolder to make new folder at pathToHome with properties {name:finalDestination}
  662.                 my debugLog("Created  final destination folder " & pathToHome & finalDestination)
  663.             end tell
  664.         on error errMsg number n
  665.             -- It's ok if the folder already exits [ -48 ]. Put out warning for all other errors.  
  666.             if n is not -48 then
  667.                 set commonError to "on error " & finalDestination & " errMsg is " & errMsg & " number is " & n
  668.                 display dialog commonError giving up after longWait
  669.                 my debugLog(commonError)
  670.                 return 3
  671.             end if
  672.         end try
  673.        
  674.        
  675.         tell application "Mail"
  676.             --activate
  677.             log "was activated"
  678.            
  679.             -- look throught the messages we selected.
  680.             repeat with aMessage in theMessages -- loop through each message
  681.                 log "class of aMessage is " & class of aMessage
  682.                
  683.                 -- get the senders email address
  684.                 set fromMail to aMessage's sender
  685.                 my debugLog("fromMail is " & fromMail)
  686.                
  687.                 -- Create folder for the individual student.
  688.                 -- ---- Set final target folder ---->
  689.                 set pathToStudents to pathToHome & finalDestination & ":"
  690.                 my debugLog("pathToStudents is " & pathToStudents)
  691.                 repeat 1 times -- sinulate continue
  692.                     try
  693.                         tell application "Finder"
  694.                             set newStudent to make new folder at pathToStudents with properties {name:fromMail}
  695.                             my debugLog("Created final destination subfolder " & pathToStudents & fromMail)
  696.                         end tell
  697.                     on error errMsg number n
  698.                         -- It's ok if the folder already exits [-48 ]. Put out warning for all other errors.
  699.                         if n is not -48 then
  700.                             set commonError to "attempting to create " & pathToStudents & fromMail & return & " on error the errMsg is " & errMsg & " number is " & n
  701.                             display dialog commonError giving up after longWait
  702.                             my debugLog(commonError)
  703.                             exit repeat -- look at next message. simulate iterate here.
  704.                         end if
  705.                     end try
  706.                    
  707.                     set pathToTheStudent to pathToStudents & fromMail & ":"
  708.                     my debugLog("pathToTheStudent is " & pathToTheStudent)
  709.                     -- repeat with aFile in aMessage's mail attachments
  710.                     -- set ourList to every mail attachment of aMessage                
  711.                     repeat with aFile in (mail attachments of aMessage)
  712.                         log "save aFile"
  713.                         repeat 1 times -- sinulate continue
  714.                            
  715.                             --if (downloaded of aFile) then -- check if file is already downloaded
  716.                             set attachmentName to name of aFile
  717.                             my debugLog("attachmentName is " & attachmentName)
  718.                             set {fileName, fileExt} to my getNameExt(attachmentName)
  719.                             log "fileName  is " & fileName & " fileExt  is " & fileExt
  720.                             -- ---- Intermediate folder target ---->
  721.                             -- apple changed mail to require the download to be in the downloads folder :-(
  722.                             set pathForDownload to pathToHome & intermediateFolder & ":"
  723.                            
  724.                             set clearCount to 0
  725.                             set destPath to pathForDownload & attachmentName
  726.                             set finalDestPath to pathToStudents & fromMail & ":" & attachmentName
  727.                             log "check for free name. clearCount is " & clearCount & return & " destPath is " & destPath & return & " finalDestPath is " & finalDestPath
  728.                            
  729.                             repeat while my fileExists(destPath) or my fileExists(finalDestPath)
  730.                                 set clearCount to clearCount + 1
  731.                                 log "clearCount is " & clearCount
  732.                                 set destPath to pathForDownload & fileName & "#" & clearCount & "." & fileExt
  733.                                 set finalDestPath to pathToStudents & fromMail & ":" & fileName & "#" & clearCount & "." & fileExt
  734.                                 log "searching for free name. clearCount is " & clearCount & return & " destPath is " & destPath & return & " finalDestPath is " & finalDestPath
  735.                             end repeat -- while  
  736.                             log "found. destPath is " & destPath
  737.                             save aFile in destPath as native format
  738.                             log "file was saved."
  739.                            
  740.                             -- move it right on to file location.
  741.                             -- debuggin to see if we got the right name
  742.                             my debugLog("Saved to intermediate.  destPath is " & destPath)
  743.                            
  744.                             if my fileExists(destPath) then
  745.                                 tell application "Finder"
  746.                                     try
  747.                                         -- from file filename path to full folder name path :-(.
  748.                                         move destPath to pathToTheStudent
  749.                                         my debugLog("saved to final folder pathToTheStudent is " & pathToTheStudent)
  750.                                     on error msg number n
  751.                                         set outMsg to "Got error message while moving " & destPath & " to " & pathToTheStudent & return & "message is " & msg & return & "number is " & n
  752.                                         my debugLog(outMsg)
  753.                                         display dialog outMsg giving up after longWait
  754.                                         -- might as well try the next attachment
  755.                                         exit repeat -- look at next message. simulate iterate here.                                    
  756.                                     end try
  757.                                 end tell
  758.                             else
  759.                                 -- very bad, folder doesn't exist as expected.
  760.                                 my debugLog("very bad, folder  " & destPath & " doesn't exist as expected.")
  761.                                 exit repeat -- look at next message. simulate iterate here.    
  762.                             end if
  763.                            
  764.                         end repeat -- one time to make like a continue statment
  765.                     end repeat -- next attached file
  766.                 end repeat -- continue
  767.             end repeat -- next message
  768.         end tell --tell app "Mail"
  769.         return 0
  770.     end perform mail action with messages
  771. end using terms from
  772.  
  773.  
  774. (* ======================== Subroutines ======================= *)
  775. -- ------------------------------------------------------  
  776. (*
  777. *)
  778. on appendToFile(fileId, theData)
  779.    
  780.     local theSize, writeWhere
  781.    
  782.     set theSize to (get eof fileId)
  783.     set writeWhere to theSize + 1 as integer
  784.     write theData to fileId starting at writeWhere
  785.    
  786. end appendToFile
  787.  
  788. -- ------------------------------------------------------  
  789. (*
  790.  debug(<string>)
  791.  Write messages to a log file.
  792.  
  793.   -- Need to place these two lines in the calling routine.
  794.     global debugRunning
  795.     set debugRunning to ""
  796.  -- references appendToFile()  
  797.   -- example:
  798.     debug("start program. Reading from " & listOfFiles)
  799.    
  800.    found here: /Users/mac/Documents/BJ\ Prior\ Years/BJ2004/sendmailapp2\ copy
  801.  
  802. *)
  803. on debug(theMessage)
  804.     -- return
  805.     global debugRunning
  806.     local theSize, startupDiskName, pathToLog, fileReference
  807.    
  808.     set pathToLog to (path to home folder as text) & "tryAttachmentsLog.txt"
  809.     -- log "pathToLog is " & pathToLog
  810.     -- display dialog "pathToLog is " & pathToLog giving up after 4
  811.    
  812.     try
  813.         -- Complete the path.
  814.         set pathToLog to pathToLog as text
  815.         set fileReference to (open for access file pathToLog ¬
  816.             with write permission)
  817.        
  818.         if debugRunning = "" then
  819.             set theSize to (get eof fileReference)
  820.             if theSize > 0 then
  821.                 appendToFile(fileReference, " " & return)
  822.             end if
  823.             appendToFile(fileReference, "   --- debug on " & ((current date) as string) & "   --- " & return)
  824.             set debugRunning to "running"
  825.         end if
  826.         -- log "theMessage " & theMessage
  827.         -- display dialog "in debug..." & return & "theMessage " & theMessage giving up after 3
  828.         appendToFile(fileReference, theMessage & return)
  829.        
  830.         close access fileReference
  831.         tell application "Finder"
  832.             set the creator type of the file pathToLog ¬
  833.                 to "R*ch"
  834.         end tell
  835.     on error mes number n
  836.         try
  837.             set commonErr to "error ... " & mes & " error number is " & n
  838.             log commonErr
  839.             close access fileReference
  840.             display dialog commonErr giving up after 4
  841.         end try
  842.        
  843.     end try
  844.     -- log "end of debug"
  845. end debug
  846.  
  847. (*
  848. write log message to script editor log and to our file log
  849. *)
  850. on debugLog(theMessage)
  851.     log "debugLog: " & theMessage
  852.     return debug(theMessage)
  853. end debugLog
  854.  
  855. -- ------------------------------------------------------  
  856. (*
  857.   ideas from:
  858.   https://stackoverflow.com/questions/3469389/applescript-testing-for-file-existence
  859.  
  860.  use the alias way.
  861. *)
  862. on fileExists(theFile) -- (String) as Boolean
  863.     (* "System Events" and "Finder" checking for file existance revealed problems. l*)
  864.     set debugging to false
  865.     if debugging then log "  fileExists: theFile is " & theFile
  866.     try
  867.         set theAlias to theFile as alias
  868.         set theExistance to true
  869.     on error errMsg number n
  870.         if debugging then log "  fileExists: n is " & n
  871.         -- File or folder doesn't exist.
  872.         if n is not -43 then
  873.             set commonError to "on error the errMsg is " & errMsg & " number is " & n
  874.             if debugging then log "  fileExists: " & commonError
  875.             display dialog commonError giving up after 10
  876.             -- cause grief above.
  877.             error "Failure of alias." number -1
  878.         else
  879.             set theExistance to false
  880.         end if
  881.     end try
  882.     if debugging then log "  fileExists: theExistance is " & theExistance
  883.     return theExistance
  884. end fileExists
  885.  
  886. (*
  887.   Philip Regan
  888.   https://stackoverflow.com/questions/3469389/applescript-testing-for-file-existence
  889. *)
  890. (*on fileExists(theFile) -- (String) as Boolean
  891.     tell application "System Events"
  892.         if exists file theFile then
  893.             return true
  894.         else
  895.             return false
  896.         end if
  897.     end tell
  898. end fileExists*)
  899.  
  900. -- ------------------------------------------------------
  901. (*
  902.    Yvan Koenig
  903.    https://macscripter.net/viewtopic.php?id=43133
  904.    with mods for no extension present
  905.    
  906. *)
  907. on getExt(theName)
  908.     if (offset of "." in theName) is greater than 0 then
  909.         set saveTID to AppleScript's text item delimiters
  910.         set AppleScript's text item delimiters to {"."}
  911.         set theExt to last text item of theName
  912.         set AppleScript's text item delimiters to saveTID
  913.         if theExt ends with ":" then set theExt to text 1 thru -2 of theExt
  914.     else
  915.         set theExt to ""
  916.     end if
  917.     return theExt
  918. end getExt
  919.  
  920. -- ------------------------------------------------------
  921. (*
  922.     Input: a file with or without an extension.
  923.     hhas
  924.     https://forums.macrumors.com/threads/applescript-to-get-file-name.927338/
  925.    
  926.     may not work with folders with extensions like apps.
  927.    
  928.     Test cases:
  929.                 set fileName to " "                  
  930.                 set fileExt to my getExt(attachmentName)
  931.                 log "fileName  is " & fileName & " fileExt  is " & fileExt
  932.                 set fileExt to my getExt("testfileNo")
  933.                 log "fileName  is " & fileName & " fileExt  is " & fileExt
  934.                 set fileExt to my getExt("path:to:testfileNo:")
  935.                 log "fileName  is " & fileName & " fileExt  is " & fileExt
  936.                 log ">>>>>>>>>>>>>>>>>>>>>>"
  937.                 set {fileName, fileExt} to my getNameExt(attachmentName)
  938.                 log "fileName  is " & fileName & " fileExt  is " & fileExt
  939.                 set {fileName, fileExt} to my getNameExt("testfileNo")
  940.                 log "fileName  is " & fileName & " fileExt  is " & fileExt
  941.                 set {fileName, fileExt} to my getNameExt("path:to:testfileNo:")
  942.                 log "fileName  is " & fileName & " fileExt  is " & fileExt
  943. *)
  944. on getNameExt(fileName)
  945.     set saveTID to AppleScript's text item delimiters
  946.     set AppleScript's text item delimiters to "."
  947.     if fileName contains "." then
  948.         set {displayName, nameExt} to {text 1 thru text item -2, text item -1} of fileName
  949.     else
  950.         set {displayName, nameExt} to {fileName, ""}
  951.     end if
  952.     set AppleScript's text item delimiters to saveTID
  953.    
  954.     return {displayName, nameExt}
  955. end getNameExt
  956. -- ------------------------------------------------------
  957. (*
  958.     modified to let the extension be.
  959.  
  960.     by mklement0
  961.     https://stackoverflow.com/questions/5770384/how-find-the-file-name-of-an-executing-applescript
  962. *)
  963. on getMyName()
  964.     local myAlias, myName
  965.     tell application "System Events"
  966.         set myAlias to path to me -- alias to the file/bundle of the running script
  967.         set myName to name of myAlias -- filename with extension, if any.
  968.         -- leave extension alone.
  969.     end tell
  970.     return myName
  971. end getMyName
  972.  
  973. -- ------------------------------------------------------
  974. (*
  975.    ls_l is list file with options  
  976.   the format is best for debuging.
  977.  
  978.   example usage:
  979.   set {fileExists, fromUnix} to ls_l(attachmentNamePath, "-l")
  980.   log "attachmentNamePath fileExists is " & fileExists & return & " fromUnix is " & fromUnix
  981.  
  982.   *)
  983. on ls_l(attachmentNamePath, options)
  984.     --log "ls_l"
  985.     --log options
  986.    
  987.     set unixAttachmentNamePath to POSIX path of attachmentNamePath
  988.     --log "unixDesktopPath = " & unixAttachmentNamePath
  989.    
  990.     set quotedUnixAttachmentNamePath to quoted form of unixAttachmentNamePath
  991.     --log "quoted form is " & quotedUnixAttachmentNamePath
  992.     try
  993.         set fromUnix to do shell script "ls " & options & " " & quotedUnixAttachmentNamePath
  994.         set fromUnix to "ls " & options & return & fromUnix
  995.         set fileExists to true
  996.     on error errMsg number n
  997.         set fromUnix to "ls " & options & "  error..." & errMsg & " with number " & n
  998.         set fileExists to false
  999.        
  1000.     end try
  1001.     return {fileExists, fromUnix}
  1002. end ls_l
  1003.  
  1004. -- ------------------------------------------------------
  1005. (*
  1006. textToList seems to be what you are trying to do
  1007.   thisText is the input string
  1008.   delim is what to split on
  1009.  
  1010.   returns a list of strings.  
  1011.  
  1012. - textToList was found here:
  1013. - http://macscripter.net/viewtopic.php?id=15423
  1014.  
  1015. *)
  1016.  
  1017. on textToList(thisText, delim)
  1018.     set resultList to {}
  1019.     set {tid, my text item delimiters} to {my text item delimiters, delim}
  1020.    
  1021.     try
  1022.         set resultList to every text item of thisText
  1023.         set my text item delimiters to tid
  1024.     on error
  1025.         set my text item delimiters to tid
  1026.     end try
  1027.     return resultList
  1028. end textToList
  1029. *)
Advertisement
Comments
  • Avery75
    103 days
    # text 0.28 KB | 0 0
    1. Use tar in order to create your backup file. ...
    2. The important command here is the following: ...
    3. Schedule your backup task. ...
    4. minute (0–59) hour (0–23) day (1–31) month (1–12) weekday (0–6) command. ...
    5. 29 0 * * * /bin/bash/path/backup_script.sh.https://buyghostgunskit.com/
Add Comment
Please, Sign In to add comment
Advertisement