1

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.

Crashmeister
  • 375
  • 1
  • 14

1 Answers1

1

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
jackjr300
  • 7,111
  • 2
  • 15
  • 25
  • Thanks. I've just seen this as I was not notified when you posted. I'll try this in a sandbox and see if I can get it to work for local box. – Crashmeister Aug 12 '17 at 21:25
  • See extension to my post above. I cannot get it to work if there are spaces in one of the mailbox names. – Crashmeister Aug 12 '17 at 22:43
  • Your code works fine on my computer (`macOS Sierra`, **Version 10.12.6**). Sorry ,I cannot help you. – jackjr300 Aug 13 '17 at 15:27
  • I'm also on 10.12.6. I gave up and removed the spaces from my mailbox names. Archiver script is now working. – Crashmeister Aug 16 '17 at 15:44