How to send email in Swift MFMailComposeViewController

Send Email In Swift 5.5 using MFMailComposeViewController

(Last Updated On: October 6, 2021)

There might be a time when you have to ask the user to send an email directly to you or other users. Like recently while developing the CryptoWatch App, I wanted a way to let users report any bugs they find in the app and send it directly to me. For that, I searched and found the functionality to send email in swift using MFMailComposeViewController.

Using MFMailComposeViewController class, you can integrate send email in swift. MFMailComposeViewController class lets you assign the Recipient’s Email Address, Add People in CC, Add People in BCC, set the subject and body of the email and many other features.

If you are also interested in integrating push notifications in your app, you might wanna read this: How To Integrate Push Notifications In Swift

The mail will be sent only once the user has tapped the send email button. You can not send mail directly, user action is required.

Now let’s see how it can be implemented through code.

import UIKit
//1
import MessageUI

class ViewController : UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    //MARK: Setup
    //2
    func sendEmail() {
        if MFMailComposeViewController.canSendMail() {
            //3
            let mailVC = MFMailComposeViewController()
            mailVC.mailComposeDelegate = self
            //4
            mailVC.setToRecipients(["primary@gmail.com"])
            mailVC.setCcRecipients(["cc@gmail.com"])
            mailVC.setBccRecipients(["bcc@gmail.com"])
            
            mailVC.setSubject("Subject Goes Here")
            mailVC.setMessageBody("<p>Add body content here if required.</p>", isHTML: true)

            self.present(mailVC, animated: true)
        } else {
            // if mail functionality not available. canSendMail() fails in simulator.
            print("Unable to open mail. Please reach out to us at primary@gmail.com")
            Toast.show(message: "Unable to open mail. Please reach out to us at primary@gmail.com")
        }
    }
    
    //MARK: IBActions
    
    @IBAction func reportBtnPressed(_ sender : Any) {
        sendEmail()
    }

}

//MARK: Mail Delegate 

extension ViewController : MFMailComposeViewControllerDelegate {
    func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
        controller.dismiss(animated: true)
    }
}
  1. We start by importing MessageUI for using MFMailComposeViewController.
  2. Create a sendEmail() function and check if user can send email or not. If it fails, handle the case in else statement. You should show an alert message to the user in this case to inform if about the alternate way to reach out.
  3. Create an object of the MFMailComposeViewController and set the delegate of the controller to self. You need mailComposeDelegate to access didFinishWith method to know that user has completed sending email and now you need to dismiss the mail controller. It does not dismisses itself automatically when the mail is sent, you will need to do it through the delegate method as we have done above.
  4. Set the receipient’s email address, cc, bcc, subject and message body. You dont need to set all these values, only use the ones you need.
  5. Once all set, present the controller.

NOTE: MFMailComposeViewController does not work in simulator. Use a real device to test it.

Now once you have implemented the send email functionality, this is how it should appear in your app:

A screenshot from the CryptoWatch app of MFMailComposeViewController

I hope you understood how to implement send email in swift using MFMailComposeViewController. If you have any queries, feel free to ask in the comments.

Leave a Comment