Member-only story
Email Composer on iOS

It’s often needed to add email sending functionality to iOS apps. In order to do that, there is a specific view controller to use called MFMailComposeViewController. When presented, it brings up the familiar system controller to compose and send an email. It’s possible to provide default values before its presentation, such as the subject or the recipients, even a predefined email body. In overall, sending email is a quite standard procedure, and this post will take you through the integration steps of the email composer on iOS.
Initial steps
The first step towards presenting the system controller to compose and send emails, is to import a specific framework that will make the MFMailComposeViewController class available. That is the MessageUI:
import MessageUI
After that, it’s mandatory to check if the device can actually send emails! If we skip that and the device is unable to send emails for some reason, then the app will just crash; that’s something we don’t want to happen by any means.
Doing that check is easy, and all it takes is to call a class method in MFMailComposeViewController:
func composeEmail() {
guard MFMailComposeViewController.canSendMail() else { let alert = UIAlertController(title: "Send email", message: "This device cannot send emails.", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
return
}
}
Suppose that the composeEmail()
method is the place to initialize an MFMailComposeViewController instance and present it modally in the app. See that it starts by calling the canSendMail()
method and verifying that the device is capable of sending emails. If not, then in this example we just present an alert reporting that, and return from the method. In real world, do whatever is appropriate to your app in order to handle this case.
Initializing and configuring a mail composer instance
The bare minimum implementation required in order to create and configure an MFMailComposeViewController instance is parted by the following two…