使用非苹果邮件应用程序发送电子邮件

3

有没有一种方法可以发送电子邮件并由设备上所有能够处理电子邮件的应用程序处理?例如GMail、Yahoo、Outlook,或者需要使用它们各自的库来实现这个功能?

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

目前,我使用MFMailComposeViewController来撰写电子邮件,但如果用户没有在邮件应用程序中设置帐户,则无法使用该功能,而许多用户确实没有设置。


苹果公司使这变得困难,因此如果有的话,您将不得不实现每个客户端库。 - rckoenes
2个回答

4

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

以上有很多重复的验证,但这些是为了调试目的。如果您绝对确定该电子邮件地址(例如之前的正则表达式匹配),那么可以强制解包;否则,这将确保您的代码安全。

希望这有所帮助!


0

有一个很不错的ThirdPartyMailer库,可以处理所有第三方链接。您需要在Info.plist文件中设置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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接