You won't be able to see what the error is if you enclose things in a plain try statement. Mail (at least the current versions) wants to use rich text, so instead of the standard write you can use open for access to specify the desired output type, for example:
globaloutputFolder-- this will be the destination folder for the text files
setoutputFolderto (choose folder) astext
tellapplication"Mail"-- write raw source of selected items to text files
repeatwithaMessagein (getselection)
setmessageSubjecttosubjectofaMessage
setmessageSourcetosourceofaMessage
setmessageIDto"" & idofaMessage-- coerce number to text
settheOutputtomessageID & return & messageSource
mywriteText_withFileName_(theOutput, messageSubject)
endrepeat
endtell
towriteText_withFileName_(theText, theName)
settheNametoreplaceText_inString_withText_(":", theName, space) -- replace illegal character
tell (current date) as «class isot» as string to set theDate to text 1 thru 10 -- yyyy-MM-dd
settheOutputFileto (outputFolder & theDate & " - " & theName) astext
try-- write to text file
settheFiletoopen for accesstheOutputFilewithwrite permission
writetheTexttotheFileas «classutf8»
close accesstheFile
onerrorerrmess-- just log it and try to make sure the file is closed
logerrmess
try
close accesstheFile
endtry
endtry
endwriteText_withFileName_
toreplaceText_inString_withText_(oldItem, someText, newItem)
set {tempTID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, oldItem}
try
set {itemList, AppleScript's text item delimiters} to {text itemsofsomeText, newItem}
set {someText, AppleScript's text item delimiters} to {itemListastext, tempTID}
onerrorerrorMessagenumbererrorNumber-- oops
setAppleScript's text item delimiterstotempTID
errorerrorMessagenumbererrorNumber-- pass it on
endtry
returnsomeText
endreplaceText_inString_withText_