iOS Programming · · 4 min read

iOS Programming 101: How To Create Email with Attachment

iOS Programming 101: How To Create Email with Attachment

A year ago, we wrote a short tutorial to show you how to send email using MessageUI framework. Some asked how to attach a photo, PDF document or Powerpoint in the email. Instead of replying every email individually, we think it’s better to write another short how-to tutorial.

The MessageUI framework has made it really easy to send email in your apps. If you’ve read the official document of MessageUI framework, you know the MFMailComposeViewController class already provides a method called “addAttachmentData:” to add any types of files as an attachment. In this short tutorial, like other articles of our iOS Programming 101 series, we’ll write a simple app and demonstrate the usage of the method.

Email Attachment Featured

A Glance at the Demo App

As the primary focus is to demonstrate the attachment usage, we keep the demo app very simple. The app simply displays a list of files in a plain table view. We’ll populate the table with various types of files including image in both PNG and JPEG format, Microsoft Word document, Powerpoint, PDF document and HTML file. Whenever users tap on any of the file, the app automatically creates an email with the selected file as an attachment.

Email Attachment Demo App

Demo App for email attachment

Start with the Xcode Project Template

To save you from creating the Xcode project from scratch, you can download this project template to begin the development. The project template comes with:

  • A pre-built storyboard with a table view controller for displaying the list of files
  • An AttachmentTableViewController class
  • A set of files that are used as attachment
  • A set of free icons from Pixeden
Email Attachment Demo App Template

Xcode Project Template with a pre-built Storyboard

After downloading and extracting the zipped file, you can compile and run the project. The demo app should display a list of files in the main view. Now, we’ll continue to implement the email function.

Creating Email using MessageUI Framework

First, add the import statement and implement the “MFMailComposeViewControllerDelegate” in “AttachmentTableViewController.m”:


@interface AttachmentTableViewController () 

Next, add the following code in the same file:

- (void)showEmail:(NSString*)file {

    NSString *emailTitle = @"Great Photo and Doc";
    NSString *messageBody = @"Hey, check this out!";
    NSArray *toRecipents = [NSArray arrayWithObject:@"[email protected]"];
    MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
    mc.mailComposeDelegate = self;
    [mc setSubject:emailTitle];
    [mc setMessageBody:messageBody isHTML:NO];
    [mc setToRecipients:toRecipents];
    // Determine the file name and extension
    NSArray *filepart = [file componentsSeparatedByString:@"."];
    NSString *filename = [filepart objectAtIndex:0];
    NSString *extension = [filepart objectAtIndex:1];
    // Get the resource path and read the file using NSData
    NSString *filePath = [[NSBundle mainBundle] pathForResource:filename ofType:extension];
    NSData *fileData = [NSData dataWithContentsOfFile:filePath];
    // Determine the MIME type
    NSString *mimeType;
    if ([extension isEqualToString:@"jpg"]) {
        mimeType = @"image/jpeg";
    } else if ([extension isEqualToString:@"png"]) {
        mimeType = @"image/png";
    } else if ([extension isEqualToString:@"doc"]) {
        mimeType = @"application/msword";
    } else if ([extension isEqualToString:@"ppt"]) {
        mimeType = @"application/";
    } else if ([extension isEqualToString:@"html"]) {
        mimeType = @"text/html";
    } else if ([extension isEqualToString:@"pdf"]) {
        mimeType = @"application/pdf";
    // Add attachment
    [mc addAttachmentData:fileData mimeType:mimeType fileName:filename];
    // Present mail view controller on screen
    [self presentViewController:mc animated:YES completion:NULL];

- (void) mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
    switch (result)
        case MFMailComposeResultCancelled:
            NSLog(@"Mail cancelled");
        case MFMailComposeResultSaved:
            NSLog(@"Mail saved");
        case MFMailComposeResultSent:
            NSLog(@"Mail sent");
        case MFMailComposeResultFailed:
            NSLog(@"Mail sent failure: %@", [error localizedDescription]);
    // Close the Mail Interface
    [self dismissViewControllerAnimated:YES completion:NULL];

We won’t go into the details of “didFinishWithResult:” method, which is a method of the MFMailComposeViewControllerDelegate protocol that have to be implemented. You can check out this tutorial for further explanation.

Okay, let’s go through the “showEmail” method. Line 3-5 of the above code define the email subject, message content and recipients. Line 7 creates the built-in MFMailComposeViewController, which provides the standard user interface for managing the editing and sending of an email message. We populate the fields of that view with initial values including the recipient email, subject and body text.

To add an attachment, all we have to do is to call up the “addAttachmentData” method of the MFMailComposeViewController.

[mc addAttachmentData:fileData mimeType:mimeType fileName:filename];

The method takes in three parameters:

  • the data to attach – this is the contents of a file that you want to include.
  • the MIME type – MIME stands for Multipurpose Internet Mail Extensions. In short, MIME is an Internet standard that defines the way for sending other kinds of information (e.g. graphic) in email. Here the MIME type specifies the type of data to attach. For instance, the MIME type of a PNG image is image/png. You can refer to full list of MIME types at
  • the file name – that’s the preferred file name to associate the attachment.

Apparently, line 13-36 of the above are used to determine the content of these parameters. We first determine the file path and create a NSData object for that file, followed by nailing down the MIME type. Lastly, we invoke the addAttachmentData method to attach the file.

We’re almost done. The last thing is changed the “didSelectRowAtIndexPath” method with the following code:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    NSString *selectedFile = [_files objectAtIndex:indexPath.row];
    [self showEmail:selectedFile];

Compile and Run the App

You’re good to go. Compile and run the app. Pick any files and you’ll have an email with the corresponding attachment.

Email Attachment App Deliverable

For your complete reference, you can download the full source from here. As always, leave us comment and share your thought about the tutorial. If you have any suggestion for the iOS Programming 101 series, feel free to let us know.

Read next