使用 Apple Mail 应用程序以外的外部应用程序发送电子邮件

Sending emails using external apps other than Apple Mail app

有没有什么方法可以发送电子邮件并让设备上所有可以这样做的应用程序处理它?例如 GMail、Yahoo、Outlook,还是需要使用各自的库来实现这样的功能?

是否有某种通用的 URL 或方案可用于提供设备上所有可用电子邮件客户端的选择?

目前,我使用 MFMailComposeViewController 撰写电子邮件,但如果用户没有使用 Mail 应用程序设置帐户(许多人没有),它就无法工作。

几个月前我遇到了完全相同的问题(尤其是在从模拟器进行测试时,因为它没有设置邮件帐户,因此发生了崩溃)。您需要在 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.")
    }
}

上面有很多过度验证,但那是出于调试原因。如果您完全确定该电子邮件地址(例如,之前的正则表达式匹配),那么一定要强制解包;否则,这将确保您的代码安全。

希望对您有所帮助!

您的 Info.plist 文件中有很好的 ThirdPartyMailer library which handles all third-party urls. You'll need to set LSApplicationQueriesSchemes 邮件客户端。

这是一个同时支持默认邮件应用程序和第三方客户端的实现:

let supportMail = "support@example.app"
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)