通过在设置中设置默认邮件应用程序的新选项,我想知道是否有更简单的发送电子邮件的解决方案。现在我正在使用手动解决方案手动添加第 3 方应用程序,如下所示:
...
if MFMailComposeViewController.canSendMail() {
self.settingsViewModel.showingFeatureEmail.toggle()
} else if let emailUrl = self.settingsViewModel.createEmailUrl(to: self.generalConstants.email, subject: "Feature request! [\(self.generalConstants.appName)]", body: "Hello, I have this idea ") {
UIApplication.shared.open(emailUrl)
} else {
self.settingsViewModel.showMailFeatureAlert = true
}
...
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)")
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 nil
}
有没有一种方法可以简单地询问您的默认邮件应用程序是什么,然后打开它来编写电子邮件?
使用上面的方法,它仅检查默认的苹果邮件应用程序以及我为第 3 方定义的任何内容。
最佳答案
iOS 14.0+ | swift 5.3
在 iOS 14.0 上; Apple 允许 iOS 用户在 Settings 中选择默认邮件应用程序
用户可以在设置中选择默认电子邮件提供商,而您撰写电子邮件所需要做的就是:
let mailTo = "mailto:<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="355b50585056505e75464045455a47411b565a58" rel="noreferrer noopener nofollow">[email protected]</a>".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
let mailtoUrl = URL(string: mailto!)!
if UIApplication.shared.canOpenURL(mailtoUrl) {
UIApplication.shared.open(mailtoUrl, options: [:])
}
它需要使用 addingPercentEncoding
进行百分比编码,然后我们将由此创建一个 URL 并使用 UIApplication.shared.open
打开它。
我们还可以使用标准 URL 参数来自定义 mailto
url。第一个参数用 ?
表示,然后其他参数用 &
链接。
我们可以像这样添加主题和正文:
let mailTo = "mailto:<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d7b9b2bab2b4b2bc97a4a2a7a7b8a5a3f9b4b8ba" rel="noreferrer noopener nofollow">[email protected]</a>?subject=Cool app feedback&body=Hello I have an issue...".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
关于swift - 使用默认电子邮件提供商发送电子邮件 - SwiftUI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69014322/