1
votes

I am trying to create a sub-mailbox in Apple Mail using JavaScript.

I have the following code snippet (parent is a reference to the mailbox in which I want the new mailbox):

var mb = mail.Mailbox({name: "SubFolder"});
parent.mailboxes.push(mb);

The events log shows:

app = Application("Mail")
 app.mailboxes.byName("Local").mailboxes.byName("Archive").mailboxes.push(app.Mailbox({"name":"SubFolder"}))

    --> Error -10000: AppleEvent handler failed.

What am I doing wrong?

Thanks, Craig.

Code now:

var mb = mail.Mailbox({name: "Local/Archive/Test Archive/SubFolder"})
logger.logDebug("mb = '" + Automation.getDisplayString(mb) + "'.");
mail.mailboxes.push(mb)                     // create the subfolder

This works as long as there are no spaces in the path. I tried to force the space using \\ in front of it, but then you get "Test\ Archive" as the name.

So how do I get a space in the name to work?

Thanks.

1

1 Answers

1
votes

To create a sub-folder, you need a name like a posix path --> "/theMasterMailbox/subMailBox1/subMailBox2/subMailBox3".


So, you need:

  • A loop to put the name of each parent folder into an array.
  • Use join('/') to join the elements of an array into a string.
  • Use mail.mailboxes.push(mb) instead of parent.mailboxes.push(mb)

Here's a sample script which creates a mailbox named "SubFolder" in the selected folder (the mailbox):

mail = Application('com.apple.Mail')
parent = mail.messageViewers()[0].selectedMailboxes()[0]

mboxNames = [parent.name()]
thisFolder = parent
try {
    while (true) { // loop while exists the parent folder 
        mboxNames.unshift(thisFolder.container().name()) // add the name of the parent folder to the beginning of an array
        thisFolder = thisFolder.container() // get the parent of thisFolder
    }
} catch (e) {} // do nothing on error, because thisFolder is the top folder

mboxNames.push("SubFolder") // append the name of the new subFolder to the array

mBoxPath = mboxNames.join('/') // get a string (the names separated by "/")
mb = mail.Mailbox({name:mBoxPath})
mail.mailboxes.push(mb) // create the subfolder