Problems with special chars when extracting Mail
I am using this script for saving a mail out from the Apple Mail app:
tell application "Mail"
# take the selected Mail
set selectedMessages to selected messages of message viewer 0
set mailToSave to first item of selectedMessages
set resultFile to (choose file name with prompt "Speichere E-Mail unter ..." default name "Mail.eml") as rich text
if resultFile does not end with ".eml" then set resultFile to resultFile & ".eml"
my writeTextToFile(source of mailToSave, resultFile, true)
end tell
on writeTextToFile(theText, theFile, overwriteExistingContent)
try
-- Convert the file to a string
set theFile to theFile as string
-- Open the file for writing
set theOpenedFile to open for access file theFile with write permission
-- Clear the file if content should be overwritten
if overwriteExistingContent is true then set eof of theOpenedFile to 0
-- Write the new content to the file
write theText to theOpenedFile starting at eof
-- Close the file
close access theOpenedFile
-- Return a boolean indicating that writing was successful
return true
-- Handle a write error
on error
-- Close the file
try
close access file theFile
on error errMsg
log errMsg
end try
-- Return a boolean indicating that writing failed
return false
end try
end writeTextToFile
In most of the cases it's working perfectly, but it some cases the special chars are broken in the exported file. For example:
One mail is displayed correctly in Mail. If I open the source of this mail I'll get this:
MIME-Version: 1.0
Content-Disposition: inline
Content-Transfer-Encoding: 8bit
Content-Type: text/plain; charset="UTF-8"
X-Mailer: .......
...
für Sie ...
In Mail the text is correctly shown as a für Sie ...
.
The exported file contains:
MIME-Version: 1.0
Content-Disposition: inline
Content-Transfer-Encoding: 8bit
Content-Type: text/plain; charset="UTF-8"
X-Mailer: ...
...
fÌ1Ú4r Sie ...
If I drag and drop this mail out of Apple Mail, it's getting saved correctly. Any way how I can achieve this with AppleScript?
I figured out an own way as I am now using JavaScript:
var source = mailToSave.source();
var newSource = decodeURIComponent(escape(source));
To get the final result, I need to save it as an UTF-8-String, what is only working with NSString
:
writeTextToFile(newFilePath.toString(), newSource);
function writeTextToFile(pathString, textToWrite) {
// convert to NSString
var nsString = $.NSString.alloc.initWithUTF8String(textToWrite)
// convert to NSPath
var nsPath = $(pathString).stringByStandardizingPath
// write File
var success = nsString.writeToFileAtomicallyEncodingError(nsPath, false, $.NSUTF8StringEncoding, null)
if (!success) {
throw new Error("Write failed. ERROR: Writing to file failed.\nPath: " + pathString)
}
return success
}