emailapplescriptapple-mail

How to use applescript to save an email as a txt file


I am completely newbie in Applescript...

In Apple Mail, you can save an email as a text file : File > Save As... > Format "Plain Text"

  1. Is it possible to automate that using an applescript ?
  2. Would it be possible to use applescript to save the mail (in txt "format") in the clipboard rather that as a txt file ?

Many thanks.


Solution

  • The Mail.app doesn't export selected message to TXT programatically. You can use GUI scripting, but GUI scripting is bad solution in this case. Exists other way, described here.

    The script assumes the message is selected in the Mail.app and creates text file on the desktop, but you can indicate other folder. .

    -- Mail.app: Export Selected Message to plain text (.txt)  file 
    -- written: by me, right now
    
    use AppleScript version "2.5"
    use scripting additions
    use framework "Foundation"
    
    set timeZone to (abbreviation of (current application's NSTimeZone's localTimeZone())) as text
    
    -- Mail.app part (load remote content, get message properties)
    tell application "Mail"
        set download html attachments to true -- load remote content as well
        tell (item 1 of (get selection)) -- here we tell to 1st selected message
            set {theSubject, fromHider} to {subject, "From: " & sender}
            tell (get date sent) -- build here "Date: ....." text line
                set dateSentHider to "Date: " & date string & " - " & time string & " " & timeZone
            end tell
            set {toHider, messageContent} to {"To: " & address of to recipient 1, content}
        end tell
    end tell
    
    set allText to fromHider & linefeed & "Subject: " & theSubject & linefeed & dateSentHider & ¬
        linefeed & toHider & linefeed & linefeed & messageContent
    
    -- replace every ":" symbol in theSubject with "_"
    set {ATID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, ":"}
    set {itemList, AppleScript's text item delimiters} to {text items of theSubject, "_"}
    set {theSubject, AppleScript's text item delimiters} to {itemList as text, ATID}
    
    -- build destination file's Posix path, write to it
    set theFile to POSIX path of (path to desktop folder) & theSubject & ".txt"
    -- or,
    -- set theFile to POSIX path of (choose folder) & theSubject & ".txt"
    (current application's NSString's stringWithString:allText)'s writeToFile:theFile atomically:true ¬
        encoding:(current application's NSUTF8StringEncoding) |error|:(missing value)
    

    You can save message (in txt "format") in the clipboard as well. Simply:

    set the clipboard to allText