How to Send Email with MFMailComposeViewController in iOS Using Objective-C?

Hello everyone, in this tutorial we will be going to work on the iOS Mail feature present within the iOS SDK.

The iOS SDK provides us the ability to send email using the built-in APIs. Adding few lines of codes, you can launch the same interface like iOS stock Mail UI application that lets you compose an email. We will be going to build a very simple app to show how to send both plain text and HTML email using the iOS SDK.

Initial Setup

Let’s first create our setup quickly, to do this head into the XCode application and click on the create a new application and within it select single view application as shown below.

After this step, give a name to your application and save it to a particular location so that you can access it later.

Interface Designing

Now we will be going to design the interface for the application. As this is a simple application so we will be going to use a button in the center of the app to show the custom message dialogue later after user press the button.

Use the constraints as center horizontally, center vertically, equal width and equal height for your button.

Give a custom color to your background so that the view looks attractive. I am going to use blue color for my button.

Connection with Outlets

At this point, we only need to create a connection with the objects and its elements. So head into New file section on the top left corner of XCode and create a new file and name it as ContactViewController and assign it to your view controller.

Step 1

Here we will 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 “ContactViewController.h”. As you place the mouse pointer between the “@interface” and “@end” keywords, you should see a prompt that allows you to insert outlet and action.

Now all you need to do is to release the mouse button and Xcode will allow you to add the outlet/action. As we are going to add the action method, We need to select the “Action” for “Connection” and name the method as “contactAction”. You can keep the event as “Touch Up Inside”. The “contactAction” method will be invoked when users lift up the finger inside the button.

Step 2

As soon as you ensure the change by clicking the “Connect” button, Xcode automatically will be going to add the method declaration in the ContactViewController.h.

After performing all the coding in your file the ContactViewController.h file will look like this:

#import <UIKit/UIKit.h>

@interface ContactViewController : UIViewController

- (IBAction)contactAction:(id)sender;

@end

Implementing the Email Interface

Now we need to add four frameworks to our project so head into the Linked Framework and Libraries section and add the following framework to it:

  1. CoreGraphics.framework
  2. Foundation.framework
  3. UIKit.framework
  4. MessageUI.Framework

You can see the snapshot in which I have added all the four frameworks mentioned earlier.

Step 1

We need to import the messageUI framework into our ContactViewController.h file so later we can add the delegate method to it

After adding the framework the modified file will look like this as shown:

#import <UIKit/UIKit.h>

#import <MessageUI/MessageUI.h>

@interface ContactViewController : UIViewController<MFMailComposeViewControllerDelegate>

- (IBAction)contactAction:(id)sender;

@end

Step 2

We will be going to implement the action part of the contact button through which, we can call the delegate method of MFMailComposer.

So head into your ContactViewController.m file and inside it, find the button action of  “contactAction” and add the following code to it as shown:

- (IBAction)contactAction:(id)sender {

 // Email Content

    NSString *messageBody = @"iOS programming is so fun!";

    // To recipient where you want to send it 

    NSArray *toRecipents = [NSArray arrayWithObject:@"[email protected]"];

  // MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];

  MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];

    if ([MFMailComposeViewController canSendMail]) {

        picker.mailComposeDelegate = self;

        [picker setSubject:@"Test mail"];

        [picker setMessageBody:messageBody isHTML:NO];

        [picker setToRecipients:toRecipents];

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

    }

}

Now as you can see that we have already added the message body and the recipient hardcoded to it. You can use a custom box to add them but I prefer to make it simple as you can change them later also when the composer will call.

Step 3

We can also check whether user canceled, save or send the email using the didFinishWithResult: method of the MFMailComposeViewController library. Add the following code to the button action method:

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

    }

      // This will be going to close the Mail Interface

    [self dismissViewControllerAnimated:YES completion:NULL];

}

This method will be going to show the result after the user finishes his action for the particular mail.

Build and Run the Application

Here if you will run the application and initially after pressing the contact us button, you will see the pop alert message which will ask you to add a mail account if it’s not there as shown:

Later after adding it if you will re-run the same application then on the contact us button click.

It will be going to open the mail interface similar to its default email screen through which you can add the new email recipient or message into it.

 

Adding HTML Text

If you want to make your simple text to HTML text then you only need to add few lines of code into your mail compose view.

For example, if you want to make the message body to HTML then add the h1 tag into it:

    NSString *messageBody =@”<h1>iOS programming is so fun!</h1>” ;

And later change the isHTML type from no to yes as shown:

        [picker setMessageBody:messageBody isHTML:YES];

Summing Up

Finally, we are ready with our tutorial and have successfully implemented the basic email sending feature into our application using the iOS Message UI framework.

I hope you will find this tutorial useful for your application and if you want more tutorial like this then let me know in the comment section below.

Latest posts by Rahul Huria (see all)

2 thoughts on “How to Send Email with MFMailComposeViewController in iOS Using Objective-C?”

Leave a Comment