Я не уверен, что могу помочь с точной причиной сбоя вашего скрипта, но я мог бы помочь вам понять, где он не работает.
Прежде всего, я бы заменил список файлов расширения, которые вы должны 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