Archive of articles classified as' "Apple Mail"

Back home

Mail: Bewege flagged Emails in Ordner XY

11/12/2011

Es ist schon erstaunlich, dass es keine Regel in Apple Mail zu geben scheint, mit der man markierte (diese kleine rote Flage) Emails automatisch in einen anderen Ordner verschieben kann... hm Vielleicht weil die Regeln in der Regel nur auf neue Emails angewendet werden, die von Natur aus nicht markiert sind...
Nun, diese Skript springt sofort auf markierte E-Mails an und verschiebt diese in definierbaren Ordner. In den Einstellungen die am Anfang des Skriptes gemacht werden können, kann der Account-Name, die zu durchsuchenden Ordner (Plural!) und der Zielordner angegeben werden. Um auch verschachtelte Ordner als Quelle oder Ziel angeben zu können, werden diese "Pfade" als Liste eingegeben... Erläuterung im Quelltext...
Ein netter Zusatz ist die Abfrage, ob Mail überhaupt läuft. So wird ein unfreiwilliger Start von Mail durch das Skript (z.B. via crontab) verhindert.

--10.12.2011 hubionmac.com

--Beweg Emails die markiert sind in einen anderen Ordner

-- In den Prefs können als Quelle mehrere Ordner angegeben werden

-- Unterordner werden in Form einer Liste angegeben z.B. um den Ordner Bla im Ordner Fasel anzugeben -> {"Fasel","Bla"}

--Beim Ziel-Ordner kann wahlweise angegeben werden, ob es sich um einen lokal oder ggf. um einen IMAP-Ordner des jeweiligen Accounts handelt


set theprefs to

{AccountName:"hubionmac.com", SourceFolders:{{"INBOX"}, {"Archive", "Kleiner Test"}}, DestinationFolder:{"Sammel", "Lager"}, DestinationFolderIsLocal:false}, ¬

{AccountName:"gmx.net", SourceFolders:{{"INBOX"}, {"bla", "blafasel"}}, DestinationFolder:{"Sammel", "Lager"}, DestinationFolderIsLocal:false} ¬

}

--prüfer erst mal ob Mail läuft… denn extra gestartet werden soll es deswegen mal nicht

tell application "System Events"

set MailIsRunning to (count of (every process whose bundle identifier is "com.apple.mail")) > 0

end tell

end

if MailIsRunning then

tell application "Mail"

repeat with todo in theprefs

set AccountName to AccountName of todo

set SourceFolders to SourceFolders of todo

set DestinationFolder to DestinationFolder of todo

set islocal to DestinationFolderIsLocal of todo

set TheDestinationFolder to my getFolderReference(AccountName, DestinationFolder, islocal)

repeat with SourceFolder in SourceFolders

set TheSourceFolder to my getFolderReference(AccountName, SourceFolder, false)

-- get the mails that are interesting

set themails to (every message of TheSourceFolder whose flagged status is true)

--movethemails

repeat with themail in themails

move themail to TheDestinationFolder

end repeat

end repeat

end repeat

end tell

end if


on getFolderReference(AccountName, DestinationFolder, isAlwayslocal)

tell application "Mail"

set TheDestinationFolder to ""

set islocal to (get account type of account AccountName is pop)

if isAlwayslocal = true then set islocal to true

repeat with FolderName in DestinationFolder

if islocal then

if FolderName as string ≠ "INBOX" then

if TheDestinationFolder = "" then

set TheDestinationFolder to mailbox FolderName

else

set TheDestinationFolder to mailbox FolderName of TheDestinationFolder

end if

else

set TheDestinationFolder to mailbox FolderName of account AccountName

end if

else

if TheDestinationFolder = "" then

set TheDestinationFolder to mailbox FolderName of account AccountName

else

set TheDestinationFolder to mailbox FolderName of TheDestinationFolder

end if

end if

end repeat

return TheDestinationFolder

end tell

end getFolderReference

Um das Skript immer mal wieder ablaufen zu lassen, kann man z.B. den crontab nutzen. Dazu am einfachsten via CronniX einen solchen für den aktuellen Nutzer einrichten und das Script mit dem Befehl osascript /Pfad/zur/.scpt-Datei alle x-Minuten laufen lassen. Wie so ein Intervall einzurichten ist, wird sehr gut in der Cronnix-Hilfe erläutert. (was lange währt wird endlich programmiert Thorkillar :-) )

No Comments

