Here comes another tutorial for our iOS Programming 101 series. Last time, we show you how to hide tab bar in navigation interface. In this tutorial, we’ll show you how easy you can let user send email in your app.
The iOS SDK has made it really easy to send email using the built-in APIs. With a few line of codes, you can launch the same email interface as the stock Mail app that lets you compose an email. In this tutorial, we’ll build a very simple app to show you how to send both plain text and HTML email using the iOS SDK.
Create a Simple View App with a Button
First, create a simple app with a view controller and a button. If you have no idea how to do it, you better revisit the Hello World tutorial. Let’s name the project as SimpleEmail. If you’ve successfully created your project, add a “Contact Us” button in the view.

SimpleEmail App with Contact Us Button
What the app does is that it’ll show up the email interface when user taps the “Contact Us” button.
Connecting the Contact Us Button with Action
In the past tutorials, we used to add the action method manually in the header file of the view controller file. We then link the button and the action method in the Interface Builder.
This time, let us show you another way to add the action method (make sure you use Xcode 4.3 or up).
In the Project Navigator, select the “SimpleEmailViewController.xib” file to go to the Interface Builder. Switch to the Assistant Editor and hide the Utility area:

Show Assistant Editor and Hide Utility Area
Once you make the change, your Xcode environment should look like the below screen. The interface and its corresponding code are now shown side by side:

User Interface and Source Code Displayed Side by Side
Now we’ll add an action method for the “Contact Us” button. Press and hold the control key, click the “Contact Us” button and drag it towards the “SimpleEmailViewController.h”. As you place the pointer between the “@interface” and “@end” keywords, you should see a prompt that allows you to insert outlet and action.

Prompt to Let You Insert Outlet and Action
Release the mouse button and Xcode prompts you to add the outlet/action. As we’re going to add the action method, select “Action” for “Connection” and name the method as “showEmail”. You can keep the event as “Touch Up Inside”. The “showEmail” method will be invoked when users lift up the finger inside the button.

Add action method – showEmail
Once you confirm the change by clicking the “Connect” button, Xcode automatically adds the method declaration in the SimpleEmailViewController.h.

