How to speed up an AppleScript

How do I make the following AppleScript faster?

property Mailbox0: "" property Mailbox1: "" property Mailbox2: "" property Mailbox3: "" property currentMessageStr: "0" with timeout of 10000 seconds set currentMessage to currentMessageStr as integer tell application "Mail" set theMessage to (message currentMessage of mailbox (Mailbox3) of mailbox (Mailbox2) of mailbox (Mailbox1)) if not deleted status of theMessage then return source of theMessage end if end tell end timeout

  • The script is created dynamically depending on the mailbox.
  • The script is precompiled with NSAppleScriptMBS.
  • The script is executed by giving it a dictionary with the values for the mailbox and the currentMessage value.

But stil it’s §$%& slow.

I’ve identified 2 possible places for handling the result of getting the message body, but I’ve no idea how:

'bug in AppleScript that gives source back as Windows1252 (WindowsAnsi)
MailText = MailText.ConvertEncoding(Encodings.WindowsANSI)
MailText = MailText.DefineEncoding(Encodings.UTF8)

'unescape " and \
theResult = ReplaceAll(theResult, “”"", “”"")
theResult = ReplaceAll(theResult, “\”, “”)

So far for the unescaping everything I’ve tried makes things slower (added an instr, regex, regex MBS flavor).

I just tried this script directly through ScriptDebugger and it’s practically instant. What happens if you drag a compiled AppleScript into your project instead and run it directly? You would have to change the “property” lines to take parameters instead, of course.

BTW, in my test script, I had to specify an account to get a result.

It seems like you have your DefineEncoding and ConvertEncoding calls reversed, no?

Also, are you sure you want source of message and not content of message?

@Kem: try running it a couple of thousand times. Or for a larger mail. I can try to run it directly.

The script is for local mailboxes. You are correct, if there is an account then you have to specify the account name.

The encoding calls need to be inverted because the encodings are wrong when executing an AppleScript. I’ve had to open a Radar issue for this.

And yes, I need the source of the message for parsing it.

If you know up front that you are going to need a x messages, you should fetch them all at once instead of calling the script x times or using a loop. That will be significantly faster.

No, I don’t know if I need all messages. The script is part of a larger algorithm. The loop is over all mails in a mailbox. First the header is needed, then the app checks if the mail is already in the archive and the last part is the script above.

Getting all mails at once is also a bad idea for those few users who have a few large mailboxes.

I’ve run such an applescript over one of my mailboxes with 70000+ messages to get certain information (sender, date etc) to do some analysis of trends & it takes a while on that many emails

and returning 70,000 emails at once simply doesn’t work