JXA: Create a mailbox in Apple Mail - applescript

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.

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

Related

Extendscript in Indesign not creating or writing to file

I am writing a script for Indesign that collects the contents from TextStyleRange objects, adds them to a javascript object, and should then write out a JSON file with the stringified JSON.
I can create the JSON just fine, with the contents from all of the TextStyleRanges in the current document, however the final file never gets written.
Here is a simplified example of what I have:
#include "json2.js";
main();
function main(){
myObj = { "key_1": "value_1", "key_2": "value_2" };
myContents = JSON.stringify(myObj, null, 4);
myFile = new File("~/Documents/myproject/en/translation.json");
myFile.open("w");
myFile.write( myContents );
$.writeln( myContents );
myFile.close();
}
In the VSCode debugger I can correctly see the JSON being output by $.writeln, however the file is not being created on disk. Any ideas what might be going wrong?
I'm using Windows 10, and Adobe Indesign 2022.
I have also tried with file edit but no luck:
myFile.open("e", "????", "????");
Actually it was simply that I needed to create the subfolder first:
var parentFolder = myFile.parent;
if (!parentFolder.exists && !parentFolder.create())
throw new Error("Cannot create file in path " + myFile.fsName);
After adding this to my script the folder and the file were created successfully.

How do I export contents between xml tags based on names in Extendscript for Indesign?

All I'd like to do here is open an InDesign 2018 CC file, pull out text uniquely (here I've chosen to grab content inside XML tag called "Title" from named tag window in the InDesign application side), save it to a txt file, and close the InDesign doc. I'm working in the Extendscript app, using Adobe InDesign CC 2018 (13.064). I just need to push to a txt file only certain named data (textboxes, xmltags, pageitems, etc) the contents based on anything, but via the name of the data holder. But xmltags are the only objects that I can name in the InDesign app apart from layers, and layers won't work for other reasons. So I'm stuck not being able to refer to xml-tagged contents. Please help.
Note:
I get an error with this code saying "Title" isn't defined, and I understand the error, but not sure how to utilize the method XML.toString() without referring to an object that's named inside the InDesign file. So I guess I'm using the wrong method to refer to xml-tagged data already located in a file??
So naturally, I throw out XML.toString() and utilize the commented out code (below) "app.activeDocument.xmlItems.item;" thinking maybe I will get an array of all items that are xml tagged, which is not even specific enough for my goal, but I'm desperate, and I get another newer error regarding the "exportfile" line of code: myArticles.exportFile() is not a function.
My code so far:
app.open(File("C:/Users/Sean/Desktop/New folder/va tech 2.indd"), true);
myArticles = Title.toString();
//THIS ATTEMPT WON'T WORK EITHER AS RPLCMNT FOR LINE ABOVE: myArticles= app.activeDocument.xmlItems.item;
myArticles.exportFile(ExportFormat.textType, new File("/C/Users/Sean/Desktop/New folder/test.txt"), false);
app.documents.everyItem().close(SaveOptions.NO);
var main = function() {
var doc, root, xes, n, nXE, st, xc, strs = [],
f = File ( Folder.desktop+"/contents.txt" );
try {
//NEED TO CHANGE THE URL. Ex: some/url > /Users/user/Desktop/foo.indd
doc = app.open ( File ( "some/url" ) );
}
catch(err){
alert(err.message);
return;
}
if ( !doc ) {
alert("You need an open document" );
return;
}
root = doc.xmlElements[0];
xes = root.evaluateXPathExpression("//Title");
n = xes.length;
while ( n-- ) {
nXE = xes[n];
xc = nXE.xmlContent;
if ( xc instanceof Story ) {
strs.push( xc.contents );
}
}
if ( strs.length ) {
f.open('w');
f.write ( strs.reverse().join("\r") );
f.close();
}
}
var u;
app.doScript ( "main()",u,u,UndoModes.ENTIRE_SCRIPT, "The Script" );

Deleting Files in Shared Google drive using Apple script

