Why does this script sometimes cause Mail to freeze?

I’m unsure about whether scripting support in Mail is really just fundamentally broken or if there’s something wrong with my script (see below). Sometimes, for no apparent reason, running it will result in the beachball and I’ll end up having to force-quit Mail.

I’m using this from an Automator service, containing nothing but a Run AppleScript command (with the following code), which I have assigned a key shortcut to so I can invoke it easily. The intent is to create and send an automated reply to any messages that are selected in Mail, then flag those messages and mark them as read.

When it works, it works well.

on run {input, parameters}
	
	set replyMessageText to "Some message text"
	
	
	tell application "Mail"
		set selectedMessages to the selection
		repeat with oneMessage in selectedMessages
			set replyAddress to extract address from oneMessage's reply to
			set aNewMessage to make new outgoing message with properties {subject:"Thanks!", sender:"me@someaddress.com", content:replyMessageText}
			tell aNewMessage
				make new to recipient at beginning of to recipients with properties {address:replyAddress}
			end tell
			send aNewMessage
		end repeat
		
		repeat with oneMessage in selectedMessages
			set the read status of oneMessage to true
			set the flagged status of oneMessage to true
		end repeat
	end tell
	
	return input
end run

Hi. Is Mail minimized when you have the issue? If the viewer window is not in the foreground, selection has no result.

Nope, the Mail window is always frontmost, as I have just selected messages before triggering the script. I also make it a policy to keep Mail in the front, and touch nothing, until the script finishes. (Or until I realize it’s not going to finish and force-quit.)

Hi,

What if you put a ‘delay 2’ after ‘send aNewMessage’?

gl,
kel