【问题标题】:Sending emails using external apps other than Apple Mail app使用 Apple Mail 应用程序以外的外部应用程序发送电子邮件
【发布时间】:2018-01-16 15:12:14
【问题描述】:

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

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

目前,为了撰写电子邮件,我使用 MFMailComposeViewController,但如果用户没有使用 Mail 应用程序设置帐户,它就不起作用,而很多人没有。

【问题讨论】:

  • Apple 让这变得很困难,因此您必须实现每个客户端的库(如果有的话)。

标签: ios objective-c email mfmailcomposeviewcontroller mfmailcomposer


【解决方案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.")
    }
}

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

希望对你有帮助!

【讨论】:

  • 运气好吗?
【解决方案2】:

有一个很好的ThirdPartyMailer 库,可以处理所有第三方网址。您需要 set LSApplicationQueriesSchemes 用于您的 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)

【讨论】:

    猜你喜欢
    • 2020-11-26
    • 2010-12-20
    • 2015-07-07
    • 2010-12-02
    • 1970-01-01
    • 2016-02-18
    • 2013-08-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多