iOS - Add multiple attachments to an email (Swift 2.3)

Recently I was working on my Simple Signature iOS app. This app allows you to make and save multiple signatures. You can save and view signature creation as an image or a video. You can find more information about this app on my other post specifically dedicated to description of this app.

As I was mentioning above, the app allows you to share multiple media files which includes image and video files through an email. Today I will teach you how you can share not only media but any local items through an email through an iOS apps.

Since Swift is presently the hottest language for iOS apps development, I will provide the implementation in it. Should you need a code in Objective-C syntax, that really shouldn't be hard to achieve

func shareEmailWithPathsCollection(filePaths: [String]) {
    if (MFMailComposeViewController.canSendMail() == true) {
        let mailComposeViewController = MFMailComposeViewController();
        mailComposeViewController.setSubject("Simple Signature App")
        mailComposeViewController.setMessageBody("Sharing signatures through an email. You can download this amazing app from app store totally free of cost!", isHTML: false)
        for filePathToShare in filePaths {
            let fileData = NSData(contentsOfFile: filePathToShare)
            var fileMIMEType = "image/png"
            let filePathToShareURL = NSURL(string: filePathToShare)
            if (filePathToShareURL?.URLByDeletingPathExtension?.lastPathComponent == "mp4") {
                fileMIMEType = "video/mp4";
            mailComposeViewController.addAttachmentData(fileData!, mimeType: fileMIMEType, fileName: (filePathToShareURL?.lastPathComponent)!)
        self.presentViewController(mailComposeViewController, animated: true, completion: nil)
    } else {
        // User can't share the files since email account is not yet setup on the device. 
        // Show suitable error message

In the above code, filePaths is a collection of full local file path. These files are stored in the documents directory. We will take files from specified directory and convert to NSData and add them as an attachment to an email.

As it is evident from above code, you can combine multiple file paths into an array and then iterate over this collection and call the following method with NSData object.

mailComposeViewController.addAttachmentData(fileData!, mimeType: fileMIMEType, fileName: (filePathToShareURL?.lastPathComponent)!)

Hope this post will help you. If you have any further questions, please do not hesitate to contact me