ios 如何从 Swift 打开邮件应用程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25981422/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to open mail app from Swift
提问by Jesse.H
Im working on a simple swift app where the user inputs an email address and presses a button which opens the mail app, with the entered address in the address bar. I know how to do this in Objective-C, but I'm having trouble getting it to work in Swift.
我正在开发一个简单的 swift 应用程序,用户输入一个电子邮件地址并按下一个按钮来打开邮件应用程序,在地址栏中输入地址。我知道如何在 Objective-C 中执行此操作,但是我无法在 Swift 中使用它。
回答by Stephen Groom
You can use simple mailto: links in iOS to open the mail app.
您可以使用简单的 mailto: 链接在 iOS 中打开邮件应用程序。
let email = "[email protected]"
if let url = URL(string: "mailto:\(email)") {
if #available(iOS 10.0, *) {
UIApplication.shared.open(url)
} else {
UIApplication.shared.openURL(url)
}
}
回答by Steve Rosenberg
I'm not sure if you want to switch to the mail app itself or just open and send an email. For the latter option linked to a button IBAction:
我不确定您是要切换到邮件应用程序本身还是只是打开并发送电子邮件。对于链接到按钮 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]"]
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)
}
}
回答by WebMajstr
While other answers are all correct, you can never know if the iPhone/iPad that is running your application has the Apple's Mail app installedor not as it can be deleted by the user.
虽然其他答案都是正确的,但您永远无法知道运行您的应用程序的 iPhone/iPad 是否安装了 Apple 的邮件应用程序,因为它可以被用户删除。
It is better to support multiple email clients. Following code handles the email sending in a more graceful way. The flow of the code is:
最好支持多个电子邮件客户端。以下代码以更优雅的方式处理电子邮件发送。代码的流程是:
- If Mail app is installed, open Mail's composer pre-filled with provided data
- Otherwise, try opening the Gmail app, then Outlook, then Yahoo mail, then Spark, in this order
- If none of those clients are installed, fallback to default
mailto:..
that prompts the user to install Apple's Mail app.
- 如果安装了邮件应用程序,打开邮件的作曲家预先填充提供的数据
- 否则,请尝试依次打开 Gmail 应用程序、Outlook、Yahoo 邮件、Spark,按此顺序
- 如果没有安装这些客户端,则回退到默认
mailto:..
提示用户安装 Apple 的邮件应用程序。
Code is written in Swift 5:
代码是用Swift 5编写的:
import MessageUI
import UIKit
class SendEmailViewController: UIViewController, MFMailComposeViewControllerDelegate {
@IBAction func sendEmail(_ sender: UIButton) {
// Modify following variables with your text / recipient
let recipientEmail = "[email protected]"
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)
}
}
Please note that I intentionally missed out the body for the Outlook app, as it is not able to parse it.
请注意,我故意错过了 Outlook 应用程序的正文,因为它无法解析它。
You also have to add following code to Info.plist
file that whitelists the URl query schemes that are used.
您还必须将以下代码添加到将Info.plist
所使用的 URl 查询方案列入白名单的文件中。
<key>LSApplicationQueriesSchemes</key>
<array>
<string>googlegmail</string>
<string>ms-outlook</string>
<string>readdle-spark</string>
<string>ymail</string>
</array>
回答by Ved Rauniyar
In Swift 3 you make sure to add import MessageUI
and needs conform to the MFMailComposeViewControllerDelegate
protocol.
在 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
}
}
Protocol:
协议:
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
controller.dismiss(animated: true)
}
回答by Ixx
Swift 2, with availabilitycheck:
Swift 2,带有可用性检查:
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)
}
回答by Yuval
Here how it looks for Swift 4:
这是 Swift 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)
}
回答by Mehdico
For Swift 4.2+ and iOS 9+
适用于 Swift 4.2+ 和 iOS 9+
let appURL = URL(string: "mailto:[email protected]")!
if #available(iOS 10.0, *) {
UIApplication.shared.open(appURL, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(appURL)
}
Replace [email protected] with your email.
将 [email protected] 替换为您的电子邮件。
回答by Ben W
Updated answer from Stephen Groom for Swift 3
Stephen Groom 为 Swift 3 更新的答案
let email = "[email protected]"
let url = URL(string: "mailto:\(email)")
UIApplication.shared.openURL(url!)
回答by Nii Mantse
Here's an update for Swift 4 if you're simply looking to open up the mail client via a URL
:
如果您只是想通过以下方式打开邮件客户端,这里是 Swift 4 的更新URL
:
let email = "[email protected]"
if let url = URL(string: "mailto:\(email)") {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
This worked perfectly fine for me :)
这对我来说非常好:)
回答by Maria Ortega
This is a straight forward solution of 3 steps in Swift.
这是 Swift 中 3 个步骤的直接解决方案。
import MessageUI
Add to conform the Delegate
添加以符合委托
MFMailComposeViewControllerDelegate
And just create your method:
只需创建您的方法:
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)
}