I have a shared folder and one of the editor usually add files into it. I want to keep flushing the folder by the following code by capturing its last change date. Its throwing error and it seems to me that as i am NOT the owner of the file, i cannot able to delete. Is there any way out?
function 7DayFlush()
{
// Log the files names and its last change info for the mentioned folder (by id)
// Enter the ID between Bracket
var mfolder = DriveApp.getFolderById('<i keep folder id here>');
// Following will get files from the folder.
var lfiles = mfolder.getFiles();
while (lfiles.hasNext()) {
var file = lfiles.next();
if (new Date() - file.getLastUpdated() > 7 * 24 * 60 * 60 * 1000) {
//Following will delete the files which matches the above condition which is older than 7days in the specified folder.
Logger.log(file.getName()+'----'+file.getLastUpdated());
//here is the error comes up.. help me.
file.setTrashed(true);
//here is the error comes up.. help me.
}
}
}

Create and show a PDF file from a Lotus Notes action

I'm using an action inside a form to create a Word document, using the CreateObject("Word.application") method, then I modify it to my liking and save it in a temp directory.
I can show the Word document as soon as it is created by calling nameOfTheDocument.visible(true), and by modifying the Save action I can save the newly created document as a PDF, however I can't find a way to show it to the user.
Trying to call visible(true) on the PDF object results in error "Instance member VISIBLE does not exist"
Hmmm... The best and right way - use OS file association.
I'm use java way:
//Win
Process p = Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + filePath);
p.waitFor();
//MacOS.*Nix
Process p = Runtime.getRuntime().exec("/usr/bin/open " + filePath);
p.waitFor();
But you can call this command on Lotusscript:
Shell({rundll32 url.dll,FileProtocolHandler } & fullFilePath,1)
'or
Shell({/usr/bin/open } & fullFilePath,1)
We have used the Shell command to launch PDFs in the past. Something like the below. The only downside to this is if the location of the executable changes (whether from upgrade or change to a different program) the code breaks.
Dim ProgPath$, FilePath$
Dim result As Integer
'Path of the executable
ProgPath$ = |"C:\Program Files (x86)\Adobe\Acrobat 7.0\Acrobat\Acrobat.exe"|
'Path of the file to open
FilePath$ = | "C:\TestFile.PDF"|
result = Shell(ProgPath$ & FilePath$,1)

exportDocument() 'destination folder does not exist' error

I'm trying to make a script in photoshop that will modify some layers and than export them as a PNG image. I've copied the following code from another place:
function SavePNG(saveFile){
var pngOpts = new ExportOptionsSaveForWeb;
pngOpts.format = SaveDocumentType.PNG
pngOpts.PNG8 = false;
pngOpts.transparency = true;
pngOpts.interlaced = true;
pngOpts.quality = 100;
activeDocument.exportDocument(saveFile,ExportType.SAVEFORWEB,pngOpts);
}
The function export the active document of photoshop to the file specified by the saveFile parameter.
It's working fine with simple paths like "C:\images\result.png" but when trying with different paths like "~/Desktop/" or paths with some special characters the file isn't exported, and a "destination folder does not exist" error message appears.
Any idea how can I solve it?
Well, I'm not sure why this is occur but you could try the following modification:
function SavePNG(saveFile){
var tmpFile = "./tmp.png";
tmpFile = new File(tmpFile);
var pngOpts = new ExportOptionsSaveForWeb;
pngOpts.format = SaveDocumentType.PNG
pngOpts.PNG8 = false;
pngOpts.transparency = true;
pngOpts.interlaced = true;
pngOpts.quality = 100;
activeDocument.exportDocument(tmpFile,ExportType.SAVEFORWEB,pngOpts);
tmpFile.rename (saveFile);
tmpFile.changePath(saveFile);
}
it'll export the file into a temporary file and then rename & move it to the requested path, should solve the path problem.
exportDocument expects a full file name, not a folder path.
This works:
activeDocument.exportDocument(new File("~/foo/foo.png"), ExportType.SAVEFORWEB, pngOpts);
This doesn't work and gives the 'destination folder does not exist' error message:
activeDocument.exportDocument(new File("~/foo/"), ExportType.SAVEFORWEB, pngOpts);
For people having this error and not using photoshop-script.
The error might be unbound to the destination folder, but occurs because the folder, which was used for the export step, is deleted. So either
recreate the folder, which was used during recording, or
recreate the export step

Resources