2014-09-26 50 views
3

在Android中,我可以使用其Intent機制從我的Android應用程序啓動電子郵件客戶端。 在ios中,我如何使用Swift從我的ios應用程序啓動它的電子郵件客戶端?如何使用Swfit在ios上啓動電子郵件客戶端

謝謝。

+0

您想發送郵件或啓動應用程序嗎? – 2014-09-26 05:48:16

回答

23
let url = NSURL(string: "mailto:[email protected]") 
UIApplication.sharedApplication().openURL(url) 

請注意,這隻適用於設備,不適用於模擬器。

+0

謝謝。啓動電子郵件應用程序時是否可以添加「主題」和「正文」? – hap497 2014-09-26 16:27:46

+2

是的,你可以使用網址方案。有關說明,請參見[這裏](http://en.wikipedia.org/wiki/Mailto)。甚至還有一個[generator](http://www.mailto.co.uk)。 - 是的,不要忘記在上面勾上勾號。 – Mundi 2014-09-26 19:54:25

2

我發現了Paul Hudson的Hacking in Swift的一個很好的解決方案。在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 
    } 
} 

// MARK: MFMailComposeViewControllerDelegate Conformance 

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

SWIFT 3:的openEmail功能將嘗試使用iOS郵件應用(如果可用)(用戶ATLEAST一個電子郵件帳戶設置)。否則,它將使用mailto:url(請參閱我答覆底部的完整示例)來啓動郵件客戶端。

「的mailto:?!

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) 
    } 
} 

全力以赴的mailto與主題,正文和CC例如[email protected]主題=哎怎麼了人&體=這是從 很好的例子,我在網上找到。& [email protected] & [email protected]

0

更新的iOS 10+

//用於打開郵件應用程序或打開與瀏覽器的任何鏈接!

let url = NSURL(string: "mailto:[email protected]") 

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