Home » Apps » Sending Mail from an app using Swift from the UIControllerClass with iOS 8

Sending Mail from an app using Swift from the UIControllerClass with iOS 8

 

  1. Import UIKit and MessageUI in your Swift code

import UIKit

import MessageUI

 

  1. Add MFMailComposeViewControllerDelegate in your class definition

class Scene2ViewController: UIViewController, MFMailComposeViewControllerDelegate {

 

  1. Create a button to send mail, with TouchUpInside event sent to a function (TapSendmail)

 

  1. Write the TapSendmail function

@IBAction func TapSendmail(sender: AnyObject) {

let mailComposeViewController = configuredMailComposeViewController()

if MFMailComposeViewController.canSendMail() {

self.presentViewController(mailComposeViewController, animated: true, completion: nil)

} else {

self.showSendMailErrorAlert()

}

}

 

 

5. Add a configuredMailComposeViewController function, MFMailComposeViewControllerDelegate and error alert function; Set subject and mail body

func configuredMailComposeViewController() -> MFMailComposeViewController {

let mailComposerVC = MFMailComposeViewController()

mailComposerVC.mailComposeDelegate = self

 

mailComposerVC.setSubject(“data from App“)

var MailBody=”mail body

mailComposerVC.setMessageBody(MailBody, isHTML: false)

return mailComposerVC

}

 

func showSendMailErrorAlert() {

let sendMailErrorAlert = UIAlertView(title: “Could Not Send Email”, message: “Your device could not send e-mail. Please check configuration.”, delegate: self, cancelButtonTitle: “OK“)

sendMailErrorAlert.show()

}

 

func mailComposeController(controller: MFMailComposeViewController!, didFinishWithResult result: MFMailComposeResult, error: NSError!) {

controller.dismissViewControllerAnimated(true, completion: nil)

}

Leave a Reply