Count Mail messages moved by script?

I cobbled together a script to move messages in Mail from a specific mailbox to the Inbox (run at a certain time of the day via Keyboard Maestro).

That part works fine, but I wanted show a notification with a count of how many messages were moved back to the Inbox. The count works fine on the first run, but after running it more times it shows the wrong number of messages. Here’s the script


tell application "Mail"
	set messageCount to 0
	tell account "FastMail"
		set snoozedMessages to messages of mailbox "Snooze/Tomorrow"
		repeat with theMessage in snoozedMessages
			set messageCount to messageCount + 1
			set read status of theMessage to false
			delay 0.25
			move theMessage to mailbox "INBOX"
		end repeat
	end tell
end tell

set theTitle to "Moved to Inbox"
set theSubtitle to messageCount & " snoozed messages" as text
set theMessage to ""
set theSound to "Tink"
display notification theMessage with title theTitle subtitle theSubtitle sound name theSound

Any idea what the problem is, and how to make it work properly?
It would also be useful if it only showed the notification if it actually moved some messages (i.e. doesn’t show a notification if the script runs and the mailbox is empty)

Hi. You can get the count non-incrementally.

tell application "Mail"
	tell account "FastMail"
		tell mailbox "Snooze/Tomorrow" to set {messageCount, messages's read status} to {count messages, false}
		move mailbox "Snooze/Tomorrow"'s messages to mailbox "INBOX"
	end tell
end tell

if not messageCount = 0 then display notification "" with title "Moved to Inbox" subtitle messageCount & " snoozed messages" as text sound name "Tink"

Thanks, this looks much cleaner than my version :slight_smile:

…but it still keeps adding up the numbers each time it’s run (so if it moves 3 messages the first time and it’s moving 4 messages the second time the notification says ‘7 snoozed messages’)

I tried adding ‘set messageCount to 0’ but that didn’t work.

Any ideas?

I don’t know where the property persistence could be coming from, as the count is being obtained at run time. Are you sure this is the code being called or is Keyboard Maestro doing something other than launching it? Are the messages actually moving between boxes?

I haven’t actually tried it with Keyboard Maestro yet, I’ve only tried running/testing it from Script Editor (move some emails to the ‘Tomorrow’ mailbox, run the script, move some more emails to the ‘Tomorrow’ mailbox, run the script again…).

And every time I run it in Script Editor it adds the count from the previous time.