How to write several selected emails to a file

What I would like to do:

  • select a number of emails;
  • for each extract some data from each email;
  • then with the data for each email format in a certain way; and
  • write to a file (all of the data from the emails to be written to the same file).

What I have done

I have been able to do the above for a single email but I do not know how to make AppleScript work through all of the selected emails,

The script I have put together is as follows:

tell application "Mail"
	set theSelection to item 1 of (get selection)
	tell theSelection
		set theMessage to its content
		set theSName to (extract name from sender)
		set theSAddress to (extract address from sender)
		set theDate to date sent
		set theDateReceived to date received
		set theRName to the (name of first to recipient)
		set theRAddress to the (address of the first to recipient)
	end tell
end tell
set SFirstName to first word of theSName
set SLastName to word -1 of theSName

set vDate to (day of theDate) & " " & (month of theDate) & " " & (year of theDate)

set vTime to the time string of theDate

set filepath to (path to desktop as text) & ""

set vmail to "## *From*: " & SFirstName & " " & SLastName & " (" & theSAddress & ") - *To*: " & theRName & " (" & theRAddress & ")  

*Date*: " & vDate & " at: " & vTime & "

" & theMessage & " 


	set openfile to open for access file filepath with write permission
	write vmail to openfile
	close access openfile
on error
		close access file filepath
	end try
end try

Any help would be gratefully received.