How to Make Your iPhone App Send Email with Attachments

Matthew Campbell, July 14th, 2009

mailbox.jpgWould you like your users to be able to send email with attachments from your app?

In iPhone OS 3.0 you can easily send pictures and voice recordings from your app in an email. In fact, now your emails can be easily formated using HTML and once the user has finished the email control returns back to your app. Pretty nifty!

Add the Framework
Add the “MessageUI” framework to your projects “Frameworks” group folder in XCode

NOTE: if you are having trouble locating the framework follow this path: Macintosh HD>Developer>Platforms>iPhoneOS.platform>developer>SDKs>
iPhoneOS3.0.sdk>System>Library>Frameworks

TIP: add a shortcut to the Frameworks folder to your Finder sidebar since you will need it often

Choose a Delegate
Choose one class to act as the MFMailComposeViewControllerDelegate

Import Message Framework
Import “MessageUI.h” and “MFMailComposeViewController.h” to the header file of the delegate

Make your Delegate
Indicate that your delegate class is the delegate by including this <MFMailComposeViewControllerDelegate> in the @interface declaration

Implement the Delegate Method
Implement the “didFinishWithResult” MFMailComposeViewControllerDelegate delegate method and make sure to return control to the program by sending the dismissModalViewControllerAnimated message.

Start Composing the Email Use an instance of MFMailComposeViewController to start composing the email and adding the attachments. This controller gives control to the user so s/he can decide to send or cancel the message.

Now if you test this out you should be able to send an email from your app.

Here is how I did the whole thing on video:

http://screencast.com/t/uz7OV6XW

A Few Notes

So, as you can see it is pretty simple to compose an email in iPhone OS 3.0. You can use HTML tags to format the email; just insert the tags into your NSString that you send with the setMessageBody message. Attachments simply use the addAttachmentData method.

Note: this example assumes that you and your users are all up to date with iPhone OS 3.0. To see an example of how to check for this and accommodate your users who are not up to date go to the Apple Developer website and look over the source code for the project “MailComposer”.