RTF als Email-Formatvorlage

23/03/2011
Sagen wir mal ich habe hier eine RTF-Datei die so aussieht:

Hey REPLACEME1,


how you are doing. Do you have time for REPLACEME2?


Yours REPLACEME3

Dann baut sich dieses Skript hier:

set mytemplate to choose file


set replace_list to {"my friend", "what ever", "hubionmac"}

set replace_markers to {}

repeat with i from 1 to count of replace_list

set replace_markers to replace_markers & {"REPLACEME" & i}

end repeat


tell application "TextEdit"

set mytextfile to open mytemplate

set mytext_parts to attribute run of mytextfile

set mylayout to properties of attribute run of mytextfile

close mytextfile

end tell

repeat with i from 1 to count of replace_list

repeat with k from 1 to count of mytext_parts

set item k of mytext_parts to my replace_chars(item k of mytext_parts as text, item i of replace_markers as text, item i of replace_list as text)

end repeat

end repeat


set mytext to mytext_parts as text


tell application "Mail"

activate

set myMessageText to make new outgoing message with properties {content:mytext, visible:true}

tell myMessageText

set globalcounter to 1

set pointer to 1

repeat with i from 1 to count of mytext_parts

set currentcount to count of every character of item i of mytext_parts

set font of characters globalcounter through (globalcounter + currentcount - 1) to (font of item i of mylayout)

set size of characters globalcounter through (globalcounter + currentcount - 1) to (size of item i of mylayout)

set color of characters globalcounter through (globalcounter + currentcount - 1) to (color of item i of mylayout)

set globalcounter to globalcounter + currentcount

end repeat

(**

--this does not work 100% since set word i does not wait for the command to finish

repeat with i from 1 to count of every word

set myword to word i

if myword is in replace_markers then

set word i to (item ((characters 14 through -1 of (myword as text)) as text as integer) of replace_list) as text

end if

end repeat**)

end tell

end tell


on replace_chars(this_text, search_string, replacement_string)

if this_text contains the search_string then

set od to AppleScript's text item delimiters

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 od

end if

return this_text

end replace_chars

.. aus dieser Vorlage eine neue Email, dessen Text entsprechend formatiert ist. Der Gag dabei ist die Geschwindigkeit und die Tatsache, dass das Ding ohne Zwischenablage und GUI-Skripting die Stil-Angaben der Vorlage übernimmt.
No Comments

Apple Mail NERV

6/03/2011
Lilly hatte ein Problem (Apple Mail lädt eine Nachricht immer wieder herunter und zeigt keine neuen mehr an) mit ihrem Mac und oh Wunder... ein AppleSkript (von hier) half bei der Lösung ;-P

display dialog "Delete Mail's offline caches?" buttons {"Cancel", "Delete"} default button 2

copy the result as list to {buttonpressed}


if the buttonpressed is "Delete" then

set thePath to (path to library folder from user domain as text) & "Mail"

tell application "Finder"

set theIMAPFolders to (every folder of folder thePath whose name begins with "IMAP") as alias list

end tell

repeat with thisFolder in theIMAPFolders

set theCachePath to (POSIX path of thisFolder & ".OfflineCache")

do shell script "rm -rf " & theCachePath

end repeat

end if

Scheint ein häufiger Bug zu sein, wenn man versucht Emails mit dicken Anhängen über eine langsame Internetverbindungen zu verschicken.
No Comments

Doppelte Emails filtern

4/02/2011
Dieses Skript ist in erster Linie zur Anschauung geschrieben, um einen Eindruck zu bekommen, wie man schnell nach doppelte Einträge suchen kann. Der eigentliche Trick dabei, ist dass die Duplikate nicht direkt via AppleScript sonder über ein standard-Unix-Tool gefunden werden (uniq)

-- hubionmac.com 04.02.2011

-- you say a folder and a search pattern for sender's address

-- and each duplicated email (sender = subject) will be marked, except the latest one

-- I you feel brave you my uncomment the delete 


tell application "Mail" to set thefolder to inbox

set sender_address to "amazon"

tell application "Finder" to set startup_disk to (startup disk as alias) as text


tell application "Mail"

set mysubjects to subject of every message of thefolder whose sender contains sender_address

set AppleScript's text item delimiters to "

"

set mysubjects to mysubjects as text

set AppleScript's text item delimiters to ""

--save this list to a text tmp text file

