Select every message in a Mailbox, then cut it with CMD-X

I’m working on a fairly simple script to select a mailbox, in this case, the spam mailbox, then select all the messages in that mailbox and cut them with CMD-X. My code looks like this:


tell application "Mail"
	set theMessages to every message in the mailbox "Spam"
	repeat with theMessage in theMessages
		tell application "System Events"
			tell application process "Mail"
				keystroke "x" using command down
			end tell
		end tell
	end repeat
end tell

I’m not sure why it doesn’t work but looking for some help.

Thanks.

Donny Hornstein
Dallas, TX

Model: MacBook
AppleScript: 2.3
Browser: Chrome
Operating System: Mac OS X (10.6)

Answering my own question, the script is fairly simple:

tell application "Mail"
	activate
	get mailbox "Spam"
	tell application "System Events" to tell process "Mail" to keystroke "a" using command down
	tell application "System Events" to tell process "Mail" to keystroke "x" using command down
end tell

OK. The above post is not right. If Mail has a different Mailbox highlighted, it select all the mail in that mailbox with CMD-A, then tries to cut it with CMD-X. So, how can I keep the focus on the Spam mailbox?

Hi,

do you mean this? It deletes every message in mailbox “Spam” then it empties the trash


tell application "Mail"
	delete every message of mailbox "Spam"
	delete every message of trash mailbox
end tell

Or do you need the messages on the clipboard?

1 Like

Thanks, but no. I don’t want the messages moved to the trash. I’m not going to empty the trash.

If I select all the messages in “Spam” then cut them, they are on the clipboard until something else gets copied to the clipboard. Then, they just vanish on their own.

That’s the end result desired. Any ideas?

you can select every message in the mailbox Spam with


tell application "Mail"
	set selected mailboxes of message viewer 1 to {mailbox "Spam"}
	set selected messages of message viewer 1 to every message of mailbox "Spam"
end tell

Thanks, Stefan. That was the missing piece.
Here’s the final script:

tell application "Mail"
	activate
	set selected mailboxes of message viewer 1 to {mailbox "Spam"}
	set selected messages of message viewer 1 to every message of mailbox "Spam"
	tell application "System Events" to tell process "Mail" to keystroke "a" using command down
	tell application "System Events" to tell process "Mail" to keystroke "x" using command down
end tell

⌘A is actually not needed, the script selects the messages

I’m such an amateur with Applescript, but I really love it. I really need to read more or take a class. Thanks so much for your help.