AppleScript для автоматического сохранения почтовых вложений - работает для новых, но не для старых писем - PullRequest
0 голосов
/ 14 июля 2020

Спасибо всем за вашу помощь. И извиняюсь, я задал это в разделе «Ответ» предыдущего вопроса, который, как я теперь понимаю, мне не следовало делать ... так что я начал здесь новый вопрос.

Итак, я хотел напишите сценарий для сохранения вложений в сообщениях электронной почты по мере их поступления - с отдельной папкой для каждого отправителя электронной почты. Мне очень помогли люди на этом сайте.

Это вроде как работает ..... для новых входящих писем работает отлично, но когда я запускаю его против моих старых писем в моем почтовом ящике, это немного экономит вложения, а не другие.

Я думал, что проблема связана с ошибкой при поиске дубликата (что, как я думал, маловероятно, поскольку я добавил отметку времени к имени файла вместе со штампом данных электронного письма). Я добавил процесс удаления delFile, чтобы проверить наличие файла с таким же именем и, если он найдет его, удалить его.

Когда я выполняю скрипт, он обрабатывает еще несколько вложений, чем раньше, но не все в любом случае. .... и, что интересно, ничего не помещается в корзину sh.

Теперь я в тупике !! Как новичок в AppleScript, я еще не знаю, как отлаживать или обрабатывать ошибки.

Кто-нибудь может помочь, пожалуйста?

use scripting additions

using terms from application "Mail"
    on perform mail action with messages messageList for rule aRule
        set destinationPath to (POSIX file "/volumes/Data/Dropbox/WORK ITEMS/Email Attachments/") as string
        tell application "Mail"
            repeat with aMessage in messageList
                repeat with anAttachment in mail attachments of aMessage
                    set senderName to (extract name from sender of aMessage)
                    set {year:y, month:m, day:d, hours:h, minutes:min} to date received of aMessage
                    set timeStamp to (d & "/" & (m as integer) & "/" & y & " " & h & "." & min) as string
                    set attachmentName to timeStamp & " - " & name of anAttachment
                    
                    set doSave to true
                    set originalName to name of anAttachment
                    if originalName contains "jpg" then
                        set doSave to false
                    else if originalName contains "jpeg" then
                        set doSave to false
                    else if originalName contains "gif" then
                        set doSave to false
                    else if originalName contains "png" then
                        set doSave to false
                    else if originalName contains "html" then
                        set doSave to false
                    else if originalName contains "ics" then
                        set doSave to false
                    end if
                    
                    if doSave is true then
                        tell application "System Events"
                            if not (exists folder (destinationPath & senderName)) then
                                make new folder at end of alias destinationPath with properties {name:senderName}
                            end if
                        end tell
                    end if
                    
                    if doSave is true then
                        set delFile to destinationPath & senderName & ":" & attachmentName
                        tell application "System Events" to if (exists file delFile) then delete file delFile
                    end if
                    
                    if doSave is true then save anAttachment in file (destinationPath & senderName & ":" & attachmentName) with replacing
                    
                    
                    
                end repeat
            end repeat
        end tell
        
    end perform mail action with messages
end using terms from

Спасибо

1 Ответ

1 голос
/ 14 июля 2020

Я не уверен, что могу помочь с точной причиной сбоя вашего скрипта, но я мог бы помочь вам понять, где он не работает.

Прежде всего, я бы заменил список файлов расширения, которые вы должны sh исключить на длительный период if ... else if. Что-то вроде:

set ignore list to {".jpg", ".jpeg", ".gif", ".png", ".html", ".ics"} в верхней части скрипта с set fileExtension to rich text (offset of "." in originalName) thru end of originalName в l oop.

Затем вы можете проверить:

if fileExtension is not in ignoreList then

и оберните его вокруг кода сохранения (вам не нужно выполнять один и тот же тест несколько раз).

Я думаю, что ваш блок удаления файла избыточен, потому что он должен делать то же самое как следующий save...with replacing (если файл уже существует). (Вы можете удалить файл, если он существует, и в этом случае удалите with replacing позже.)

Чтобы начать отладку, сначала удалите верхний код, который работает с входящими сообщениями, и замените его с set messageList to selection. Попробуйте вставить display dialog <varname> в местах, где вы не знаете, что происходит. Например, вы знаете, что такое приложение, но уверены ли вы, что такое destinationPath & senderName & ":" & attachmentName?

