This is my script based on pickings of one here on SO:
set theFile to (path to desktop folder as text) & "unsubscribe.csv"
set theRecord to ""
set counter to 1
set theAddresses to "Address, Name, Counter" & return
try
set theFileID to open for access file theFile with write permission
tell application "Mail"
set emailSelection to selection
repeat with eachMessage in emailSelection
-- log sender of the_message
set theSender to extract address from sender of eachMessage
set theName to extract name from sender of eachMessage
if theAddresses contains theSender then
log "*** Double: " & theSender & " ***"
theSender & "***********" & return
else
copy theSender to the end of theAddresses
set theAddresses to theAddresses & theSender & "," & theName & "," & counter & "," & return
log theAddresses
end if
end repeat
end tell
try
write theAddresses to theFileID as «class utf8»
on error theError
log theError
end try
on error theError
log theError
try
close access file theFile
end try
end try
On run I get this error:
"(*Can’t set end of "Address, Name, Counter " to "[email protected]".*)"
When I created a proof of scope script so show myself that the tell application "Mail" block scope isn't an issue, it works:
try
set theFile to (path to desktop folder as text) & "test3.csv"
set theFileID to open for access file theFile with write permission
set theAddresses to "Address, Name, Counter" & return
tell application "Mail"
set emailSelection to selection
set theMsg to the first item in emailSelection
set theSender to extract address from sender of theMsg
end tell
set theAddresses to theAddresses & theSender & return
try
write theAddresses to theFileID as «class utf8»
on error theError
log theError
end try
close access file theFile
on error theError
close access file theFile
end try
From the Applescript docs on Scope (remnant of previous iteration of the question):
set x to 3
In the absence of a global variable declaration, the scope of a variable declared with the copy or set command is normally restricted to the run handler for the script, making it implicitly local to that run handler. However, a handler or nested script object can declare the same variable with a global declaration to gain access to it.
I have made a few assumptions: