Mail Rule Script running on previous message in Inbox

I’m having some issues with my Mail Script that I’ve attached to a rule in Mail.
It is executing properly, BUT it’s working on the previous item at the top of my inbox rather on the new message that has just arrived. It’s almost as if the script is faster than the mail server and is executing on the incorrect message.

I took most of my code directly from forums on here and from the sample code that Apple uses in the mail scrip examples.

I’m working on a Microsoft Exchange 2007 mail server and wouldn’t be shocked if it was helping cause some of these problems. I’ve yet to try to attach the script to a non-Exchange account but will try that soon.

The goal is to download attached files from incoming emails.

The script works perfectly if I take it out of the rule form.
Its successfully downloads the attachments when I leave it in rule form, But for the wrong email message.

Here’s what i’m working with right now:


using terms from application "Mail"
	on perform mail action with messages theMessages for rule theRule
		tell application "Mail"
			
			repeat with aMessage in theMessages
				
				
				set theSubject to the subject of aMessage
				display dialog theSubject as text
				
				set theAttached to every mail attachment of aMessage
				repeat with i in theAttached
					set attachProp to properties of i
					log attachProp
					
					set fileName to name of i as text
					set theOutput to "The Brain:Users:alex:Desktop:"
					save i in (theOutput & fileName)
					
				end repeat
			end repeat
		end tell
		
	end perform mail action with messages
end using terms from


I’ve played around with using delay commands and the “check for new mail” command to retrieve the item and have the script execute on it but this hasn’t worked either.

Thanks for all the help!

-Alex F