MFMailComposeViewController in Swift

前端 未结 5 740
没有蜡笔的小新
没有蜡笔的小新 2021-02-03 21:36

This is sample code:

import UIKit
import MessageUI

class ViewController: UIViewController, MFMailComposeViewControllerDelegate {

    @IBAction func showEmail(s         


        
5条回答
  •  别那么骄傲
    2021-02-03 21:58

    In swift 3, you can use this clear code:

     @IBAction func sendMail(_ sender: Any) {
    
            print(MFMailComposeViewController.canSendMail())
            if MFMailComposeViewController.canSendMail() {
                let mail = MFMailComposeViewController()
                mail.mailComposeDelegate = self
                mail.setToRecipients(["test@test.com"])
                mail.setMessageBody("

    This is test Mail!

    ", isHTML: true) present(mail, animated: true) } else { let email = "test@test.com" if let url = URL(string: "mailto:\(email)") { UIApplication.shared.open(url) } } } func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { controller.dismiss(animated: true) switch result { case .cancelled: print("Mail cancelled") case .saved: print("Mail saved") case .sent: self.allertInfo(_title: "Mail Info", _message: "Mail is sent successfuly", _actionTitle: "OK") print("Mail sent") case .failed: self.allertInfo(_title: "Mail Info", _message: "Mail isn't sent.", _actionTitle: "OK") print("Mail sent failure: \(error?.localizedDescription)") default: break } } func allertInfo(_title:String, _message:String, _actionTitle:String) { let alert = UIAlertController(title: _title, message: _message, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: _actionTitle, style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) }

提交回复
热议问题