Erase junk mail folder in Apple Mail

I tried to use what I thought I could learn from the examples on Apple’s GUI scripting site to script the needed commands to click on the menu bar in Apple Mail in order to erase the junk mail.

I have this, but it doesn’t work. I would also like to add in a command to hit the “Return” key to complete the action by selecting “OK” (“keystroke return”? key code 36?)

thanks for any help.

on do_menu(Mail, Mailbox, “Erase Junk Mail”)
try
– bring the target application to the front
tell application Mail
activate
end tell
tell application “System Events”
tell process Mail
tell menu bar 1
tell menu bar item Mailbox
tell menu “Mailbox”
click menu item “Erase Junk Mail”
end tell

				end tell
			end tell
		end tell
	end tell
	
	return true
on error error_message
	return false
end try

end do_menu

Model: iMac
AppleScript: 2.2.1
Browser: Safari 531.9
Operating System: Mac OS X (10.6)

Hi,

it’s


tell process "Mail"

Sorry, but I’m not understanding what you mean. I added the quotation marks in that line of the script, but I still don’t get the results I’m after.

Also, any guidance on how to click “OK” on the “Are you sure…” dialog box?

it probably depends on the paramteers you pass.
As I use an external spam filter, the script with menu item “New Mailbox.” works on my machine, even with the string variables.
I added an display dialog line to catch the error message if there is one


do_menu("Mail", "Mailbox", "New Mailbox.")

on do_menu(Mail, Mailbox, MenuItem)
	try
		-- bring the target application to the front
		tell application Mail
			activate
		end tell
		tell application "System Events"
			tell process Mail
				tell menu bar 1
					tell menu bar item Mailbox
						tell menu "Mailbox"
							click menu item MenuItem
						end tell
						
					end tell
				end tell
			end tell
		end tell
		return true
	on error error_message
		display dialog error_message
		return false
	end try
end do_menu

OK, thanks to your help, I now have this script, which works just fine:

do_menu(“Mail”, “Mailbox”, “Erase Junk Mail”)

on do_menu(Mail, Mailbox, “Erase Junk Mail”)
try
– bring the target application to the front
tell application Mail
activate
end tell
tell application “System Events”
tell process Mail
tell menu bar 1
tell menu bar item Mailbox
tell menu “Mailbox”
click menu item “Erase Junk Mail”
end tell
end tell
end tell
end tell
return true

	end tell
end try

end do_menu
tell application “System Events”
keystroke return
end tell

the third parameter is actually useless, because you pass always a literal string, not a variable