iOS Programming 101: How To Send Email in Your iPhone App

36 Flares 36 Flares ×

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.

SimpleEmail Tutorial Logo

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

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

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:

Assistant Editor Enabled

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

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

Add action method - showEmail

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

Added ShowEmail Action Method

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
    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];

    // 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 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

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

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

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
    NSArray *toRecipents = [NSArray arrayWithObject:@"[email protected]"];
   
    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

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.

You May Like These:

Get Free Chapters of Our AppCoda Book

Learn iOS 7 Programming from Scratch

The Learn iOS 7 Programming from Scratch is a 400-page eBook written for beginners with little or even no programming experience. It is based on the tutorials of our popular programming course. The book starts with the basics and walks you through the process to create iOS apps using iOS 7 SDK and Xcode 5. Want to learn more? Check it out here and get two free chapters.


Build Your Own Game and Monetize on the Side

Learn how to develop your first iOS game and make money on the side. The starter kit will come with full source code of a memory game for both iPhone and iPad, as well as, a complete guide to explain how the code works. Check out the starter kit to learn more.


  • arjun

    Please post new tutorials as soon as possible. they are really helpful. Hoping for the best.
    Thank you.

  • Raghavendra

    pls 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

    Great 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

    This was very helpful. Thanks for posting!

  • shivank

    Sir first i thanks to u!!
    Actually sir i want that from this tutorials i can send the message to anybody by just entering email

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

      Do 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

    no 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
  • http://www.facebook.com/sean.derning.5 Sean Derning

    Thanks 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.

  • Pingback: 第十六部分:如何在你的iPhone App中发送邮件 | EntLib.net 技术分享平台

  • Pingback: iOS Programming 101: How To Get the User Location in iPhone App | iptips - iphone / ipad / ios / android / mobile / tutorials

  • Pingback: iOS Programming 101: How To Get the User Location in iPhone App | t1u

  • nickykiet83

    I 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?

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

      Are you testing it using the iPhone Simulator? You won’t be able to send email using the simulator.

      • nickykiet83

        Ok Thanks! I’ve got it!

  • Coyote6

    Are 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

    @raghavendra, come on dude, dont be so desperate…dig around, read api docsand u be fine. Simon is not your private tutor.

  • Kristoffer B

    Nice and smooth did it in one minute. Thanks a lot for this!

  • Jim

    Excellent 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

    Never mind. The mail account settings were wrong. Thanks for the tutorial.

  • MillsapsFinest
    • Adarsh Rai

      Apple 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.

  • Pingback: Curso de programación iOS para principiantes | CyberHades

  • zil

    When 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 0×208418 0×208648 0×208882 0x157a25 0x157dbf 0x157f55 0x160f67 0×2935 0x1247b7 0x124da7 0x125fab 0×137315 0x13824b 0x129cf8 0x1f34df9 0x1f34ad0 0x1c70bf5 0x1c70962 0x1ca1bb6 0x1ca0f44 0x1ca0e1b 0x1257da 0x12765c 0x266d 0×2595 0×1)

    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

    Thanks 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

      The iPhone simulator doesn’t send email,but real device will work and send the email.

  • Daniel

    Hello. Great Tutorial, thank you. I have got a question, how can I custom the view’s transition?

  • Seven

    hi 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

      There is no email account configured on your iphone. Try

      if (mc != nil) {

      [self presentViewController:mc animated:YES completion:NULL];

      }

  • tcm692

    How 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

    Thanks 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

  • sree

    thanks for the tutorial

  • Jimmy

    I 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

    It is very good tutorial. if u have a time, pls post the about how to send sms.

  • osropa

    Great tutorial, thank you so much for it. Now my app can send mail with the data collected during its execution.

  • Trina

    Fantastic tutorial! This helped me so so much as I’ve only been using xcode for a little while. Thanks so much.

  • Souvick

    How to add video attachment?

  • Me

    Great Tutorial! But on line ‘mc.mailComposeDelegate = self;’ I get the warning: Assigning to ‘id’ from incompatible type ‘ImpressumViewController *const __strong’. Any ideas?

    • go2014

      any comments on this one folks? i have the similar issue

      • max

        You forgot to add to your header file!

  • LittlePeculiar

    I’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

    thanks

  • Ravi

    How to add multiple email address.. actually its not working the arraylist

  • elturner2000

    WOW – that was excellent. Thanks Guys!

  • Arvind Kumar Barnwal

    Mail application is not sending any mail….I need to send the mail on anyt email id entered by the user…

  • NK

    not having email in my inbox after send from simulator ???

  • Jeffrey Neo

    Add condition
    if ([MFMailComposeViewController canSendMail])
    before calling
    [self presentViewController:mc animated:YES completion:NULL];

  • Salman Khan

    its awsum

36 Flares Twitter 9 Facebook 24 Google+ 2 LinkedIn 1 36 Flares ×