如何从Swift打开邮件应用程序

Jes*_*e.H 97 ios swift

我在一个简单的快速应用程序上工作,用户输入一个电子邮件地址并按下一个打开邮件应用程序的按钮,输入的地址在地址栏中.我知道如何在Objective-C中执行此操作,但是我无法在Swift中使用它.

Ste*_*oom 215

您可以在iOS中使用简单的mailto:链接来打开邮件应用程序.

let email = "foo@bar.com"
if let url = URL(string: "mailto:\(email)") {
  if #available(iOS 10.0, *) {
    UIApplication.shared.open(url)
  } else {
    UIApplication.shared.openURL(url)
  }    
}
Run Code Online (Sandbox Code Playgroud)

  • 也许值得补充一点,这在模拟器中不起作用,只在设备上...参见http://stackoverflow.com/questions/26052815/how-can-i-launch-an-email-client-on-ios - 使用 - swfit (67认同)
  • 现在你需要添加"!" 在第二行,对于NSURL NSURL(字符串:"mailto:\(email)")! (4认同)
  • 为什么它说这只适用于ios 10或更新,当答案显然是3岁时 (4认同)
  • Swift 4/iOS 10+ 示例:UIApplication.shared.open(url, options: [:], completionHandler: nil) 为选项传递空字典会产生与调用 openURL 相同的结果。 (2认同)

Ste*_*erg 53

我不确定您是想切换到邮件应用程序本身还是只是打开并发送电子邮件.对于后一个选项链接到按钮IBAction:

    import UIKit
    import MessageUI

    class ViewController: UIViewController, MFMailComposeViewControllerDelegate {

    @IBAction func launchEmail(sender: AnyObject) {

    var emailTitle = "Feedback"
    var messageBody = "Feature request or bug report?"
    var toRecipents = ["friend@stackoverflow.com"]
    var mc: MFMailComposeViewController = MFMailComposeViewController()
    mc.mailComposeDelegate = self
    mc.setSubject(emailTitle)
    mc.setMessageBody(messageBody, isHTML: false)
    mc.setToRecipients(toRecipents)

    self.presentViewController(mc, animated: true, completion: nil)
    }

    func mailComposeController(controller:MFMailComposeViewController, didFinishWithResult result:MFMailComposeResult, error:NSError) {
        switch result {
        case MFMailComposeResultCancelled:
            print("Mail cancelled")
        case MFMailComposeResultSaved:
            print("Mail saved")
        case MFMailComposeResultSent:
            print("Mail sent")
        case MFMailComposeResultFailed:
            print("Mail sent failure: \(error?.localizedDescription)")
        default:
            break
        }
        self.dismissViewControllerAnimated(true, completion: nil)
    }

    }