Наконец, обратите внимание, что я НЕ запускал это на ВАШИХ данных, поэтому обязательно сделайте резервную копию. Он не должен ничего разрушать, но лучше перестраховаться, чем сожалеть!

Пожалуйста, возвращайтесь с любыми вопросами. Удачи!

EDIT:

Я добавил функцию вверху (блок on getExtension(fileName). Это вызывается строкой set fileExtension to my getExtension(originalName)

Это для уточнение получения расширения путем переворота строки имени так, чтобы был найден только первый '.'. После получения расширение перевернутое.

Другой важной частью является то, что оно содержит try ... on error ... end try. Вот как AppleScript делает ошибку Если нет '/', выдается ошибка. Это перехватывается on error, которое возвращает 'skip'. (На данный момент это не используется в основной программе, но может использоваться для направления всего вывода в общая папка.)

Последнее изменение заключается в том, что я обернул часть сохранения в If originalName does not contain "/" then ... end if. Это нужно для того, чтобы поймать те файлы, которые содержат '/', и «перепрыгнуть» через них, ничего не делая.

Мне НЕ нужно было добавлять delay, поэтому попробуйте начать без него. Это могло быть отвлекающим маневром!

set ignoreList to {".jpg", ".jpeg", ".gif", ".png", ".html", ".ics"}
set destinationPath to (POSIX file "/volumes/Data/Dropbox/WORK ITEMS/Email Attachments/") as string

on getExtension(fileName)
    try
        set fileName to (reverse of every character of fileName) as string
        set extension to text 1 thru (offset of "." in fileName) of fileName
        set extension to (reverse of every character of extension) as string
        return extension
    on error
        return "skip"
    end try
end getExtension


tell application "Mail"
    set messageList to selection
    
    repeat with aMessage in messageList
        repeat with anAttachment in mail attachments of aMessage
            set senderName to (extract name from sender of aMessage)
            set {year:y, month:m, day:d, hours:h, minutes:min} to date received of aMessage
            set timeStamp to (d & "/" & (m as integer) & "/" & y & " " & h & "." & min) as string
            set attachmentName to timeStamp & " - " & name of anAttachment
            set originalName to name of anAttachment
            if originalName does not contain "/" then
                set fileExtension to my getExtension(originalName)
                if fileExtension is not in ignoreList then
                    
                    tell application "System Events"
                        if not (exists folder (destinationPath & senderName)) then
                            make new folder at end of alias destinationPath with properties {name:senderName}
                        end if
                    end tell
                    
                    save anAttachment in file (destinationPath & senderName & ":" & attachmentName) with replacing
                end if
            end if
        end repeat
    end repeat
    
end tell

Для звонков из правила почты:

use scripting additions

set ignoreList to {".jpg", ".jpeg", ".gif", ".png", ".html", ".ics"}
set destinationPath to (POSIX file "/Users/bernardharte/test/") as string

on getExtension(fileName)
    try
        set fileName to (reverse of every character of fileName) as string
        set extension to text 1 thru (offset of "." in fileName) of fileName
        set extension to (reverse of every character of extension) as string
        return extension
    on error
        return "skip"
    end try
end getExtension

using terms from application "Mail"
    on perform mail action with messages messageList for rule aRule
        
        tell application "Mail"
            
            repeat with aMessage in messageList
                repeat with anAttachment in mail attachments of aMessage
                    set senderName to (extract name from sender of aMessage)
                    set {year:y, month:m, day:d, hours:h, minutes:min} to date received of aMessage
                    set timeStamp to (d & "/" & (m as integer) & "/" & y & " " & h & "." & min) as string
                    set attachmentName to timeStamp & " - " & name of anAttachment
                    set originalName to name of anAttachment
                    if originalName does not contain "/" then
                        set fileExtension to my getExtension(originalName)
                        if fileExtension is not in ignoreList then
                            
                            tell application "System Events"
                                if not (exists folder (destinationPath & senderName)) then
                                    make new folder at end of alias destinationPath with properties {name:senderName}
                                end if
                            end tell
                            
                            save anAttachment in file (destinationPath & senderName & ":" & attachmentName) with replacing
                        end if
                    end if
                end repeat
            end repeat
            
        end tell
        
    end perform mail action with messages
end using terms from
...