MacOS – Backup mailbox of mail.app with applescript

applescriptbackupmacosmail.app

I would like to automate, with applescript, the back up a mailbox of mail, which is manually done with the menu "Export mailbox …", but:
I can not set the folder where the mailbox will be saved;
I can not set the mailbox to export, it works only with the mailbox that I've previously selected manually with the following command: Click menu item…

The lines of the script, which does not work, are:

tell application "Finder"
  --set mboxSavePath to "HD Macintosh:Users:simonepiersigilli:Desktop:e-mail:" -incorrect command to set the save path-
  --set mboxSavePath to "/Users/simonepiersigilli/Desktop/e-mail/" -incorrect command to set the save path-
  --set path POSIX to mboxSavePath -incorrect command to set the save path-
end tell
tell application "Mail" to activate
tell application "System Events"
  tell process "Mail"
  --click menu item "cesare@appuntidigitali.eu" of menu "Entrata" of menu "Caselle" of menu bar 2 -wrong command to set the mailbox to export-
  click menu item "Esporta casella di posta…" of menu "Casella" of menu bar 1 -correct command to open the menu "Export mailbox ..."-
  -- Now click the Go (choose) button
  click button "Scegli" of sheet of front window -correct command to click the button choose-
  tell application "Mail" to close the front window
  end tell
end tell

**UPDATE****

The intention is for the script to be run every week and it will have to backup the following inbox and sent mailboxes highlighted in red.

Mailboxes

Best Answer

GUI scripting is not that great. And can easily fail due to timing or GUI changes.

But try this:

set mboxSavePath to "/Users/simonepiersigilli/Desktop/e-mail/"

tell application "Mail" to activate
tell application "System Events"
    tell application process "Mail"


        click menu item 20 of menu 6 of menu bar 1
        delay 2
        keystroke "G" using {command down, shift down}
        delay 2
        keystroke mboxSavePath
        click button 1 of sheet 1 of sheet 1 of window 1

        click button 1 of sheet of front window


    end tell
end tell