Applescript для сохранения загруженных писем в формате PDF и их вложений - PullRequest
0 голосов
/ 20 апреля 2020

У меня есть запрос.

Я пришел из MS Outlook 2011 и из-за системных требований в macOS 10.15+ я должен обновить наш пакет Office до версии 2019.

У меня был скрипт, который сохранял каждое только что загруженное письмо в формате PDF и их вложения в дереве папок> Дата -> Отправитель -> MAIL_Date_Sender_Subject.pdf. Вложения сохраняются отдельно в той же папке, используя оригинальное имя с ATT_ в качестве префикса. Я вставлю этот скрипт ниже.

Начиная с Office 2016, мы больше не можем использовать почтовые правила для запуска «запуска скрипта», но в Apple Mail это все еще возможно: D.

План был продолжать использовать MS Outlook 2019 в качестве ежедневного драйвера (почему? Я к этому привык и у него хороший набор функций) и запускать параллельную скрытую в фоновом режиме Apple Mail.

Я увидел здесь нечто похожее, что почти там, хотя это зависит от ввода пользователя (выбор) и показывает диалоговое окно принтера. https://macscripter.net/viewtopic.php?id=43790

Любая помощь будет принята с благодарностью

Вот скрипт, который я использовал с Ma c OSX 10.9 и MS Outlook 2011

текущее использование MacPro 2009 под управлением Ma c OS X 10.13.6 MacBook Pro под управлением macOS 10.14.4


#begin script
delay 2 --let imap sync with server
--DECLAREREN PROPERTYS
--name for the main folder where the mails are saved 
property MailFolderIn : "inkomendeMail"
property MailFolderUit : "uitgaandeMail"

--name of the folder within the homefolder where the mailfolder is kept
property MailParentFolder : "Documents"

--prefix for mails
property MailPrefix : "MAIL_"

--prefix for attachments
property AttPrefix : "ATT_"

--Subroutine to remove special characters : / &
on RemoveChar(TxtCharRemove)
    set AppleScript's text item delimiters to ":"
    set TxtItem to text items of TxtCharRemove
    set AppleScript's text item delimiters to {""}
    set TxtCharRemove to TxtItem as string
    set AppleScript's text item delimiters to {""}

    set AppleScript's text item delimiters to "/"
    set TxtItem to text items of TxtCharRemove
    set AppleScript's text item delimiters to {""}
    set TxtCharRemove to TxtItem as string
    set AppleScript's text item delimiters to {""}

    set AppleScript's text item delimiters to "&"
    set TxtItem to text items of TxtCharRemove
    set AppleScript's text item delimiters to {""}
    set TxtCharRemove to TxtItem as string
    set AppleScript's text item delimiters to {""}


    set AppleScript's text item delimiters to ","
    set TxtItem to text items of TxtCharRemove
    set AppleScript's text item delimiters to {""}
    set TxtCharRemove to TxtItem as string
    set AppleScript's text item delimiters to {""}

    return TxtCharRemove
end RemoveChar

--subroutine folder creation
on MakeSubMap(PathNaarParentMap, NaamVanDeFolder)
    tell application "Finder"
        if not (exists folder NaamVanDeFolder in folder PathNaarParentMap) then
            make new folder in PathNaarParentMap with properties {name:NaamVanDeFolder}
        end if
    end tell
end MakeSubMap

(*--subroutine wachten tot de mail volledig is gedownloaded (gemaakt in Versie 5)
on WaitForMail(mailMsg)
    tell application "Microsoft Outlook"
        if (is partially downloaded) of mailMsg = true then
            repeat while (is partially downloaded) of mailMsg = true
                delay 0.5
            end repeat
            exit repeat
        else
            --display dialog "volledig"
        end if
    end tell
end WaitForMail*)

--Boolean subroutine, to check if the mail is incoming or outgoing 
on CheckMailType(myMsg)
    tell application "Microsoft Outlook"
        try
            if (was sent) of myMsg = true then
                return true
            end if
        on error
            return false
        end try
    end tell
end CheckMailType

--Boolean subroutine, to filter attachments smaller than 100kb (footers and stuch)
on CheckAtt(myAtt)
    --filesize ophalen
    tell application "Microsoft Outlook"
        set AttFileSize to file size of myAtt
        set AttFileType to content type of myAtt

    end tell
    if AttFileType = "image/jpeg" and AttFileSize < 50000 then

        return true
    else
        if AttFileType = "image/png" or AttFileType = "image/gif" then
            if AttFileSize < 100000 then --100kB
                return true
            else
                return false
            end if
        else
            return false
        end if

        return false
    end if
