Swift: Compose Email (MFMailComposeViewController) as an Extension to UIViewController

extension to compose email swiftUPDATED for Swift 3…

I’m a fan of extensions – but hopefully only when it makes sense. I wanted to write an extension on UIViewController to allow me to send email from any subclass…





Swift: Compose Email (MFMailComposeViewController) as an Extension to UIViewController


  1. Add a new file (⌘-N) and select a iOS>Source>Swift file (name it whatever you want)
  2. Add the code below as it’s list (full code at the bottom)
  3. Call from your class to create and present the composition controller

Start by declaring the extension on UIView Controller and adding the method that will create the composition view controller: MFMailComposeViewController

NOTE: I’m not closing the extension (with the } ) because more code will be added.

The method takes option recipients of strings, a subject, body, optional isHTML (with default of false) and an optional array of images to attach.

It creates the MFMailComposeViewController, sets the values passed in, attaches the images and returns it. You could change the attachments to be data instances or something if you’d rather.

It doesn’t present the MFMailComposeViewController in case you want to do something else with it like adding cc or bcc emails, etc.

The second function presents the MFMailComposeViewController. First it checks to make sure the device can send email.

The third function handles the return. It either dismisses the controller and it’s done or it displays an alert that there was an error.

That’s it!

I call it like this:

I have one recipient (me), a subject and body (no attachments in this case). I use a method to get the version text (included in the full code below) and the version of iOS so the email (for support) tells me what they’re running. They could delete that, but…

Here’s the full code: