2014-09-22 93 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) 
} 

這個工作對我來說非常好:)

相關問題