How can I send mail from an iPhone application

前端 未结 11 1859
甜味超标
甜味超标 2020-11-22 11:47

I want to send an email from my iPhone application. I have heard that the iOS SDK doesn\'t have an email API. I don\'t want to use the following code because it will exit my

11条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 12:15

    Swift 2.2. Adapted from Esq's answer

    import Foundation
    import MessageUI
    
    class MailSender: NSObject, MFMailComposeViewControllerDelegate {
    
        let parentVC: UIViewController
    
        init(parentVC: UIViewController) {
            self.parentVC = parentVC
            super.init()
        }
    
        func send(title: String, messageBody: String, toRecipients: [String]) {
            if MFMailComposeViewController.canSendMail() {
                let mc: MFMailComposeViewController = MFMailComposeViewController()
                mc.mailComposeDelegate = self
                mc.setSubject(title)
                mc.setMessageBody(messageBody, isHTML: false)
                mc.setToRecipients(toRecipients)
                parentVC.presentViewController(mc, animated: true, completion: nil)
            } else {
                print("No email account found.")
            }
        }
    
        func mailComposeController(controller: MFMailComposeViewController,
            didFinishWithResult result: MFMailComposeResult, error: NSError?) {
    
                switch result.rawValue {
                case MFMailComposeResultCancelled.rawValue: print("Mail Cancelled")
                case MFMailComposeResultSaved.rawValue: print("Mail Saved")
                case MFMailComposeResultSent.rawValue: print("Mail Sent")
                case MFMailComposeResultFailed.rawValue: print("Mail Failed")
                default: break
                }
    
                parentVC.dismissViewControllerAnimated(false, completion: nil)
        }
    }
    

    Client code :

    var ms: MailSender?
    
    @IBAction func onSendPressed(sender: AnyObject) {
        ms = MailSender(parentVC: self)
        let title = "Title"
        let messageBody = "https://stackoverflow.com/questions/310946/how-can-i-send-mail-from-an-iphone-application this question."
        let toRecipents = ["foo@bar.com"]
        ms?.send(title, messageBody: messageBody, toRecipents: toRecipents)
    }
    

提交回复
热议问题