Willkommen auf der Blog-Seite von hubionmac.com!
Alles rund um AppleScript und was mich sonst noch so interessiert ;-)!

Die Idee war vor fast 9 Jahren irgendwie Emails zu Archivieren.. (ich persönlich habe einfach ein riesiges Mail-Postfach auf meinem Synology-NAS, in dass jedes Jahr die alten Emails wandern). Nun dieses Skript pfuscht etwas (öffnet den Druck-Dialog über den Keyboard-Shortcut) und druckt die Email das PDF aus. Die Anhänge einer Email werden kurz im Download-Ordner gepspeichert (Sicherheitsvorgabe von OSX) und dann in den Unterordner der Nachricht ~/Desktop/mail_archiv verschoben.

Achtung: Auf Grund der Tatsache, dass das Script Tastatur-Befehler ausführen muss, um zu funktionieren, muss die Anwendung die das Script ausführt die entsprechenden Rechte für Bedienungshilfen erhalten.


-- Save Mail as PDF and it's attachments to folder
-- Created by hubionmac (22.03.2010) requested by Udo
-- Update by hubionmac (09.01.2019)
--  - works now with 10.13.6
--  - the name of the outputfolder my contain the time and no just the date (see variable showtimeinfoldername)
--  - checkname-function updated so it works with suffixes > 3 characters
-- - Save Attachment into any other folder than downloads does not work out of the box with newer OSX, so first save inside downloads (subfolders are allowed) and then move it to it's final destination ;-) 

global frontmost_message_viewer
--this is the posix (unix) path of the folder you would like to store the messages in
--#####settings
set showtimeinfoldername to true
--#####settings

tell application "Finder" to set mymailboxpath to POSIX path of ((desktop) as alias) & "mail_archiv/"
tell application "Mail"
    set myselection to my check_message_viewer_and_return_selection()
    --works only with one selected message for many reasons...
    if (count of myselection) = 1 then
        repeat with currentMail in myselection

            set currentSender to my (getEmail(sender of currentMail))
            set currentDateSent to my getDatestring(date sent of currentMail, showtimeinfoldername)
            set currentSubject to my replace_chars(my replace_chars(subject of currentMail, ":", "-"), "/", ":")
            --Doppelpunkte kommen bei Dateinamen nicht so gut
            set currentFolder2Store to mymailboxpath & currentDateSent & " " & currentSender & " " & currentSubject & "/" as string
            my create_messagefolder(currentFolder2Store)
            try
                do shell script "mkdir ~/downloads/tmp_mail_downloads"
            end try
            repeat with a in (every mail attachment of currentMail)
                set current_a_name to name of a
                set current_a_name to my checkname_with_pdf_suffix(current_a_name, path to downloads folder, false)

                save a in ((((path to downloads folder) as string) & "tmp_mail_downloads:" & current_a_name) as string)
                do shell script "mv ~/downloads/tmp_mail_downloads/" & quoted form of current_a_name & " " & quoted form of currentFolder2Store
            end repeat
            set desktop_pdf_name to my checkname_with_pdf_suffix("1.pdf", path to desktop, false)
            set the clipboard to desktop_pdf_name
            my print_current_mail_as_pdf()
            repeat until (index of window of frontmost_message_viewer) is 1
                delay 1
            end repeat
            my move_desktop_pdf(desktop_pdf_name, currentFolder2Store)
            --open destination folder in finder ( did it really work? YES!! =))
            do shell script "open " & quoted form of currentFolder2Store
        end repeat
    else
        error "Sorry, ich kann zur Zeit nur mit einer ausgewählten Email hantieren"
    end if
end tell
to move_desktop_pdf(desktop_pdf_name, currentFolder2Store)
    --used to move the printed pdf to it's final destination
    set finalname to checkname_with_pdf_suffix("__message.pdf", (POSIX file currentFolder2Store) as alias, false)
    try
        tell application "Finder" to do shell script "mv " & POSIX path of ((desktop) as alias) & quoted form of desktop_pdf_name & " " & quoted form of currentFolder2Store & quoted form of finalname
    on error msg
        error "Fehler beim Bewegen der gedruckten Nachricht:  " & msg as text
    end try
end move_desktop_pdf
to getEmail(mailstring)
    -- if an email contains the senders name like "Mr.Bla <bla@bla.com>" then returns just the email not leaves the name
    if mailstring contains "<" then
        return (characters ((offset of "<" in mailstring) + 1) through ((offset of ">" in mailstring) - 1) of mailstring) as text
    else
        return mailstring
    end if
