writing to file from Apple Mail Rule

Hi All,

My first question is, what are the known limitations when running a script from a rule in Mail? Like I have noticed that Display Dialog does not work. Is there a list around here somewhere that lists the limitations?

Second question is, can you write to a new file from an AppleScript that was launched by a Mail rule? I am using the following code and it does not work when run from a Mail rule. It runs just fine when I run it from SD. I am running this on 10.15.

using terms from application "Mail"
	on perform mail action with messages theMessages in mailboxes mbox for rule aRule
		repeat with i from 1 to (count of theMessages)
			set theMessage to item i of theMessages
			tell application "Mail"
				set outputFile to (((path to desktop folder) as rich text) & "temp.eml")
				set richSource to (source of theMessage) as rich text
			end tell
			try -- write text to EML file
				set the fileReference to open for access file outputFile with write permission
				set eof of the fileReference to 0
				write richSource to fileReference starting at eof
				close access the fileReference
			on error
				try
					close access file outputFile
				end try
			end try
			
		end repeat
	end perform mail action with messages
end using terms from

Thanks all!

  1. Tell to “Mail”, if you want display dialog to be at the front.

  2. Command path to is from Standard Additions too, but performed in the background, so you can tell to current application:


using terms from application "Mail"
	on perform mail action with messages theMessages in mailboxes mbox for rule aRule
		
		tell current application to set outputFile to ((path to desktop folder) as text) & "temp.eml"
		
		tell application "Mail" to display dialog "Mail rule performing..."
		tell application "Mail" to set richSource to (source of (item 1 of theMessages)) as rich text
		
		try -- write text to EML file
			set the fileReference to open for access file outputFile with write permission
			set eof of the fileReference to 0
			write richSource to fileReference starting at eof
			close access the fileReference
		on error
			try
				close access file outputFile
			end try
		end try
		
	end perform mail action with messages
end using terms from