my writeToFile(startup_disk & "tmp:mail_subjects.txt", mysubjects, false)

--now use the unix tool unig to find all duplicated subjects

--this way because uniq is much faster on comparing thousands of lines than applescript

set duplicated_subjects to do shell script "sort </tmp/mail_subjects.txt | uniq -d | uniq"

do shell script "rm /tmp/mail_subjects.txt"

repeat with mydublicated_subject in (every paragraph of duplicated_subjects)

set current_messages to (every message of thefolder whose subject is mydublicated_subject and sender contains sender_address)

set first_loop to true

repeat with current_message in current_messages

if first_loop is true then

set last_message to current_message

set last_date to date sent of current_message

set first_loop to false

else

if last_date ≤ (date sent of current_message) then

set background color of last_message to green

--delete last_message

set last_message to current_message

set last_date to date sent of current_message

else

set background color of current_message to green

--delete current_message

end if

end if

end repeat

end repeat

end tell



on writeToFile(MacFilePathTxt, txt, add2eof)

--lastedit 18.01.2011

if add2eof is false then

try

do shell script "rm " & quoted form of POSIX path of (MacFilePathTxt as alias)

end try

end if

set RefNum to (open for access file MacFilePathTxt with write permission)

try

if add2eof is false then

write txt to RefNum

else

write txt to RefNum starting at ((get eof RefNum) + 1)

end if

close access RefNum

return true

on error

close access RefNum

return false

end try

end writeToFile

No Comments

Apple Mail: Regel zum Drucken von neuen Nachrichten

22/01/2011

Hier in kleines Skript zum direkten drucken von eintreffenden Nachrichten. Bisher sehe ich nur einen Weg über GUI-Skripting, sollte jemand eine bessere Lösung haben (ausser Quickmail als Client zu verwenden) -->Please comment!

Read the rest of this article »
2 Comments

Apple Mail: Access outgoing message via AppleScript

4/01/2011

Jeder der schon einmal Apple Mail via AppleScript geskriptet hat (ein wohl ehr überschaubarer Personenkreis), hatte vielleicht schon einmal ein Problem mit outgoing messages (noch überschaubarer). Eine neue Nachricht ist irgendwie anders als eine bereits gespeicherte. Man kann zwar Adressen, Betreff und Signatur hinzufügen, aber schon bei der Auswahl des Absende-Accounts stößt man bei Apple Mail auf eine Logik-Blase die sofort zerplatzt. Es geht einfach nicht und kommt man dann noch auf die abwegige Idee den Email-Text einer gerade geschrieben Nachricht auslesen zu wollen, merkt man erst einmal wie schlecht Apple Mail und wie gut Microsoft Entourage zu skripten ist. Lage rede kurzer Sinn, alles was auf der Platte gespeichert ist (in Form einer EMLX-Datei), ist wunderbar auszuwerten, da aber Nachrichten, die gerade erst geschrieben werden noch nicht gespeichert sind, ist der Zugriff auf Informationen wie Inhalt, Absender, Attachments-Namen, etc. bei solchen noch nicht möglich. Deshalb hier ein Beispiel für einen Work-Around, der die gerade geschrieben Nachricht als Entwurf abspeichert, diese Datei dann auswertet und einem die Namen der Attachments in den Mailtext einfügt. So etwas dürfte bei normalen POP-Accounts recht gut funktionieren, bei IMAP eher weniger, da der Entwurf erst auf den Server hochgeladen, anschließend wieder heruntergeladen wird und dann erst zur Verfügung steht.

Code zum markieren einmal anklicken Code im Skript-Editor öffnen

-- Nachricht als Entwurf speichern

tell application "Mail" to activate

tell application "System Events"

tell process "Mail"

keystroke "s" using command down

set messagename to name of window 1

end tell

end tell

delay 2

--Entwurfs-Maibox nach der neuesten Nachricht durchsuchen, die den passenden Betreff trägt

--Anschließend die Namen der Anhänge auslesen

tell application "Mail"

set found to (every message of drafts mailbox whose (subject is messagename))

set theid to 0

repeat with f in found

if id of f > theid then

set theid to id of f

end if

end repeat

set mymessage to item 1 of (every message of drafts mailbox whose (id is theid))

set attachmentnames to name of every mail attachment of mymessage

set AppleScript's text item delimiters to return

set attachmentnames to attachmentnames as text

set AppleScript's text item delimiters to ""

