如何使用Swift在ios上启动电子邮件客户端

时间:2014-09-26 05:44:47

标签: ios swift

在Android中,我可以使用其Intent机制从我的Android应用程序启动电子邮件客户端。 在ios中,如何使用Swift从我的ios应用程序启动其电子邮件客户端?

谢谢。

4 个答案:

答案 0 :(得分:31)

let url = NSURL(string: "mailto:jon.doe@mail.com")
UIApplication.sharedApplication().openURL(url)

请注意,这仅适用于设备,而不适用于模拟器。

答案 1 :(得分:4)

更新iOS 10 +

//用于开放邮件应用程序或使用浏览器打开任何链接!

let url = NSURL(string: "mailto:your_mail_here@mail.com")

if #available(iOS 10.0, *) {
    UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
   // Fallback on earlier versions
   UIApplication.shared.openURL(url)
}

答案 2 :(得分:3)

Paul Hudson从Hacking in Swift找到了一个很好的解决方案。在Swift 3中,将import MessageUI添加到文件顶部,使类符合MFMailComposeViewControllerDelegate协议。

func sendEmail() {
  if MFMailComposeViewController.canSendMail() {
   let mail = MFMailComposeViewController()
   mail.mailComposeDelegate = self
   mail.setToRecipients(["example@example.com"])
   mail.setMessageBody("<p>You're so awesome!</p>", isHTML: true)

   present(mail, animated: true)
   } else {
   // show failure alert
  }
}

// MARK: MFMailComposeViewControllerDelegate Conformance

func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
    controller.dismiss(animated: true)
}

答案 3 :(得分:3)

SWIFT 3 :openEmail功能将尝试使用iOS Mail应用程序(如果可用)(用户至少有一个电子邮件帐户设置)。否则,它将使用mailto:url(请参阅我的回复底部的完整示例)来启动邮件客户端。

import MessageUI
// Make your view controller conform to MFMailComposeViewControllerDelegate
class Foo: UIViewController, MFMailComposeViewControllerDelegate {

    func openEmail(_ emailAddress: String) {
        // If user has not setup any email account in the iOS Mail app
        if !MFMailComposeViewController.canSendMail() {
            print("Mail services are not available")
            let url = URL(string: "mailto:" + emailAddress)
            UIApplication.shared.openURL(url!)
            return
        }

        // Use the iOS Mail app
        let composeVC = MFMailComposeViewController()
        composeVC.mailComposeDelegate = self
        composeVC.setToRecipients([emailAddress])
        composeVC.setSubject("")
        composeVC.setMessageBody("", isHTML: false)

        // Present the view controller modally.
        self.present(composeVC, animated: true, completion: nil)
    }

    // MARK: MailComposeViewControllerDelegate
    func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
        // Dismiss the mail compose view controller.
        controller.dismiss(animated: true, completion: nil)
    }
}

包含subject,body和cc的全部mailto示例:

  

“mailto:me@gmail.com?subject =嘿嘿呀!&amp; body =这是来自一个   我在网上找到的一个很好的例子。&amp; cc = someoneelse@yahooo.com& bcc=whostillusesthis@hotmail.com“