end CheckAtt

(*
//////////////////
Einde subroutines Begin hoofscript
//////////////////
*)


-- collecting data from email

tell application "Microsoft Outlook"
    set msg to first item of (get current messages)
    if ((subject of msg) is missing value) then
        set msgSubject to ("<no subject>")
    else
        set msgSubject to (subject of msg)
    end if

    set MsgTimeSent to (time sent) of msg as date
    set MsgTimeSentStr to (year of MsgTimeSent & "_" & ((month of MsgTimeSent) as integer) & "_" & day of MsgTimeSent) as string
    set MsgSender to ((sender) of msg)
    try
        set MsgSender to (name of MsgSender) as string
    on error
        set MsgSender to "unknown"
    end try

    set cAttMsg to count (attachments of msg)
    set msgToRecipient to ((to recipient) of msg)
    set msgRecipient to (first item of msgToRecipient)
    set msgRecipientAddress to (email address) of msgRecipient
    try
        set msgRecipientName to name of msgRecipientAddress
    on error
        set msgRecipientName to "unknown"
    end try
end tell

--determenation of incoming or outgoing
if CheckMailType(msg) = true then
    set MailFolder to MailFolderUit
    set MsgSenderReciever to msgRecipientName
else
    set MailFolder to MailFolderIn
    set MsgSenderReciever to MsgSender
end if

--set the home folder and Documents als text
set DestPath to ((path to home folder) & MailParentFolder) as string

--set the path to the MailFolder in the MailParentFolder of the home folder
set MailFolderPath to DestPath & ":" & MailFolder

--set de subFolderMail folder with timestamp, on the date of the script, parameter
set MailSubTimeFolder to (do shell script "date '+%Y_%m_%d'")

MakeSubMap(DestPath, MailFolder) --maak een map inkomende of uitgaande mail is documenten

MakeSubMap(MailFolderPath, MailSubTimeFolder) --maak een map in inkomende of uitgaande mail met datum tijdens het uitvoeringsscript

MakeSubMap(MailFolderPath & ":" & MailSubTimeFolder, MsgSenderReciever) --map aanmaken per afzender in de datum map

set MsgSubjectFileName to MailPrefix & MsgTimeSentStr & "_[" & MsgSenderReciever & "]_" & RemoveChar(msgSubject) --naam creeren op basis van het onderwerp van de mail

set MailFolder to (MailFolderPath & ":" & MailSubTimeFolder & ":" & MsgSenderReciever) --path stellen naar de map waar de mails worden bewaard


if cAttMsg = 0 then
    set FileNameMsg to (POSIX path of (MailFolder) & "/" & MsgSubjectFileName & ".pdf") --filename creation

    tell application "Microsoft Outlook"
        print msg with properties {as pdf:true, path name:FileNameMsg}
    end tell

else
    MakeSubMap(MailFolder, MsgSubjectFileName) --map aanmaken voor mails met attachments
    set FileNameMsg to (POSIX path of (MailFolder) & "/" & MsgSubjectFileName & "/" & MsgSubjectFileName & ".pdf")

    tell application "Microsoft Outlook"
        print msg with properties {as pdf:true, path name:FileNameMsg}

        --opslaan van de attachments
        repeat with i from 1 to cAttMsg

            set Att to (item i of attachments) of msg
            --display dialog CheckAtt(Att) of me
            if my CheckAtt(Att) = false then -- bijlagen als png kleiner dan 100kb worden niet opgeslagen
                set AttName to name of (item i of attachments) of msg as string
                set AttName to RemoveChar(AttName) of me

                set AttName to (AttPrefix & MsgTimeSentStr & "_" & AttName)


                set tempPath to (POSIX path of (MailFolder) & "/" & MsgSubjectFileName & "/" & AttName) as string

                save ((item i of attachments) of msg) in file tempPath
            end if
        end repeat

    end tell
end if

if CheckMailType(msg) = true then
    display notification msgSubject & " is als pdf in archief geplaatst." with title "mail 2 pdf - " & MailFolderUit subtitle MsgSenderReciever
else
    display notification msgSubject & " is als pdf in archief geplaatst." with title "mail 2 pdf - " & MailFolderIn subtitle MsgSenderReciever
end if

delay 1

beep 2



...