Search code examples
swiftmacosemailioapplescript

Open mail app with a specific mail in the inbox with Swift


I have the UID of a E-Mail message in the inbox. Now I want to open Apple Mail (or alternatively Outlook) to present that mail to the user. All examples I have found are how to start the standard Mail program to compose a new E-Mail.

Any Idea, hoe to solve that. I tried with a Applescript but it does not work.

import SwiftUI

struct ContentView: View {
  var body: some View {
    Button(action: {
      present_Email()
    }) {
      Text("Show E-Mail")
    }
    .frame(maxWidth: .infinity, maxHeight: .infinity)
  }
}

func present_Email()
{
  let myAppleScript = """
    tell application "Mail"
    set myMessages to messages 1 through 1 of inbox
    repeat with aMesseage in myMessages
    open (contents of aMesseage)
    end repeat
    end tell
    """

  var error: NSDictionary?
  if let scriptObject = NSAppleScript(source: myAppleScript) {
    scriptObject.executeAndReturnError( &error)
  }
}

Solution

  • Found a quite easy Solution:
    To open the Mail App with a given Message-ID you can simply open it via the message: URL Scheme.
    No Need for AppleScript ;-).

    Button(action: {
      NSWorkspace.shared.open(URL(string: "message:%3C...YOUR-MESSAGE_ID....%3E")!)
          }) {
            Text("Open E-Mail in Mail App")
          }