TextEdit won't open a plain text file after writing to it with write cmd


Ilya Shebalin
 

Hello,
I wrote a script that would act as an Automator service plug-in in Mail.app when placed to "Run AppleScript" action. It basically would extract the contents of a selected message along with its subject and create a plain text file with the subject as its name and the msg contents becoming the file's contents. IIf the file exists and all the statements beyond "else" clause are executed then TextEdit gives a warning of a wrong encoding ("The document "theFile.txt" could not be opened. Text encoding Unicode (UTF-8) isn’t applicable.") and refuses to open the file. The script is as follows:


property theText: ""
property theSubject:""
property theFile: missing value

tell application "Mail"
set theMessages to (get selection)
set theSubject to ""

repeat with aMessage in theMessages
set {theSubject, theText} to {subject of aMessage, content of aMessage}
end repeat
end tell

tell application "Finder"
set theName to theSubject & ".txt"
set FullFilePath to (((path to desktop) as text) & theName)
if not (file  FullFilePath exists) then
set theDoc to make new document file with properties {name:theName, displayed name: theSubject } at folder "Desktop" of home
tell application "TextEdit"
activate
set myDoc to make new document with properties {text:theText, name:theName} at end of documents
close myDoc saving in file  FullFilePath 
quit
end tell
else
display dialog "The file already exists." & return & return & "Do you want to update it?" buttons {"Cancel", "Update"} default button  1 cancel button 2
if button returned of result is "Cancel" then
error number -128
else
set theFile to  (FullFilePath as alias)
try
my writeToFile(theText, theFile)
on error number -49
close access theFile
my  writeToFile(theText, theFile)
end try
end if
end if
end tell

on   writeToFile(theText, theFile)
set FileID to open for access theFile with write permission
set eof FileID to 0
write theText to  FileID
close access FileID
end 

.Is this an issue when you cannot open a file in an app that wasn't the one you created said file in?
OS X Lion 10.7.5

Join applescript@apple-dev.groups.io to automatically receive all group messages.