Reputation: 4190
With the new option of setting the default mail app on settings, I'm wondering if there is a simpler solution to sending emails. Right now I'm using a manual solution adding 3rd party apps manually, like this:
...
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
}
Is there a way to simply ask, what is your default mail app, and open it to write the email?
Using the method above it only checks for apple mail app as default and whatever I have defined for the 3rd parties.
Upvotes: 3
Views: 1379
Reputation: 2571
On iOS 14.0; Apple allows iOS users to choose a default mail app in Settings
Users can choose their default email provider in settings, and all you have to do to compose an email would be:
let mailTo = "mailto:[email protected]".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
let mailtoUrl = URL(string: mailto!)!
if UIApplication.shared.canOpenURL(mailtoUrl) {
UIApplication.shared.open(mailtoUrl, options: [:])
}
It needs to be percent-encoded with the addingPercentEncoding
and then we would create an URL from this and open it with UIApplication.shared.open
.
We can also use standard URL parameters to customize the mailto
url. First parameter is denoted with ?
and then others are chained with &
.
We can add a subject and body like this:
let mailTo = "mailto:[email protected]?subject=Cool app feedback&body=Hello I have an issue...".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
Upvotes: 6