swiftmacosemailmessageui

How to open mail panel in Swift? Mac OS


For the past few days I've been strugling with finding a way to send emails from my app. This is the sample code I am currently using. It think, by using this method, I might be unable to handle the situation of an improper setting of the mail accound of the computer my app will be running, so I thought about using a different method. I was wondering if is there any MessageUI equivalent for mac os. Is there any MessageUI equivalent for mac os. Any ideas?


Solution

  • There are two ways to do that:

    1. AppleScript framework

    2. NSSharingService

    NSSharingService to compose mail:

    let service = NSSharingService(named: NSSharingServiceNameComposeEmail)
    
    service?.recipients = ["test@gmail.com"]
    service?.subject = "Test Mail"
    service?.performWithItems(["Test Mail body"])
    

    Launch Mail App

    If you just want to open Mail app, try below code:

    NSWorkspace.sharedWorkspace().launchApplication("Mail")
    

    Improper Setting:

    Try from terminal:

    You can use shell script to send mail using native client

    mail -s "Hello" "test@gmail.com" <<EOF
    Hello, Test!
    EOF