set the clipboard to attachmentnames

end tell


--Namen in die Zwischenablage und an der aktuellen Cursor-Position einfügen

tell application "Mail" to activate

tell application "System Events"

tell process "Mail"

keystroke "v" using command down

end tell

end tell

1 Comment

Apple Mail: EMLX-Datei der ausgewählte Nachricht speichern

29/12/2010
Apple Mail nutzt glaube ich seit Leopard nicht mehr eine fette mbox Datei sondern einzelne .emlx Dateien zum speichern der abgerufenen Emails. So können die Dateien schön einzeln indiziert (Spotlight) werden und können auch recht leicht kopiert werden (TimeMachine). Eine solche EMLX-Datei lässt sich über Quicklook oder Apple Mail betrachten und beinhaltet sogar die in der Email enthaltenen Anhänge.
Dummerweise kann man via AppleScript nicht direkt den Speicherort der Email abfragen, aber da die emlx-Datei nach der ID der Email benannt ist, kann man sie recht leicht im entsprechenden Account-Ordner finden. Das tut dieses Skript also, es sucht sich die emlx-Dateien der ausgewählten Emails kopiert diese auf den Schreibtisch...
Code zum markieren einmal anklicken Code im Skript-Editor öffnen

--hubionmac.com 29.12.2010 EMLX-Dateien ausgewählter Emails in einen Order (Saved_Mails(Acountname) auf dem Schreibtisch kopieren... (4 Chris_Zuerich)


--auswahl aus Apple Mail abfragen

set mymails to my getSelection()

repeat with mymail in mymails

tell application "Mail"

--das Verzeichnis des Email Accounts ausfindig machen

set accountDir to quoted form of POSIX path of ((account directory of account of mailbox of mymail) as alias)

set account_name to (name of account of mailbox of mymail) as text

tell application "Finder" to set temp_dir to quoted form of (POSIX path of (desktop as alias) & "Saved_Mails (" & account_name & ")/")

try

do shell script "mkdir " & temp_dir

end try

--in dem Account-Verzeichnis nach der der Email-Datei suchen und diese kopieren...

set myid to id of mymail

do shell script "find " & accountDir & " -name " & myid & "*.emlx* -exec cp {} " & temp_dir & " \\;"

end tell

end repeat


on getSelection()

tell application "Mail"

set a to selection

if (count of a) < 1 then

error "Eine Mitteilung muss ausgewählt sein."

end if

return a

end tell

end getSelection

Ein Grund für den regen Gebrauch von Wildcards im find-Befehl ist die Tatsache, dass besonder große Emails aufgesplittet werden in .emlx und .emlxpart Dateien. Gemeinsamer Nenner ist aber immer die ID, mit der der Dateiname stets beginnt.
No Comments

Mail-Regel: Links laden und als PDF abspeichern

5/10/2010
Julien hat mich heute gebeten eine Möglichkeit zu finden, die Links einer Email aufzurufen und die entsprechenden Websites als PDF zu drucken. Bei der Suche nach einer Lösung bin ich auf wkpdf gestoßen. Das ist ein Ruby-Script mit dem man eine URL über das Webkit-Framework lädt und den Output als PDF abspeichern kann. Da die Installation von wkpdf so simple ist und danach einfach via do shell script abrufbar ist, eine perfekte Lösung. Als Anhang (weil durch einen sed-Befehl einige besonders besondere Sonderzeichen im Quellcode stehen). DOWNLOAD
mail_links_to_pdf v.0.1
7.36 kB (133 hits)

Anwendung

Das Skript über eine Mail-Regel anfeuern und jede Email, die auf die Mail-Regel anspringt, wird nach URLs gescannt, die URLs werden über wkpdf aufgerufen und als PDF gespeichert.

Nice2Know

Das Skript nutzt als Email-Text zur Zeit set mytext to content of thisMessage, man könnte aber auch (um auch html-Emails verarbeiten zu können set mytext to source of thisMessage auskommentieren.

Links

3 Comments

Mail: angehängte PDFs direkt drucken als Regel…

3/09/2010
Ist eine leicht erweiterte Version dieses Skriptes....

Update 15.02.2011

Wie von Markus gemeldet, werden so keine ausgefüllten Formulare gedruckt... um GUI-Skript zu umgehen wird nun pdftk genutzt um eine druckbare Version zu erstellen, ausserdem wird nun das Druckprogramm ausgeblendet (ist zwar nicht die optimale Lösung, druckt aber zuverlässiger als über lpr via shell scripting)

-- hubionmac.com 2010-09-03

-- script to be added to a Apple Mail rule

--saves PDF attachmens of new mails into a tmp folder and prints them with standard printer

## Update 15.02.2011

## - script now also prints filled pdf forms (requires pdftk to flatten forms)

## - printing app window is hidden after launch (pomps up a milsec... )

on perform_mail_action(info)

tell application "Mail"

tell application "Finder" to set mypath to (name of startup disk & ":tmp:") as text

set theMessages to |SelectedMessages| of info

repeat with thisMessage in theMessages

try

repeat with a in (every mail attachment of thisMessage)

set current_a_name to name of a

if current_a_name ends with ".pdf" then

set current_a_name to my checkname_with_pdf_suffix(current_a_name, mypath as alias, false)

save a in mypath & current_a_name

##print pdf form workaround, this requires pdftk installed!!!

set current_a_name2 to my checkname_with_pdf_suffix(current_a_name, mypath as alias, false)

do shell script "/opt/pdflabs/pdftk/bin/pdftk " & quoted form of POSIX path of ((mypath & current_a_name) as alias) & " output " & POSIX path of ((mypath) as alias) & quoted form of current_a_name2 & " flatten;rm " & quoted form of POSIX path of ((mypath & current_a_name) as alias)

set current_a_name to current_a_name2

##workaround --END--

my print_file_with_standard_printer(POSIX path of ((mypath & current_a_name) as alias))

else

--display dialog current_a_name

end if

end repeat

on error msg

do shell script "echo " & quoted form of msg & " | cat>>~/Desktop/MailscriptErrorLog.txt"

end try

end repeat

end tell

end perform_mail_action

on checkname_with_pdf_suffix(n, D, looped)

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 n to ((characters 1 through -5 of n) & " 1" & (characters -4 through -1 of n)) as text

my checkname_with_pdf_suffix(n, D, true)

else

set tmp to (last word of ((characters 1 through -5 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 & (characters -4 through -1 of n)) as text

my checkname_with_pdf_suffix(n, D, true)

end if

else

return n

end if

end checkname_with_pdf_suffix

on getStandardPrinter()

tell application "Printer Setup Utility"

return name of current printer & ".app"

end tell

end getStandardPrinter

on print_file_with_standard_printer(thefile)

-- thefile is a unquoted POSIX path

--assumes that the printer app is stored in ~/Library/Printers/ not /Library/Printers/

tell application (my getStandardPrinter()) to activate

tell application "Mail"

do shell script "open -a ~/Library/Printers/" & quoted form of (my getStandardPrinter()) & " " & quoted form of thefile

##hide the printer app

tell application "Finder" to set visible of process (characters 1 through -5 of (my getStandardPrinter()) as text) to false

end tell

end print_file_with_standard_printer

3 Comments

AppleScript: Email als PDF speichern, mit Attachments

23/03/2010
Mich hat heute eine Email erreicht, in der mir folgende Aufgabe beschrieben wurde (Ich hoffe mal Udo ist mit der Veröffentlichung einverstanden, hätte ich selber nicht besser formulieren können.):
Ich möchte eine Mail in Mail.app anklicken, danach sollte die Mail als pdf (wie unter Ablage Drucken PDF Als PDF sichern) in einem speziellen Ordner auf dem Schreibtisch mit folgendem Namen (Sendedatum, E-Mail-Adresse und Betreff aus Mail) gesichert werden. Der eventuelle Anhang sollte ebenfalls in diesem Ordner gesichert werden. Die Mail kann danach gelöscht werden.
zusammen mit dieser Aufgabenstellung und den ersten Code-Zeilen von Udo ist dann das hier entstanden (ich mag zwar GUI-Scripting nicht, aber das hier ROCKT ;-) ):
Code zum markieren einmal anklicken Code im Skript-Editor öffnen

-- Save Mail as PDF and it's attachments to folder

--  Created by hubionmac (22.03.2010) requested by Udo

global frontmost_message_viewer

--this is the posix (unix) path of the folder you would like to store the messages in

tell application "Finder" to set mymailboxpath to POSIX path of ((desktop) as alias) & "mail_box/"

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)

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 text

my create_messagefolder(currentFolder2Store)

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, (POSIX file currentFolder2Store) as alias, false)

save a in (((POSIX file currentFolder2Store) as text) & current_a_name) as text

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)

