简体   繁体   中英

How to launch the iOS mail app in Swift?

I'm creating an iOS application with a password reset feature that sends an email to the user. After sending the email I want to display a UIAlertController to the user asking them if they would like to open the mail application.

I've seen various posts on here along the lines of:

let url = NSURL(string: "mailto:")
UIApplication.sharedApplication().openURL(url!)

This works but unfortunately it starts a new message which is not what I want. I only want to launch the application so the user can see their inbox.

Not tested myself but maybe this answer will help you:

Apparently Mail supports a second url scheme message:// which (I suppose) allows you to open a specific message if it was fetched by your application. If you do not provide a full message url, it will just open Mail:

let mailURL = URL(string: "message://")!
if UIApplication.shared.canOpenURL(mailURL) {
    UIApplication.shared.openURL(mailURL)
}

Taken from: Launch Apple Mail App from within my own App?

The Swift 3.0.1 way of just opening the Mail app goes as follows:

private func openMailClient() {
    let mailURL = URL(string: "message://")!
    if UIApplication.shared.canOpenURL(mailURL) {
        UIApplication.shared.openURL(mailURL)
    }
}

As "dehlen" correctly stated, using the message:// scheme will only open the mail app, if no further information is provided.

Obviously a few years later...I had to add a completion handler for Xcode 10.2.1 swift 5.

This works perfectly-

    let emailURL = NSURL(string: "message://")!

    if UIApplication.shared.canOpenURL(emailURL as URL)
    {
        UIApplication.shared.open(emailURL as URL, options: [:],completionHandler: nil)
    }

Since UIApplication.shared.openURL() method has been deprecated and we can use URL() directly in place of NSURL() , the updated version of this question's answer is:

let mailURL = URL(string: "message://")!
if UIApplication.shared.canOpenURL(mailURL) {
    UIApplication.shared.open(mailURL, options: [:], completionHandler: nil)
}

This will work with Xcode 11.5:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    switch indexPath.row {     
    case 5:
        openEmailApp(email: "email@gmail.com")
        
    default:
        break
    }
}

func openEmailApp(email: String) {
    if let url = URL(string: "mailto: \(email)") {
        UIApplication.shared.open(url)

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