Run Code Online (Sandbox Code Playgroud)

  • 在导入中添加"import MessageUI",并确保将"MFMailComposeViewControllerDelegate"选项添加到类声明中,如:`class myClass:UIViewController,MFMailComposeViewControllerDelegate {` (3认同)
  • 还有问题:''NSInvalidArgumentException',原因:'应用程序试图在目标`上呈现一个零模态视图控制器.应用程序在某些设备(iPhone 5,iPhone 6和iPad Mini)中崩溃 (2认同)

Ved*_*yar 21

在Swift 3中,您确保添加import MessageUI并需要符合MFMailComposeViewControllerDelegate协议.

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

    present(mail, animated: true)
  } else {
    // show failure alert
  }
}
Run Code Online (Sandbox Code Playgroud)

协议:

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


Ixx*_*Ixx 16

Swift 2,可用性检查:

import MessageUI

if MFMailComposeViewController.canSendMail() {
    let mail = MFMailComposeViewController()
    mail.mailComposeDelegate = self
    mail.setToRecipients(["test@test.test"])
    mail.setSubject("Bla")
    mail.setMessageBody("<b>Blabla</b>", isHTML: true)
    presentViewController(mail, animated: true, completion: nil)
} else {
    print("Cannot send mail")
    // give feedback to the user
}


// MARK: - MFMailComposeViewControllerDelegate

func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
    switch result.rawValue {
    case MFMailComposeResultCancelled.rawValue:
        print("Cancelled")
    case MFMailComposeResultSaved.rawValue:
        print("Saved")
    case MFMailComposeResultSent.rawValue:
        print("Sent")
    case MFMailComposeResultFailed.rawValue:
        print("Error: \(error?.localizedDescription)")
    default:
        break
    }
    controller.dismissViewControllerAnimated(true, completion: nil)
}
Run Code Online (Sandbox Code Playgroud)


小智 14

这是它如何寻找Swift 4:

import MessageUI

if MFMailComposeViewController.canSendMail() {
    let mail = MFMailComposeViewController()
    mail.mailComposeDelegate = self
    mail.setToRecipients(["test@test.test"])
    mail.setSubject("Bla")
    mail.setMessageBody("<b>Blabla</b>", isHTML: true)
    present(mail, animated: true, completion: nil)
} else {
    print("Cannot send mail")
    // give feedback to the user
}

func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
        switch result.rawValue {
        case MFMailComposeResult.cancelled.rawValue:
            print("Cancelled")
        case MFMailComposeResult.saved.rawValue:
            print("Saved")
        case MFMailComposeResult.sent.rawValue:
            print("Sent")
        case MFMailComposeResult.failed.rawValue:
            print("Error: \(String(describing: error?.localizedDescription))")
        default:
            break
        }
        controller.dismiss(animated: true, completion: nil)
    }
Run Code Online (Sandbox Code Playgroud)


小智 12

Stephen Groom为Swift 3更新了答案

let email = "email@email.com"
let url = URL(string: "mailto:\(email)")
UIApplication.shared.openURL(url!)
Run Code Online (Sandbox Code Playgroud)


Nii*_*tse 10

如果您只是想通过以下方式打开邮件客户端,这里是Swift 4的更新URL:

let email = "foo@bar.com"
if let url = URL(string: "mailto:\(email)") {
   UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
Run Code Online (Sandbox Code Playgroud)

这对我来说非常好:)


Meh*_*ico 10

在Swift 4.2和iOS 9+中

let appURL = URL(string: "mailto:BLAH@BLAH.COM")!

if #available(iOS 10.0, *) {
    UIApplication.shared.open(appURL as URL, options: [:], completionHandler: nil)
}
else {
    UIApplication.shared.openURL(appURL as URL)
}
Run Code Online (Sandbox Code Playgroud)

用您的电子邮件替换BLAH@BLAH.COM.


小智 9

这是Swift中3个步骤的直接解决方案.

import MessageUI
Run Code Online (Sandbox Code Playgroud)

添加以符合委托

MFMailComposeViewControllerDelegate
Run Code Online (Sandbox Code Playgroud)

然后创建您的方法:

    func sendEmail() {
    if MFMailComposeViewController.canSendMail() {
        let mail = MFMailComposeViewController()
        mail.mailComposeDelegate = self
        mail.setToRecipients(["support@mail.com"])
        mail.setSubject("Support App")
        mail.setMessageBody("<p>Send us your issue!</p>", isHTML: true)
        presentViewController(mail, animated: true, completion: nil)
    } else {
        // show failure alert
    }
}

func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
    controller.dismissViewControllerAnimated(true, completion: nil)
}
Run Code Online (Sandbox Code Playgroud)


Web*_*str 9

尽管其他答案都正确,但是您永远无法知道正在运行应用程序的iPhone / iPad是否安装了Apple的Mail应用程序,因为用户可以删除它。

最好支持多个电子邮件客户端。以下代码以更优雅的方式处理电子邮件发送。代码流为:

  • 如果已安装Mail应用程序,请打开Mail的编辑器,该填充器已预先填充了提供的数据
  • 否则,请尝试依次打开Gmail应用,Outlook,Yahoo邮件和Spark。
  • 如果没有安装这些客户端,则回退到默认值mailto:..,提示用户安装Apple的Mail应用程序。

代码是用Swift 4编写的:

    import MessageUI
    import UIKit

    class SendEmailViewController: UIViewController, MFMailComposeViewControllerDelegate {

        @IBAction func sendEmail(_ sender: UIButton) {
            // Modify following variables with your text / recipient
            let recipientEmail = "test@email.com"
            let subject = "Multi client email support"
            let body = "This code supports sending email via multiple different email apps on iOS! :)"

            // Show default mail composer
            if MFMailComposeViewController.canSendMail() {
                let mail = MFMailComposeViewController()
                mail.mailComposeDelegate = self
                mail.setToRecipients([recipientEmail])
                mail.setSubject(subject)
                mail.setMessageBody(body, isHTML: false)

                present(mail, animated: true)

            // Show third party email composer if default Mail app is not present
            } else if let emailUrl = createEmailUrl(to: recipientEmail, subject: subject, body: body) {
                UIApplication.shared.open(emailUrl)
            }
        }

        private func createEmailUrl(to: String, subject: String, body: String) -> URL? {
            let subjectEncoded = subject.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
            let bodyEncoded = body.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!

            let gmailUrl = URL(string: "googlegmail://co?to=\(to)&subject=\(subjectEncoded)&body=\(bodyEncoded)")
            let outlookUrl = URL(string: "ms-outlook://compose?to=\(to)&subject=\(subjectEncoded)")
            let yahooMail = URL(string: "ymail://mail/compose?to=\(to)&subject=\(subjectEncoded)&body=\(bodyEncoded)")
            let sparkUrl = URL(string: "readdle-spark://compose?recipient=\(to)&subject=\(subjectEncoded)&body=\(bodyEncoded)")
            let defaultUrl = URL(string: "mailto:\(to)?subject=\(subjectEncoded)&body=\(bodyEncoded)")

            if let gmailUrl = gmailUrl, UIApplication.shared.canOpenURL(gmailUrl) {
                return gmailUrl
            } else if let outlookUrl = outlookUrl, UIApplication.shared.canOpenURL(outlookUrl) {
                return outlookUrl
            } else if let yahooMail = yahooMail, UIApplication.shared.canOpenURL(yahooMail) {
                return yahooMail
            } else if let sparkUrl = sparkUrl, UIApplication.shared.canOpenURL(sparkUrl) {
                return sparkUrl
            }

            return defaultUrl
        }

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

请注意,我故意错过了Outlook应用的正文,因为它无法解析它。

您还必须向Info.plist文件添加以下代码,该文件将使用的URl查询方案列入白名单。

<key>LSApplicationQueriesSchemes</key>
<array>
    <string>googlegmail</string>
    <string>ms-outlook</string>
    <string>readdle-spark</string>
    <string>ymail</string>
</array>
Run Code Online (Sandbox Code Playgroud)

  • 做得好。这是最完整的答案,并且可以轻松扩展到其他电子邮件客户端应用程序。恕我直言,我认为在 2019 年底,如果人们不使用默认的 Apple Mail 应用程序(正如大多数其他解决方案所建议的那样),只是告诉他们“对不起,你运气不好”是不可接受的。这弥补了这个缺陷。 (4认同)

iHa*_*hil 8

适用于 Swift 4.2 及以上版本

let supportEmail = "abc@xyz.com"
if let emailURL = URL(string: "mailto:\(supportEmail)"), UIApplication.shared.canOpenURL(emailURL)
{
    UIApplication.shared.open(emailURL, options: [:], completionHandler: nil)
}
Run Code Online (Sandbox Code Playgroud)

让用户选择许多邮件选项(如 iCloud、google、yahoo、Outlook.com - 如果手机中没有预先配置邮件)来发送电子邮件。

  • 就我而言,在 iOS 13 中,当调用 UIApplication.shared.open 时,操作系统将始终显示一个对话框,提供安装 Mail.app(哦,“mailto”的 canOpenURL 也始终为 true),即使有其他邮件应用程序。所以这绝对是行不通的。 (2认同)

len*_*ooh 7

您应该尝试使用内置邮件编辑器发送,如果失败,请尝试使用共享:

func contactUs() {

    let email = "info@example.com" // insert your email here
    let subject = "your subject goes here"
    let bodyText = "your body text goes here"

    // https://developer.apple.com/documentation/messageui/mfmailcomposeviewcontroller
    if MFMailComposeViewController.canSendMail() {

        let mailComposerVC = MFMailComposeViewController()
        mailComposerVC.mailComposeDelegate = self as? MFMailComposeViewControllerDelegate

        mailComposerVC.setToRecipients([email])
        mailComposerVC.setSubject(subject)
        mailComposerVC.setMessageBody(bodyText, isHTML: false)

        self.present(mailComposerVC, animated: true, completion: nil)

    } else {
        print("Device not configured to send emails, trying with share ...")

        let coded = "mailto:\(email)?subject=\(subject)&body=\(bodyText)".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
        if let emailURL = URL(string: coded!) {
            if #available(iOS 10.0, *) {
                if UIApplication.shared.canOpenURL(emailURL) {
                    UIApplication.shared.open(emailURL, options: [:], completionHandler: { (result) in
                        if !result {
                            print("Unable to send email.")
                        }
                    })
                }
            }
            else {
                UIApplication.shared.openURL(emailURL as URL)
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Shi*_*ash 6

在您希望点击打开邮件应用程序的视图控制器中。

  • 在文件顶部导入 MessageUI
  • 将此函数放入您的控制器中。

    func showMailComposer(){
    
      guard MFMailComposeViewController.canSendMail() else {
           return
      }
      let composer = MFMailComposeViewController()
      composer.mailComposeDelegate = self
      composer.setToRecipients(["abc@gmail.com"]) // email id of the recipient
      composer.setSubject("testing!!!")
      composer.setMessageBody("this is a test mail.", isHTML: false)
      present(composer, animated: true, completion: nil)
     }
    
    Run Code Online (Sandbox Code Playgroud)
  • 扩展您的视图控制器并符合MFMailComposeViewControllerDelegate

  • 使用此方法来处理邮件发送失败的情况。

    func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
      if let _ = error {
          controller.dismiss(animated: true, completion: nil)
          return
      }
      controller.dismiss(animated: true, completion: nil)
    }
    
    Run Code Online (Sandbox Code Playgroud)


小智 5

@IBAction func launchEmail(sender: AnyObject) {
 if if MFMailComposeViewController.canSendMail() {
   var emailTitle = "Feedback"
   var messageBody = "Feature request or bug report?"
   var toRecipents = ["friend@stackoverflow.com"]
   var mc: MFMailComposeViewController = MFMailComposeViewController()
   mc.mailComposeDelegate = self
   mc.setSubject(emailTitle)
   mc.setMessageBody(messageBody, isHTML: false)
   mc.setToRecipients(toRecipents)

   self.present(mc, animated: true, completion: nil)
 } else {
   // show failure alert
 }
}

func mailComposeController(controller:MFMailComposeViewController, didFinishWithResult result:MFMailComposeResult, error:NSError) {
    switch result {
    case .cancelled:
        print("Mail cancelled")
    case .saved:
        print("Mail saved")
    case .sent:
        print("Mail sent")
    case .failed:
        print("Mail sent failure: \(error?.localizedDescription)")
    default:
        break
    }
    self.dismiss(animated: true, completion: nil)
}
Run Code Online (Sandbox Code Playgroud)

请注意,并非所有用户的设备都配置为发送电子邮件,这就是为什么我们需要在尝试发送之前检查 canSendMail() 的结果。另请注意,您需要捕获 didFinishWith 回调才能关闭邮件窗口。