MFMailComposeViewController – sending emails from an iOS app

MFMailComposeViewController

MFMailComposeViewController provides an easy way to present a view controller, that allows to write, edit and send an email. It’s presented modally, so the context of the app won’t be left.

Hint: This post is using Swift 4 and iOS 9


Creating and presenting MFMailComposeViewController

It’s very easy. First, you have to import the MessageUI framework:

Then, you just have to create an instance of MFMailComposeViewController, set some parameters and present it. The rest is taken care of by that controller.

The static  canSendMail() method of MFMailComposeViewController is called to check if an email account is set up on the device. Note that this doesn’t include email accounts of third party apps like Gmail or Outlook.

It’s important to set the MFMailComposeViewControllerDelegate as well to handle the dismissal of the controller. There’s just one method to implement:

It’s called when the user dismisses the controller, either by sending the email or canceling the action. Either way, you have to dismiss the controller manually.

Setting the recipients, subject and message body are the most obvious parameters you can set. However, it’s also possible to set CC and BCC recipients:

It’s also possible to set an attachment:

In this example, an image called Test.jpeg from the asset bundle gets attached to the email.

Open Mail app

There’s also another way to sent emails from an iOS app. Instead of presenting the MFMailComposeViewController, you can open the mail app:

There is also the possibility to use the UIActivityViewController. However, then the user can choose from different types of channels, not only email.

References

Title image: @ Andrey Bayda / shutterstock.com