iOS

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


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

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.

Select the “SimpleEmailViewController.m” and we’ll implement the “showEmail” method and MFMailComposeViewControllerDelegate. Add the following code in the implementation file:

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:

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.

iOS
How to Beta Test Your App Using TestFlight
Tutorial
Integrating Mixpanel Analytics into iOS App for Tracking User Events
iOS
An Introduction to Stack Views in iOS 9 and Xcode 7
  • arjun

    arjunarjun

    Author Reply

    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

    stevealdsteveald

    Author Reply

    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

    shawcshawc

    Author Reply

    This was very helpful. Thanks for posting!


  • shivank

    shivankshivank

    Author Reply

    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


    • Simon Ng

      Simon NgSimon Ng

      Author Reply

      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

    shivankshivank

    Author Reply

    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

    I’m unable to receive mail i gave my email id instead of [email protected]


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


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


    • Simon Ng

      Simon NgSimon Ng

      Author Reply

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


  • Coyote6

    Coyote6Coyote6

    Author Reply

    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

    WalidWalid

    Author Reply

    @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

    JimJim

    Author Reply

    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

    JimJim

    Author Reply

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


  • MillsapsFinest

    How 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

      Adarsh RaiAdarsh Rai

      Author Reply

      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.


  • zil

    zilzil

    Author Reply

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

    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

    DanielDaniel

    Author Reply

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


  • Seven

    SevenSeven

    Author Reply

    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

      tanzelwurmtanzelwurm

      Author Reply

      There is no email account configured on your iphone. Try

      if (mc != nil) {

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

      }


  • tcm692

    tcm692tcm692

    Author Reply

    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

    mikemike

    Author Reply

    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


    • Jeria

      JeriaJeria

      Author Reply

      MFMailComposeViewController has a delegate method called mailComposeController:didFinishWithResult:error. You can in that method dismiss the email dialog with [self dismissViewControllerAnimated:YES completion:nil];


  • sree

    sreesree

    Author Reply

    thanks for the tutorial


  • Jimmy

    JimmyJimmy

    Author Reply

    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

    osropaosropa

    Author Reply

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


  • Trina

    TrinaTrina

    Author Reply

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


  • Souvick

    SouvickSouvick

    Author Reply

    How to add video attachment?


  • Me

    MeMe

    Author Reply

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


    • go2014

      go2014go2014

      Author Reply

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


      • max

        maxmax

        Author Reply

        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

    RaviRavi

    Author Reply

    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

    NKNK

    Author Reply

    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


  • Milos

    MilosMilos

    Author Reply

    WOW, Thanks for great tutorial


  • faysalsabbagh

    I 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

    please help with this error

    timed out waiting for fence barrier from com.apple.MailCompositionService


  • Muhammad Bilal

    can we change background of mail composer ?


  • Anne B Perrault

    Thanks


  • bhavya

    bhavyabhavya

    Author Reply

    i am getting an erroe when i run the app with above code
    viewServiceDidTerminateWithError: Error Domain=_UIViewServiceInterfaceErrorDomain Code=3 “(null)”


  • bhavya

    bhavyabhavya

    Author Reply

    hiii i am getting mail sent in console but there is no mail in my inbox.


  • timbojill

    timbojilltimbojill

    Author Reply

    Is there an updated version made with swift 2 and xcode 7 I can download ?


  • Rajkar

    RajkarRajkar

    Author Reply

    [self presentViewController:mc animated:YES completion:NULL];
    I’m getting the exception with this line can any one help me to resolve this
    .


Shares