--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

return yearnum & "-" & monthnum & "-" & daynum as text

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 n to ((characters 1 through -5 of n) & " 1" & (characters -4 through -1 of n)) as text

my checkname_with_pdf_suffix(n, D, true)

else

set tmp to (last word of ((characters 1 through -5 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 & (characters -4 through -1 of n)) 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 window 1

keystroke "a" using command down

keystroke "v" using command down

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

In habe mal auf das Löschen der Email verzichtet (das soll mal jeder lieber alleine rein schreiben), aber es scheint wunderbar zu funktionieren. Bin mal gespannt ob es auch bei anderen läuft...Update vom 27.09.2011:

-- Save Mail as PDF and it's attachments to folder

--  Created by hubionmac (29.09.2010)

-- 29.09.2010 

-- -Auswahl von mehren Emails wird nun auch möglich

-- -Abgesendete Emails werden als solche erkannt und in einem anderen Verzeichnis mit Empfänger-Adresse im Ordnernamen gespeichert (req. by Andreas)

-- 27.09.2011 made it work with local mailboxes, too

global frontmost_message_viewer

--this is the posix (unix) path of the folder you would like to store the messages in

tell application "Finder" to set mymailboxpath to POSIX path of ((desktop) as alias) & "received_mail_box/"

tell application "Finder" to set mysentmailboxpath to POSIX path of ((desktop) as alias) & "sent_mail_box/"

tell application "Mail"

set myselection to my check_message_viewer_and_return_selection()

repeat with currentMail in myselection

open currentMail

set currentSender to my (getEmail(sender of currentMail))

set currentDateSent to my getDatestring(date sent of currentMail)

set currentSubject to my replace_chars(my replace_chars(subject of currentMail, ":", "-"), "/", ":") --Doppelpunkte kommen bei Dateinamen nicht so gut

if my is_in_sent_mail(currentMail) is true then

--if the file was sent FROM this email account

set sentToEmail to address of item 1 of to recipient of currentMail

set currentFolder2Store to mysentmailboxpath & sentToEmail & " " & currentDateSent & " " & currentSubject & "/" as rich text

else

--if the email was sent TO this email account 

try

set myemail to item 1 of (get email addresses of account of mailbox of currentMail)

on error

--27.09.2011 added to make it work with local mailboxes, too

set myemail to item 1 of (get address of to recipient of currentMail)

end try

set currentFolder2Store to mymailboxpath & currentDateSent & " " & currentSender & " " & currentSubject & " send to" & myemail & "/" as rich text

end if

my create_messagefolder(currentFolder2Store)

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, (POSIX file currentFolder2Store) as alias, false)

save a in (((POSIX file currentFolder2Store) as rich text) & current_a_name) as rich text

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

tell application "System Events"

tell process "Mail"

set wc to count of every window

end tell

end tell

my print_current_mail_as_pdf()

tell application "System Events"

tell process "Mail"

repeat until (count of every window) is wc

end repeat

end tell

end tell

my move_desktop_pdf(desktop_pdf_name, currentFolder2Store)

--close last_message window

activate

tell application "System Events"

tell process "Mail"

keystroke "w" using command down

end tell

end tell

--open destination folder in finder ( did it really work? YES!! =))

--do shell script "open " & quoted form of currentFolder2Store

end repeat

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)

--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

return yearnum & "-" & monthnum & "-" & daynum as text

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 n to ((characters 1 through -5 of n) & " 1" & (characters -4 through -1 of n)) as text

my checkname_with_pdf_suffix(n, D, true)

else

set tmp to (last word of ((characters 1 through -5 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 & (characters -4 through -1 of n)) 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 until 0 = 1

if (count of every sheet of window 1) > 0 then

set p to "ready"

exit repeat

end if

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

set cwc to count of every window

keystroke return

repeat until 1 = 0

if (cwc + 1) = (count of every window) then

exit repeat

end if

end repeat

click text field 1 of window 1

keystroke "a" using command down

keystroke "v" using command down

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

on is_in_sent_mail(amessage)

tell application "Mail"

set sentmailboxes to every mailbox of sent mailbox

set currentmailbox to mailbox of amessage

repeat with i from 1 to (count of sentmailboxes)

if item i of sentmailboxes = currentmailbox then

return true

end if

end repeat

return false

end tell

end is_in_sent_mail

33 Comments