2014-09-22 91 views
42

我正在使用一个简单的快速应用程序,用户在其中输入电子邮件地址并按下打开邮件应用程序的按钮,并在地址栏中输入地址。我知道如何在Objective-C中做到这一点,但我无法在Swift中使用它。如何从Swift打开邮件应用程序

回答

37

我不确定您是要切换到邮件应用程序本身,还是只需打开并发送电子邮件。对于链接到一个按钮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 = ["[email protected]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) 
    } 

    } 
+1

我遇到了未调用mailComposeController委托函数的问题。 – AustinT 2015-01-22 05:31:42

+3

添加“导入MessageUI”你的进口,并确保到“MFMailComposeViewControllerDelegate”选项添加到您的类声明,如: 'MyClass类:UIViewController中,MFMailComposeViewControllerDelegate {' – Jalakoo 2015-02-21 01:27:19

+0

MFMailComposeViewController()对我来说 – ilan 2015-04-20 07:21:08

128

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

let email = "[email protected]" 
if let url = URL(string: "mailto:\(email)") { 
    UIApplication.shared.open(url) 
} 
+37

也许值得一提的是,这在模拟器中不起作用,只能在设备上运行...请参阅http://stackoverflow.com/questions/26052815/how -can-i-launch-an-email-client-on-ios-using-swfit – Pieter 2015-04-24 09:44:10

+4

现在您需要添加“!”在第二行中,对于NSURL NSURL(字符串:“mailto:\(email)”)! – anthonyqz 2015-11-07 19:58:58

+1

只是最好和最简单的答案。 thx – 2016-03-23 22:38:08

13

夫特2,用availability检查:

import MessageUI 

if MFMailComposeViewController.canSendMail() { 
    let mail = MFMailComposeViewController() 
    mail.mailComposeDelegate = self 
    mail.setToRecipients(["[email protected]"]) 
    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) 
} 
+1

如果在执行此操作时收到模拟器错误,则可能是由于模拟器错误:https://stackoverflow.com/questions/25895634/email-composure-ios-8 – 2016-03-02 18:04:29

7

这在夫特3个步骤的直接的解决方案。

import MessageUI 

添加符合委派

MFMailComposeViewControllerDelegate 

而刚刚创建的方法:

func sendEmail() { 
    if MFMailComposeViewController.canSendMail() { 
     let mail = MFMailComposeViewController() 
     mail.mailComposeDelegate = self 
     mail.setToRecipients(["[email protected]"]) 
     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) 
} 
5
import UIKit 
import MessageUI 

class ViewController: ViewController,MFMailComposeViewControllerDelegate { 

    @IBAction func EmailBtnClicked(sender: AnyObject) { 
     let mailComposeViewController = configuredMailComposeViewController() 
     if MFMailComposeViewController.canSendMail() { 
      self.presentViewController(mailComposeViewController, animated: true, completion: nil) 
     } else { 
      self.showSendMailErrorAlert() 
     } 
    } 

    func configuredMailComposeViewController() -> MFMailComposeViewController { 
     let mailComposerVC = MFMailComposeViewController() 
     mailComposerVC.mailComposeDelegate = self // Extremely important to set the --mailComposeDelegate-- property, NOT the --delegate-- property 

     mailComposerVC.setToRecipients(["[email protected]"]) 
     mailComposerVC.setSubject("Sending you an in-app e-mail...") 
     mailComposerVC.setMessageBody("Sending e-mail in-app is not so bad in swift!", isHTML: false) 

     return mailComposerVC 
    } 

    func showSendMailErrorAlert() { 
     let sendMailErrorAlert = UIAlertView(title: "Unable to Send Email", message: "Your device could not send e-mail. Please check e-mail configuration and try again.", delegate: self, cancelButtonTitle: "OK") 
     sendMailErrorAlert.show() 
    } 

    // MARK: MFMailComposeViewControllerDelegate 

    func mailComposeController(controller: MFMailComposeViewController!, didFinishWithResult result: MFMailComposeResult, error: NSError!) { 
     controller.dismissViewControllerAnimated(true, completion: nil) 

    } 
} 
8

更新斯蒂芬新郎答案斯威夫特3

let email = "[email protected]" 
let url = URL(string: "mailto:\(email)") 
UIApplication.shared.openURL(url!) 
12

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

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

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

协议:

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

对于我们这些对雨燕2.3在这里仍落后是戈登在我们的语法答案:

let email = "[email protected]" 
if let url = NSURL(string: "mailto:\(email)") { 
    UIApplication.sharedApplication().openURL(url) 
} 
2
@IBAction func launchEmail(sender: AnyObject) { 
if if MFMailComposeViewController.canSendMail() { 
    var emailTitle = "Feedback" 
    var messageBody = "Feature request or bug report?" 
    var toRecipents = ["[email protected]"] 
    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) 
} 

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

2

呢?这里是如何寻找斯威夫特4:

import MessageUI 

if MFMailComposeViewController.canSendMail() { 
    let mail = MFMailComposeViewController() 
    mail.mailComposeDelegate = self 
    mail.setToRecipients(["[email protected]"]) 
    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) 
    } 
4

下面是斯威夫特4的更新,如果你只是希望通过URL打开邮件客户端:

let email = "[email protected]" 
if let url = NSURL(string: "mailto:\(email)") { 
    UIApplication.shared.open(url! as URL, options: [:], completionHandler: nil) 
} 

这个工作对我来说非常好:)

相关问题