Search code examples
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 = ["[email protected]"]
    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:

    • If account is not configured on the system, this code will show configuration window for mail
    • When user will try to send mail it'll be shown improper setting related error by Mail app so you need not to bother about it
    • If you want to use other then Mail app, just try your own mail system, native mail client or third party mail framework.

    Try from terminal:

    You can use shell script to send mail using native client

    mail -s "Hello" "[email protected]" <<EOF
    Hello, Test!
    EOF