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

时间:2018-01-16 15:12:15

标签: ios objective-c email mfmailcomposeviewcontroller mfmailcomposer

有没有办法发送电子邮件并由设备上的所有应用程序处理?比如GMail,Yahoo,Outlook,还是需要使用每个自己的库来实现这样的功能?

我可以使用某种通用网址或方案来选择设备上所有可用的电子邮件客户端吗?

目前,为了编写电子邮件,我使用的是MFMailComposeViewController但如果用户没有使用Mail应用程序进行帐户设置,那么它就不起作用了,很多人都没有。

2 个答案:

答案 0 :(得分:1)

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

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

希望它有所帮助!

答案 1 :(得分:0)

有一个不错的ThirdPartyMailer库,可以处理所有第三方url。 LSApplicationQueriesSchemes文件中的邮件客户端需要set Info.plist

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

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)