Reputation: 71
I'm stuck writing a JXA script using Apple's Script Editor. Essentially, I want to go through my inbox folder and move messages older than 44 days to an archive folder. I'm able to find the account, and my inbox and archive "mailboxes", but I can't for the life of me figure out how to move the darn message to a new mailbox.
Here's what I have so far:
var staleTime = 44;
var countMessages = 0;
var Mail = new Application("Mail")
var accounts = Mail.accounts();
var account;
var found = false;
for (i = 0; i < accounts.length && !found; ++i) {
if (accounts[i].name().indexOf("xchange") > -1) {
account = accounts[i];
found = true;
}
}
var mailboxes = account.mailboxes();
var inbox;
var archive;
for (i = 0; i < mailboxes.length; ++i) {
if(mailboxes[i].name().indexOf("nbox") > -1) {
inbox = mailboxes[i];
}
if(mailboxes[i].name().indexOf("rchive") > -1 &&
mailboxes[i].name().indexOf("CDE") == -1) {
archive = mailboxes[i];
}
}
// console.log("mailbox name is: " + inbox.name());
var messages = m inbox.messages();
var fortyFourDaysAgo = new Date();
fortyFourDaysAgo.setDate(fortyFourDaysAgo.getDate() - staleTime);
for (i = 0; i < messages.length; ++i) {
var dateSent = messages[i].dateSent();
if(dateSent < fortyFourDaysAgo) {
// now what???
}
}
I can see in the dictionary help in script editor that the Message object has a mailbox property, but none of the following seem to work:
messages[i].mailbox = archive;
messages[i].mailbox(archive);
any help would be greatly appreciated.
Upvotes: 3
Views: 883
Reputation: 3259
Yikes. This task should be a simple two-line script [1]:
set cutoffDate to (current date) - 44 * days
tell application "Mail" to move (every message of inbox whose date sent < cutoffDate) to mailbox "Archive"
As for how to translate it to JXA – well, there's reasons I generally recommend sticking to AppleScript, including non-broken implementation, better (if still not ideal) documentation, and an established community of expert users who are always happy to explain and assist newcomers.
Or, even simpler, just set up a Mail Rule and avoid the need for scripting completely!
[1] Assuming you know how Apple event-based automation actually works, which 99.99% of programmers don't due to 1. Apple's own documentation failing utterly to explain it either clearly or correctly, and 2. Scripting Bridge and JXA crippling and obfuscating the crap out of it. Short version: it's not OOP, it's RPC plus simple first-class relational queries. (Slightly longer, if somewhat patchy explanation here.)
Upvotes: 0
Reputation: 71
Asked the question over on the Apple Discussion Board and got an answer.
Essentially, replace
// now what???
... with ...
Mail.move(messages[i], {to: archive});
Actually, the post over there had a more succinct way of doing it, but the above works too.
Upvotes: 3