Not authorized to send Apple events to Mail

I have a simple Swift-based macOS app that creates and executes an Apple Script:


let unreadEmailsScript = """
                             tell application "Mail"
                                  get unread count of inbox
                             end tell
                             """
    if let scriptObject = NSAppleScript(source: unreadEmailsScript) {
      var errorDict: NSDictionary? = nil
      scriptObject.executeAndReturnError(&errorDict)
     
      if let error = errorDict {
          print(error)
      }
    }


I've added the following to my project's entitlements:


<key>com.apple.security.temporary-exception.apple-events</key>

<array>

<string>com.apple.Mail</string>

</array>


When I execute this on the latest version (18A389) of Mojave the code prints:


{
    NSAppleScriptErrorAppName = Mail;
    NSAppleScriptErrorBriefMessage = "Not authorized to send Apple events to Mail.";
    NSAppleScriptErrorMessage = "Not authorized to send Apple events to Mail.";
    NSAppleScriptErrorNumber = "-1743";
    NSAppleScriptErrorRange = "NSRange: {33, 12}";
}


The system doesn't prompt me for authorization at app launch.


What is the correct way to send Apple Events to Mail via a Swift app under Mojave?


TIA

Answered by latency in 332158022

In case anyone else runs into this problem... what solved it for me was this the following. I added


<key>NSAppleEventsUsageDescription</key>

<string>Please give Unread Mail access to Mail via Apple Script.</string>


to my app's plist.


Now, upon first launch, the system prompts the user for permission. If permission is granted the app's Apple Script works correctly.

Accepted Answer

In case anyone else runs into this problem... what solved it for me was this the following. I added


<key>NSAppleEventsUsageDescription</key>

<string>Please give Unread Mail access to Mail via Apple Script.</string>


to my app's plist.


Now, upon first launch, the system prompts the user for permission. If permission is granted the app's Apple Script works correctly.

@latency you're a genius.
Not authorized to send Apple events to Mail
 
 
Q