end getEmail
to getDatestring(thedate, withtime)
    --format a date to a string like 2010-03-22
    set monthnum to characters -2 through -1 of ("0" & ((month of thedate) as integer)) as text
    set daynum to characters -2 through -1 of ("0" & ((day of thedate) as integer)) as text
    set yearnum to year of the thedate
    set hournum to characters -2 through -1 of ("0" & ((hours of thedate) as integer)) as text
    set minutnum to characters -2 through -1 of ("0" & ((hours of thedate) as integer)) as text
    if withtime is true then
        return yearnum & "-" & monthnum & "-" & daynum & " " & hournum & "-" & minutnum as text
    else
        return yearnum & "-" & monthnum & "-" & daynum as text
    end if
end getDatestring
to create_messagefolder(thepath_posix)
    --I love mkdir -p, simple, short, easy to use
    try
        do shell script "mkdir -p " & quoted form of thepath_posix
    on error msg
        error msg
    end try
end create_messagefolder
to replace_chars(this_text, search_string, replacement_string)
    --this replaces characters
    --used for folder and filenames, since a : must not be used for that
    if this_text contains the search_string then
        set AppleScript's text item delimiters to the search_string
        set the item_list to every text item of this_text
        set AppleScript's text item delimiters to the replacement_string
        set this_text to the item_list as string
        set AppleScript's text item delimiters to ""
    end if
    return this_text
end replace_chars
to checkname_with_pdf_suffix(n, D, looped)
    --check if filename exists in D
    -- so if "A File.pdf" exists it names it "A File 1.pdf","A File 2.pdf",...
    tell application "Finder"
        set thefiles to name of every item of (D as alias)
    end tell
    if thefiles contains n then
        if looped = false then
            set AppleScript's text item delimiters to "."
            set suffix to text item -1 of n
            set n to text items 1 through -2 of n
            set n to n as string
            set AppleScript's text item delimiters to ""
            set n to n & " 1." & suffix as string
            my checkname_with_pdf_suffix(n, D, true)
        else
            set AppleScript's text item delimiters to "."
            set suffix to text item -1 of n
            set n to text items 1 through -2 of n
            set n to n as string
            set AppleScript's text item delimiters to ""
            set tmp to ((last word of n as text) as integer)
            set tmpcount to (count of characters of (tmp as text)) + 5
            set tmp to tmp + 1
            set n to ((characters 1 through (-1 * tmpcount) of n) & tmp & "." & suffix) as text
            my checkname_with_pdf_suffix(n, D, true)
        end if
    else
        return n
    end if
end checkname_with_pdf_suffix
to print_current_mail_as_pdf()
    --hopefully works on every mac in every language =)
    -- GUI-Scripting is not the best way, but somehow the only way at the moment :-/
    tell application "Mail"
        activate
        tell application "System Events"
            tell process "Mail"

                keystroke "p" using command down
                set p to "false"
                repeat with i from 1 to 10
                    if (count of every sheet of window 1) > 0 then
                        set p to "ready"
                        exit repeat
                    end if
                    delay 1
                end repeat
                if p = "ready" then
                    click menu button 1 of sheet 1 of window 1
                    delay 0.25
                    key code 125
                    key code 125
                    delay 0.25
                    keystroke return
                    delay 1
                    click text field 1 of sheet 1 of sheet 1 of window 1
                    --click text field 1 of window 1 
                    keystroke "a" using command down
                    delay 0.25
                    keystroke "v" using command down
                    delay 0.25
                    keystroke "d" using command down
                    keystroke return
                else
                    error "timeout"
                end if
            end tell
        end tell
    end tell
end print_current_mail_as_pdf
to check_message_viewer_and_return_selection()
    -- check if frontmost window is a message viewer, otherwhise tell the user to RTFM!... wait there is no manual... don't care error change user!
    tell application "Mail"
        set frontmost_message_viewer to {}
        repeat with i from 1 to count of every message viewer
            if index of window of message viewer i = 1 then
                set frontmost_message_viewer to message viewer i
                exit repeat
            end if
        end repeat
        if frontmost_message_viewer = {} then
            error "Ist ja gar kein Message Viewer im Vordergrund, so kann ich einfach nicht arbeiten!"
        else
            return selection
        end if
    end tell
end check_message_viewer_and_return_selection
delay 5
tell application "Finder" to close window 1```

Continue reading...