Reputation: 1046
Is there any way to send an email and have it handled by all apps on the device which can do so? Such as GMail, Yahoo, Outlook, or does it requiring using each ones own library to implement such a feature?
Is there some sort of generic URL or scheme I can use to offer a choice of all available email clients on the device?
Currently, for composing an email I use the MFMailComposeViewController but it does not work if the user does not have an account setup with the Mail app, which many do not.
Upvotes: 3
Views: 1915
Reputation: 1564
There is nice ThirdPartyMailer library which handles all third-party urls. You'll need to set LSApplicationQueriesSchemes
for mail clients in your Info.plist
file.
Here is an implementation which support both default mail app and thirdparty clients:
let supportMail = "[email protected]"
let subject = "App feedback"
guard MFMailComposeViewController.canSendMail() else {
var client : ThirdPartyMailClient?
for c in ThirdPartyMailClient.clients() {
if ThirdPartyMailer.application(UIApplication.shared, isMailClientAvailable: c) {
client = c
break
}
}
guard client != nil else {
self.showError("Please contact us via \(supportMail)")
return
}
ThirdPartyMailer.application(
UIApplication.shared,
openMailClient: client!,
recipient: supportMail,
subject: subject,
body: nil
)
return
}
// set up MFMailComposeViewController
mailVC = MFMailComposeViewController()
mailVC.mailComposeDelegate = vc
mailVC.setToRecipients([supportMail])
mailVC.setSubject(subject)
Upvotes: 0
Reputation: 1232
I faced that exact same issue a few months ago (especially when testing from the simulator since this doesn't have mail account set and therefore a crash occurred). You need to validate this flow in your MFMailComposeViewControllerDelegate
let recipient = "[email protected]"
if MFMailComposeViewController.canSendMail() {
// Do your thing with native mail support
} else { // Otherwise, 3rd party to the rescue
guard let urlEMail = URL(string: "mailto:\(recipient)") else {
print("Invalid URL Scheme")
return
}
if UIApplication.shared.canOpenURL(urlEMail) {
UIApplication.shared.open(urlEMail, options: [:], completionHandler: {
_ in
})
} else {
print("Ups, no way for an email to be sent was found.")
}
}
There's a lot of over validation above but that's for debugging reasons. If you're absolutely sure of that email address (previous regular expression match for instance) then, by all means, just force unwrap; otherwise, this will keep your code safe.
Hope it helps!
Upvotes: 4