iosobjective-cemailmfmailcomposeviewcontrollermfmailcomposer

Sending emails using external apps other than Apple Mail app


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.


Solution

  • 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 = "whoever@youwant.com"
    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!