简体   繁体   中英

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?

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:

  • 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" "test@gmail.com" <<EOF
Hello, Test!
EOF

For Swift 4, little changes.

let service = NSSharingService(named: NSSharingService.Name.composeEmail)
service?.recipients = ["test@gmail.com"]
service?.subject = "Test Mail"
service?.perform(withItems: ["Test Mail body"])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM