Guarde los archivos adjuntos de Mail.app según los temas

2

Lo que estoy tratando de hacer: tengo que escanear algunos escritos personales que hago para que mi mentor los revise, tengo 3 tipos de escritos: J, F, W. Utilizo mi escáner para enviarlos por correo electrónico (es una cuestión de trabajo, así que no puedo cambiarlo). Tuve la idea esta mañana de que podría poner el código en el asunto en el escáner y luego tener una regla para procesar los correos electrónicos y archivarlos en la carpeta correcta para mí.

Encontré y reutilizé el script en la publicación Guarda los archivos adjuntos de Mail.app según el tema , respuesta de markhunte

Estoy usando Mail en MacOSX 10.13.6

Para hacer pruebas, comenté la función de regla de correo.

Mi prueba es solo mía para seleccionar manualmente los mensajes en la aplicación de correo (se convertirá en regla una vez que funcione).

Una cosa que no puedo entender es que la primera vez que guarda el archivo no cambia el nombre del archivo. Verás que he usado registros para ayudarme a resolver esto. En la primera ejecución de la secuencia de comandos, la instrucción IF cree que la carpeta existe y, por lo tanto, no cambia el nombre del archivo, vuelve a ejecutar la secuencia de comandos y la cambia de nombre correctamente.

Al sentirse un poco confundido, la ayuda sería muy apreciada.

Mi correo electrónico tiene líneas de asunto con una letra en ellas (lo hago cuando escaneo documentos para hacerlo más fácil). El nombre del archivo adjunto es siempre scan.pdf

TambiénparecehaberunproblemaconlacodeList,noencuentraelprimerelementoenlaLista(poresotengoJdosveces),noesungranproblemaactualmente.

(*usingtermsfromapplication"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*)
    
pregunta mgguinne 12.09.2018 - 03:01

1 respuesta

0

Lo encontré. La primera configuración de savePath no tiene el código adicional para cambiar el nombre del archivo (por cualquier motivo). También obtuve un código de inicio de semana incluido para crear carpetas dinámicas de semana.

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

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

Código completo:

 # 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*)
    
respondido por el mgguinne 12.09.2018 - 06:39

Lea otras preguntas en las etiquetas