JXA - performMailActionWithMessages can't convert types

Does this work for anyone else? I’m trying to run a script on incoming messages with AppleScript (JXA). I have a more elaborate script that does things with the messages but this simple example displays an error.

var mail = Application('Mail');

mail.performMailActionWithMessages(function(messages) {

Error -1700: Can’t convert types.


using terms from application "Mail"
	on perform mail action with messages JunkMessages for rule this_rule
	end perform mail action with messages
end using terms from

Running this in script editor doesn’t show any errors at all. Is this just a bug on Apple’s end or does it have to do with running the script in the script editor vs running it as part of an Apple Mail rule? Just curious if anyone knows.

You need to define performMailActionWithMessages as a function, e.g.:

function performMailActionWithMessages(messages, options) {
	const app = Application('System Events');
	app.includeStandardAdditions = true;
	app.displayDialog(messages.map((message) => message.subject()).join(', '))
	if (options.inMailboxes) app.displayDialog(options.inMailboxes.map((mailbox) => mailbox.name()).join(', '))

Added some arbitrary System Events code just to show how the parameters work.

Note: The Can't convert types error is saying that you’re passing the wrong argument to mail.performMailActionWithMessages, since your script is calling the function directly (vs. Mail calling it). You would need to provide a list of messages here for the code to be valid (albeit not immensely useful).

1 Like

Ah ok thanks Stephen. This appears to work when a new email comes in but if I right click an email and say “Apply Rules” it doesn’t (I’m mainly doing that for testing the script). Do you happen to know if the intention of that feature is to run the rule like usual? Or will it just skip it because it’s already been passed to the script.

It works for me when using ‘Apply Rules’, so I’m not sure. Might be an issue with the exact rule you’re trying to apply.