iOS Programming 101: How To Create Email with Attachment

42 Flares 42 Flares ×

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”:

1
2
3
#import <MessageUI/MessageUI.h>

@interface AttachmentTableViewController () <MFMailComposeViewControllerDelegate>

Next, add the following code in the same file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
- (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/vnd.ms-powerpoint";
    } 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");
            break;
        case MFMailComposeResultSaved:
            NSLog(@"Mail saved");
            break;
        case MFMailComposeResultSent:
            NSLog(@"Mail sent");
            break;
        case MFMailComposeResultFailed:
            NSLog(@"Mail sent failure: %@", [error localizedDescription]);
            break;
        default:
            break;
    }
   
    // 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.

1
[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 http://www.iana.org/assignments/media-types/.
  • 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:

1
2
3
4
5
- (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.

You May Like These:

Get Free Chapters of Our Swift Book

Beginning iOS 8 Programming with SwiftIf you want to create an app but don't know where to begin, this book covers the whole aspect of Swift programming and iOS 8 development and shows you every step from an idea to a real app on App Store. This book features a lot of hands-on exercises and projects. You will first create a simple app, then prototype an app idea, and later add some features to it in each chapter, until a real app is built. Want to learn more? Check it out here and get three free chapters.


  • iOSWarriors

    I want your “no more complaint” image! haha

    • http://www.simonblog.com Simon Ng

      Hey, you can find the image in the Xcode project.

      • abdul rahman

        how you can find the two picker views in same pages..?

  • Pingback: iOS Programming Tutorial: Create Email with Attachment Using … | MUSCLE CODER()

  • iMac

    HI Simon, how can we create word doc or pdf file in our application and send it as a attachment.

  • John Malkovich

    Hi Simon, same question as iMac but more general- how can we create a file in our application and send it as an attachment? Are there only certain formats that it can be saved in?

  • sisocial

    Great tutorial but getting a problem in iOS 5 – it crashes the Code. (so can test on the 3GS iPhone…) iOS6 works… in the simulator… (the app runs etc…)

    I changed the Deployment Target to 5.0, and ran the iPhone 5 simulator. Same problem with the Email attachment tutorial – any help would be great… Details below…

    Part of the error log:
    [UITableView dequeueReusableCellWithIdentifier:forIndexPath:]: unrecognized

    Part of this file page: AttachmentTableViewController.m

    – (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @”Cell”;
    AttachmentTableViewCell *cell = (AttachmentTableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    Full error log
    2013-09-07 16:07:17.779 SMS[1238:c07] -[UITableView dequeueReusableCellWithIdentifier:forIndexPath:]: unrecognized selector sent to instance 0x80f1800
    2013-09-07 16:07:17.780 SMS[1238:c07] *** Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘-[UITableView dequeueReusableCellWithIdentifier:forIndexPath:]: unrecognized selector sent to instance 0x80f1800′
    *** First throw call stack:
    (0x15f4052 0xf70d0a 0x15f5ced 0x155af00 0x155ace2 0x2e09 0x179e0f 0x17a589 0x165dfd 0x174851 0x11f301 0x15f5e72 0x49b492d 0x49be827 0x4944fa7 0x4946ea6 0x49d230c 0xdf4c6 0xdfbd6 0xee743 0xef1f8 0xe2aa9 0x1787fa9 0x15c81c5 0x152d022 0x152b90a 0x152adb4 0x152accb 0xdf2a7 0xe0a9b 0x27bd 0x26e5)
    terminate called throwing an exception(lldb)

  • sisocial

    Sorry… looking at the SMS version as well – both crashes in iOS 5 for me…

  • Srinivas

    Hi Simon,

    I am trying to create a Printer APP, Which will send all the photos and documents to cloud server from my app. My requirement is how to make my app visible to other apps like photos, email, adobe reader to print the documents or photos. For example, if i click print icon from photo or email app i should see my app which will take the email or pic to send it to cloud server for printing. My app will act as printer app but it wont send the documents to network printer instead to a cloud server where it will have direct connection to print servers.

  • http://GitHub.com/cc941201 CC-Dog

    NSArray *filepart = [file componentsSeparatedByString:@”.”];
    NSString *filename = [filepart objectAtIndex:0];
    NSString *extension = [filepart objectAtIndex:1];

    This could get wrong result if there is “.” in filename.

  • Sudheer

    hi simon , i want attach a video can you address the mime type and limitation of size of the video.

  • Anna Yelizarova

    What if I want to attach a CSV file to the email for the recipient to be able to open it on excel? From what I read online there isn’t a MIME type for CSV and the default is text/plain text. Will that allow to open it in excel?

  • Dhvl Golakiya

    How can i put browse option to select files from device?

  • Adam

    Would prefer an tutorial how to attach a photo form camera or camera roll to the email…

  • Pingback: How To Create Email with Attachment(.pdf , .html, .png) Files | kamanijaydeep()

42 Flares Twitter 8 Facebook 33 Google+ 1 LinkedIn 0 42 Flares ×