【发布时间】:2014-11-21 01:36:04
【问题描述】:
在 Android 中,我可以使用其 Intent 机制从我的 android 应用程序启动电子邮件客户端。 在 ios 中,如何使用 Swift 从我的 ios 应用程序启动其电子邮件客户端?
谢谢。
【问题讨论】:
-
你想发邮件还是启动应用程序?
在 Android 中,我可以使用其 Intent 机制从我的 android 应用程序启动电子邮件客户端。 在 ios 中,如何使用 Swift 从我的 ios 应用程序启动其电子邮件客户端?
谢谢。
【问题讨论】:
SWIFT 3: openEmail 功能将尝试使用可用的 iOS 邮件应用程序(用户至少有一个电子邮件帐户设置)。否则它将使用 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)
}
}
一个包含主题、正文和抄送的完整邮件示例:
"mailto:me@gmail.com?subject=嘿,伙计!&body=这是来自 我在网上找到的很好的例子。&cc=someoneelse@yahooo.com&bcc=whostillusesthis@hotmail.com"
【讨论】:
我从 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)
}
【讨论】:
更新 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)
}
【讨论】:
为 Xcode 12.5 更新
let url = NSURL(string: "mailto:mailto:someone@example.com")
UIApplication.shared.open(url! as URL)
或者如果您想添加嵌入式主题
let url = NSURL(string: "mailto:someone@example.com?subject=This%20is%20the%20subject&cc=someone_else@example.com&body=This%20is%20the%20body")
或者如果您想添加多个电子邮件地址
let url = NSURL(string: "mailto:mailto:someone@example.com,someoneelse@example.com")
UIApplication.shared.open(url! as URL)
【讨论】: