Sending Email with Image Attachments in Swift

Sending content from an iOS application to external sources like email is a common requirement. This quick post summarizes the steps to implement this feature. Aa an added twist, the project used for this technique post includes capturing an image from one of the app's UIViews.

Below is a video demo of the application we'll go over in this post:

Demonstration of iOS App Sending Email using Swift

Sending Email from within an app

The crux of the technique is using the iOS provided MFMailComposeViewController.  This handy class has a perfectly descriptive name.

To use this component, make sure to include the following import at the top of the file where it's referenced:

import MessageUI

Once the namespace is imported, create and configure a Compose ViewController by setting the properties of the email.

 1@IBAction func sendEmailTapped(_ sender: UIButton) {
 2    if let addr = emailAddress.text, !addr.isEmpty,
 3        let jpegData = designView.asJpeg,
 4        MFMailComposeViewController.canSendMail() {
 6        let mail = MFMailComposeViewController()
 8        mail.setToRecipients(["\(addr)"])
 9        mail.setSubject("Design attached")
10        mail.setMessageBody("Body goes here", isHTML: true)
11        mail.mailComposeDelegate = self
12        mail.addAttachmentData(jpegData, 
13                                mimeType: "image/jpeg", 
14                                fileName: "mydesign.jpeg")
16        present(mail, animated: true)
17    }
18    else {
19        print("Email cannot be sent")
20    }

Code Snippet that Sends an Email from Swift Code Once the inputs for the email are set, call the present() function to call up the iOS mail sheet (you can see it in the demo after the "email" button is tapped in the app.

In this sample app, an attachment is included with the email. Almost any type of data can be attached--just make sure to set the correct MIME type for the Data, so the sending and receiving e-mail client applications will know how to present a preview to the user, and decide what actions can be taken with the attachment once it's received.  In this demo, the attachment is a JPEG image file.

2                        mimeType: "image/jpeg", 
3                        fileName: "mydesign.jpeg")

A caveat to using the Compose ViewController is that the device must be able to send email. Typically this just means the user has configured at least one e-mail account, but make sure to trap the error and provide a useful error to a user. This example only uses the print() statement to send output to the debug log--but you should use an Alert() or other user-visible error report.

Note the delegate assignment in the above code snippet:

1    mail.mailComposeDelegate = self

Implement the MFMailComposeViewControllerDelegate to get feedback from iOS whether the email send operation succeeded or not.  This delegate method is a good place to provide feedback to the user.

Errors are provided in an error implementing the Error protocol, so be helpful to users and provide them feedback and a way to recover.

 1extension ViewController: 
 2      MFMailComposeViewControllerDelegate {
 3    func mailComposeController(_ controller:   
 4            MFMailComposeViewController, 
 5            didFinishWith result: MFMailComposeResult, 
 6            error: Error?) {
 8        if let _ = error {
 9            self.dismiss(animated: true, completion: nil)
10        }
11        switch result {
12            case .cancelled:
13                print("Cancelled")
14                break
15            case .sent:
16                print("Mail sent successfully")
17                break
18            case .failed:
19                print("Sending mail failed")
20                break
21            default:
22                break
23        }
24        controller.dismiss(animated: true, completion: nil)
25    }

Code Snippet of MFMailComposeViewControllerDelegate

 1extension ViewController: MFMailComposeViewControllerDelegate {
 2    func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
 3        if let _ = error {
 4            self.dismiss(animated: true, completion: nil)
 5        }
 6        switch result {
 7            case .cancelled:
 8                print("Cancelled")
 9                break
10            case .sent:
11                print("Mail sent successfully")
12                break
13            case .failed:
14                print("Sending mail failed")
15                break
16            default:
17                break
18        }
19        controller.dismiss(animated: true, completion: nil)
20    }

The demo video above actually illustrates two other techniques, covered in related posts:

Related Post: Drawing with Core Graphics using Swift

Related Post: Capture a UIView as a a JPEG image using Swift

Full Project Source Code

The source for this project is available in my GitHub repository:

Link to GitHub Repository