Xcode Automatically Inserts the showEmail Method
Implementing the Email Interface
Next, import the “MessageUI.h” and implement the “MFMailComposeViewControllerDelegate” delegate in SimpleEmailViewController.h.
1 2 3 4 5 6 7 |
#import <UIKit/UIKit.h> #import <MessageUI/MessageUI.h> @interface SimpleEmailViewController : UIViewController <MFMailComposeViewControllerDelegate> // Add the delegate - (IBAction)showEmail:(id)sender; @end |
Select the “SimpleEmailViewController.m” and we’ll implement the “showEmail” method and MFMailComposeViewControllerDelegate. Add the following code in the implementation 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 |
- (IBAction)showEmail:(id)sender { // Email Subject NSString *emailTitle = @"Test Email"; // Email Content NSString *messageBody = @"iOS programming is so fun!"; // To address MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init]; mc.mailComposeDelegate = self; [mc setSubject:emailTitle]; [mc setMessageBody:messageBody isHTML:NO]; [mc setToRecipients:toRecipents]; // 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]; } |
Line 3-7 of the above code define the email subject, message content and recipients. Line 9-13 creates the built-in MFMailComposeViewController. The MFMailComposeViewController class provides a standard interface that manages the editing and sending an email message. You can use this view controller to display a standard email view inside your application. We populate the fields of that view with initial values including the recipient email, subject and body text.
Line 13 of the code invokes the presentViewController to display the mail interface on screen.
The “didFinishWithResult:” is a method of the MFMailComposeViewControllerDelegate protocol. This method will be automatically called when the mail interface is closed (e.g. user cancels the operation). The result parameter tells you the result code when the mail composition interface is dismissed. For the sake of simplicity, we simply log the status in this example. In real world application, you should provide special handling for the result code (e.g. display an alert when the app fails to send the email).
Finally, line 41 dismisses the mail composition interface.
Adding the MessageUI Framework
However, this is not done yet. If you try to compile the app, you’ll end up with the below compilation error:

SimpleEmail App Compilation Error
The problem is that Xcode has no idea about what the “MFMailComposeViewController” is. Though “MFMailComposeViewController” is a built-in controller in iOS SDK, it’s developers’ responsibility to embed the necessary framework in your project. When the Xcode project is first created, it only comes with three core frameworks including UIKit, Foundation and CoreGraphics. The “MFMailComposeViewController” class is included in the MessageUI framework that you have to add manually.
To fix the error, we have to embed the framework in the project. In the Project Navigator, select “SimpleEmail” project and then select the “SimpleEmail” target under “Targets”. Click “Build Phases” at the top of the project editor. Then open the Link Binary With Libraries section.

Add Framework in Build Phases
Next, click the “+” button and select the “MessageUI.framework”. After you click the “Add” button, Xcode will include the MessageUI framework in the project.

Add MessageUI Framework in Your Xcode Project
Now the error should have been fixed. Run your app and see how it works. Tapping the “Contact Us” button will show you the “Compose Email” interface with pre-populated content.

SimpleEmail App
Composing HTML Email
The SimpleEmail app now only supports plain text email. You can easily enable the support of HTML email by changing the “isHTML” parameter in “setMessageBody” method from “N” to “Y”. Try to change the code in “showEmail” method to the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
- (IBAction)showEmail:(id)sender { // Email Subject NSString *emailTitle = @"Test Email"; // Email Content NSString *messageBody = @"<h1>Learning iOS Programming!</h1>"; // Change the message body to HTML // To address MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init]; mc.mailComposeDelegate = self; [mc setSubject:emailTitle]; [mc setMessageBody:messageBody isHTML:YES]; [mc setToRecipients:toRecipents]; // Present mail view controller on screen [self presentViewController:mc animated:YES completion:NULL]; } |
Compile and run your app again. With just a simple change, the SimpleEmail app now offers HTML support!

SimpleEmail App with HTML Support
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.
Comments
arjun
AuthorPlease post new tutorials as soon as possible. they are really helpful. Hoping for the best.
Thank you.
Raghavendra
Authorpls pls pls pls pls pls pls pls help me simon ….. me using x code 3.2.4 to develop iphone applications……. i am facing very difficulty in dveloping customised table view different images in each row specially in making outlet connections…… u pls post customised table view and each row’s detailed view step by step explaination . pls develop it in x code 3.2.4….. pls post it tomorrow… bcos if won’t show customised table view… i will be kicked from job pls pls pls pls pls pls pls pls pls pls pls pls pls pls pls pls pls pls pls pls pls pls pls pls pls pls pls pls plssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss
steveald
AuthorGreat tutorial!! Could you expand a bit on it by showing what code to enter in the emailTitle and messageBody strings so they take values from a picker array? I have a screen that allows the user to select a term from a picker wheel and it displays the term’s definition. I would like them to be able to then email that term and definition to someone else.
shawc
AuthorThis was very helpful. Thanks for posting!
shivank
AuthorSir first i thanks to u!!
Actually sir i want that from this tutorials i can send the message to anybody by just entering email
Simon Ng
AuthorDo you mean you want to empty the “To” field. You can simply remove these two lines:
NSArray *toRecipents = [NSArray arrayWithObject:@”[email protected]”];
[mc setToRecipients:toRecipents];
shivank
Authorno sir i can’t enable to send the message on click the send button and i just want to remove the cc and bcc button
Muddu Patil
AuthorI’m unable to receive mail i gave my email id instead of [email protected]
Sean Derning
AuthorThanks for the post. Works on 4 and 4s, but crashes on 3gs with error
“Application tried to present a nil modal view controller on target”
Any ideas would be appreciated.
nickykiet83
AuthorI did exactly as your tut, I saw NSLOG appeared “Mail sent”. After this, however, I checked my email and didn’t get it! Please tell my why?
Simon Ng
AuthorAre you testing it using the iPhone Simulator? You won’t be able to send email using the simulator.
nickykiet83
AuthorOk Thanks! I’ve got it!
Coyote6
AuthorAre the log messages in the mailComposeController method, a requirement from Apple, can those just be skipped in an actual app, or is it just a good practice to add them? Or was that just for this tutorial to show the results? Thanks.
Great tutorials by the way.
Walid
Author@raghavendra, come on dude, dont be so desperate…dig around, read api docsand u be fine. Simon is not your private tutor.
Kristoffer B
AuthorNice and smooth did it in one minute. Thanks a lot for this!
Jim
AuthorExcellent tutorial. I implemented it in my app in a matter of minutes. The only problem I see is that it does not email the message. I am using the app on an iPad. It populates the body with “Sent from my iPad. and the NSLog output occurs. However, there is no indication of any sent email, or received email.
Thanks! You saved me a lot of research. I hope you can help with this problem.
Jim
AuthorNever mind. The mail account settings were wrong. Thanks for the tutorial.
MillsapsFinest
AuthorHow would you do this in the background? like send an email without the user going to this, example: enter name —> hit send —> name goes to [email protected]
Adarsh Rai
AuthorApple does not allow to send email or message without user intervention. You just can fill all the required fields but you can not send it, programmatically.
zil
AuthorWhen i run the app after adding MessageUI.framework it give the exception and terminate the app. The exception is :
2012-12-29 12:42:43.841 SimpleEmail[1455:c07] *** Terminating app due to uncaught exception ‘NSUnknownKeyException’, reason: ‘[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key showEmail.’
*** First throw call stack:
(0x1cfb012 0x11dfe7e 0x1d83fb1 0xc8c711 0xc0dec8 0xc0d9b7 0xc38428 0x3440cc 0x11f3663 0x1cf645a 0x342bcf 0x207e37 0x208418 0x208648 0x208882 0x157a25 0x157dbf 0x157f55 0x160f67 0x2935 0x1247b7 0x124da7 0x125fab 0x137315 0x13824b 0x129cf8 0x1f34df9 0x1f34ad0 0x1c70bf5 0x1c70962 0x1ca1bb6 0x1ca0f44 0x1ca0e1b 0x1257da 0x12765c 0x266d 0x2595 0x1)
libc++abi.dylib: terminate called throwing an exception
(lldb)
Please give me the solution for that as early as possible.
The tutorial is very good. Thanks for that.
Kirti Avaiya
AuthorThanks for such easier tutorial, but I have some problem encountered in the mail sending , after clicking on the send button in the simulator , output window shows the mail sent message but in actually i dont get any test mail from my simulator .
Thank you and show me some help
Kirti Avaiya
AuthorThe iPhone simulator doesn’t send email,but real device will work and send the email.
Daniel
AuthorHello. Great Tutorial, thank you. I have got a question, how can I custom the view’s transition?
Seven
Authorhi thanks !
but i have proplem when run my app on iphone 3Gs , ios 5.1.1 =>> crash
“* Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘Application tried to present a nil modal view controller on target .”
Pls help me !
tanzelwurm
AuthorThere is no email account configured on your iphone. Try
if (mc != nil) {
[self presentViewController:mc animated:YES completion:NULL];
}
tcm692
AuthorHow could you incorporate this into a tab view? For example, I have 2 tabs and on the 2nd tab I want the users to be able to send an email…is that done with a segue to a view controller page? Or…If I created the sending email app as above, what would I add to my tab bar app from the email app?
mike
AuthorThanks for the tutorial, I’ve a small problem with the email message screen.
When I click the button the email screen appears with the options to send the message or cancel.
If I click the cancel button nothing happens – I just stay stuck on the email screen without the option to go back, please can you help
Jeria
AuthorMFMailComposeViewController has a delegate method called mailComposeController:didFinishWithResult:error. You can in that method dismiss the email dialog with [self dismissViewControllerAnimated:YES completion:nil];
sree
Authorthanks for the tutorial
Jimmy
AuthorI want to send a message, I get the info from the address book, and I get the name and email address to send the mail to, and I compose a predefined email, but in the end, I want to add my name (the phone owners name) like
“hello Mark
bla bla bla
bla bla bla
bla bla bla
bla bla bla
Thanks,
Jimmy”
Where Mark is the recipient, and I can get this info, how do I get the “Jimmy” name, that actually is my name (the owners phone)
Htun Lin Aung
AuthorIt is very good tutorial. if u have a time, pls post the about how to send sms.
Simon Ng
AuthorHere is the tutorial: http://104.131.120.244/ios-programming-send-sms-text-message/
osropa
AuthorGreat tutorial, thank you so much for it. Now my app can send mail with the data collected during its execution.
Trina
AuthorFantastic tutorial! This helped me so so much as I’ve only been using xcode for a little while. Thanks so much.
Souvick
AuthorHow to add video attachment?
Me
AuthorGreat Tutorial! But on line ‘mc.mailComposeDelegate = self;’ I get the warning: Assigning to ‘id’ from incompatible type ‘ImpressumViewController *const __strong’. Any ideas?
go2014
Authorany comments on this one folks? i have the similar issue
max
AuthorYou forgot to add to your header file!
LittlePeculiar
AuthorI’m using a custom navigation bar that I set up in AppDelegate, as per your tutorial in “Custom Navigation Bar and Status Bar” in iOS7. I’m having a problem when presenting MFMailComposeViewConroller running on 4-inch 64-bit. It seems that the background image I am using is the wrong size or it looks displaced. It works perfectly on 4-inch as well as 3.5-inch. Also all my other views are appearing as they should be. I’m having another issue where the status bar text goes back to black only in mail. Maybe these issues are related. It actually sounds like an Apple bug. Any help is truly appreciated.
And just so you know, I am incredibly grateful for all the time and effort you put into your tutorials. This site has become invaluable to me.
Thanks so much
Jitender Singh
Authorthanks
Ravi
AuthorHow to add multiple email address.. actually its not working the arraylist
elturner2000
AuthorWOW – that was excellent. Thanks Guys!
Arvind Kumar Barnwal
AuthorMail application is not sending any mail….I need to send the mail on anyt email id entered by the user…
NK
Authornot having email in my inbox after send from simulator ???
Jitendra Singh
AuthorNSArray *toRecipents = [NSArray arrayWithObject:@”[email protected]”]; Comment this line or don’t write it in code
Jeffrey Neo
AuthorAdd condition
if ([MFMailComposeViewController canSendMail])
before calling
[self presentViewController:mc animated:YES completion:NULL];
Salman Khan
Authorits awsum
Milos
AuthorWOW, Thanks for great tutorial
faysalsabbagh
AuthorI have this in the compilers timed out waiting for fence barrier from com.apple.MailCompositionService
how can I fix this error so I can send the email?
faysalsabbagh
Authorplease help with this error
timed out waiting for fence barrier from com.apple.MailCompositionService
Muhammad Bilal
Authorcan we change background of mail composer ?
Anne B Perrault
AuthorThanks
bhavya
Authori am getting an erroe when i run the app with above code
viewServiceDidTerminateWithError: Error Domain=_UIViewServiceInterfaceErrorDomain Code=3 “(null)”
Jitendra Singh
AuthorTry in device not in simulator
bhavya
Authorhiii i am getting mail sent in console but there is no mail in my inbox.
timbojill
AuthorIs there an updated version made with swift 2 and xcode 7 I can download ?
Simon Ng
AuthorYou may check out our Intermediate Swift book. It is now updated for Swift 3 and Xcode 8.
https://www.appcoda.com/intermediate-swift-programming-book/
Rajkar
Author[self presentViewController:mc animated:YES completion:NULL];
I’m getting the exception with this line can any one help me to resolve this
.