Scripting Mail

I am working on an AppleScript that will delete messages in my various mailboxes that are over 160 days old. I thought I could just make a rule, but I can’t figure out how to make it work on all mailboxes and to execute on a regular basis. Anyway, everything in my script works great except for when I want to either move or delete the message. When I try, I get the wonderful NSInternalScriptError message. The line it occurs on is theMessage delete. That section of code is below:


repeat with theMessage in every message in the mailbox mailboxName
   set difference to ((current date) - (date sent of theMessage)) div days
        if difference is greater than StaleTime then
	    delete theMessage
	end if
end repeat

What am I doing wrong?

try this…

set mailboxName to "friends"
set StaleTime to 160

tell application "Mail"
	set messages_list to every message of mailbox mailboxName
	repeat with i from 1 to number of items in messages_list
		set theMessage to item i of messages_list
		set difference to ((current date) - (date sent of theMessage)) div days
		if difference is greater than StaleTime then
			delete theMessage
		end if
	end repeat
end tell

That worked great! Thanks!