Trying to write to a file - a compiler oddity

I am trying to write data to a file thus:


using terms from application "Mail"
	on perform mail action with messages theSelectedMessages
                tell application "Mail"
                   .
                   .
                   .
                end tell
                set my_file to (path to documents folder as text) & "emailblocks.csv"
		set open_file to open for access my_file with write permission
		repeat with i from 1 to number of items in data_part by 2
			set lineout to date_part & "," & item i of data_part & "," & item (i + 1) of data_part & "
"
			write lineout to open_file starting at eof
		end repeat
		close access open_file
        end perform mail action with messages
end using terms from

Note the syntax for setting ‘my_file’. This is before compiling. After compiling that line is changed to:

set my_file to (path to documents folder rule type text) & "emailblocks.csv"

The next time I try to compile the script that line gets a syntax error, "Expected “, " but found property.” The words “rule type” are highlighted. I don’t know if this is causing my problem but when I run the script it appears to fail on the ‘write’. What is the compiler doing and is this why the write fails? TIA.

While using terms from “Mail”, Mail seems to think something in “path to documents folder as text” means something else.

Does this work?

using terms from application "Mail"
	set my_file to ((path to documents folder) as text) & "emailblocks.csv"
end using terms from

Or just try moving all this part out of the “using terms from” block.

Thanks. Your first suggestion worked so I didn’t try the second. That seems to have cured both my problems.