How to open mail app from Swift

前端 未结 15 1273
被撕碎了的回忆
被撕碎了的回忆 2020-11-30 20:18

Im working on a simple swift app where the user inputs an email address and presses a button which opens the mail app, with the entered address in the address bar. I know ho

相关标签:
15条回答
  • 2020-11-30 20:53

    In Swift 3 you make sure to add import MessageUI and needs conform to the MFMailComposeViewControllerDelegate protocol.

    func sendEmail() {
      if MFMailComposeViewController.canSendMail() {
        let mail = MFMailComposeViewController()
        mail.mailComposeDelegate = self
        mail.setToRecipients(["ved.ios@yopmail.com"])
        mail.setMessageBody("<p>You're so awesome!</p>", isHTML: true)
    
        present(mail, animated: true)
      } else {
        // show failure alert
      }
    }
    

    Protocol:

    func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
      controller.dismiss(animated: true)
    }
    
    0 讨论(0)
  • 2020-11-30 20:53

    Here how it looks for Swift 4:

    import MessageUI
    
    if MFMailComposeViewController.canSendMail() {
        let mail = MFMailComposeViewController()
        mail.mailComposeDelegate = self
        mail.setToRecipients(["test@test.test"])
        mail.setSubject("Bla")
        mail.setMessageBody("<b>Blabla</b>", isHTML: true)
        present(mail, animated: true, completion: nil)
    } else {
        print("Cannot send mail")
        // give feedback to the user
    }
    
    func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
            switch result.rawValue {
            case MFMailComposeResult.cancelled.rawValue:
                print("Cancelled")
            case MFMailComposeResult.saved.rawValue:
                print("Saved")
            case MFMailComposeResult.sent.rawValue:
                print("Sent")
            case MFMailComposeResult.failed.rawValue:
                print("Error: \(String(describing: error?.localizedDescription))")
            default:
                break
            }
            controller.dismiss(animated: true, completion: nil)
        }
    
    0 讨论(0)
  • 2020-11-30 20:56

    You should try sending with built-in mail composer, and if that fails, try with share:

    func contactUs() {
    
        let email = "info@example.com" // insert your email here
        let subject = "your subject goes here"
        let bodyText = "your body text goes here"
    
        // https://developer.apple.com/documentation/messageui/mfmailcomposeviewcontroller
        if MFMailComposeViewController.canSendMail() {
    
            let mailComposerVC = MFMailComposeViewController()
            mailComposerVC.mailComposeDelegate = self as? MFMailComposeViewControllerDelegate
    
            mailComposerVC.setToRecipients([email])
            mailComposerVC.setSubject(subject)
            mailComposerVC.setMessageBody(bodyText, isHTML: false)
    
            self.present(mailComposerVC, animated: true, completion: nil)
    
        } else {
            print("Device not configured to send emails, trying with share ...")
    
            let coded = "mailto:\(email)?subject=\(subject)&body=\(bodyText)".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
            if let emailURL = URL(string: coded!) {
                if #available(iOS 10.0, *) {
                    if UIApplication.shared.canOpenURL(emailURL) {
                        UIApplication.shared.open(emailURL, options: [:], completionHandler: { (result) in
                            if !result {
                                print("Unable to send email.")
                            }
                        })
                    }
                }
                else {
                    UIApplication.shared.openURL(emailURL as URL)
                }
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题