Sending emails from your iOS app without leaving the application is really easy thanks to MFMailComposeViewController. Today I will demonstrate how to do this by creating a simple app to send an email.
Step 1: Creating the project
First of all, you need to create a new project. Open Xcode, create a new project and select Single View Application. Fill in the App name, make sure you use Storyboard and ARC, and click next.
Step 2: Importing MessageUI Framework
To use MFMailComposeViewController, you will need the message framework. Click on the project file, and in Summary, scroll down to Linked Frameworks and Libraries and click on the plus button. Then, select MessageUI.framework and add it to your project.
Step 3: The Header File
Now, go to ViewController.h and replace the existing code with this:
#import <UIKit/UIKit.h>
#import <MessageUI/MessageUI.h>
@interface ViewController : UIViewController
- (IBAction)sendMail:(id)sender;
@end
In line 2 we import the framework we added, and in line 6 we declare the method that will be called when the user clicks on the UIButton we will create in the next step to send a new email. As for line 4, we made our ViewController adopt the MFMailComposeViewControllerDelegate protocol to set it as the delegate of the MFMailComposeViewController instance we will create. This way, ViewController will be notified when the user finishes sending an email or cancels it.
Step 4: UI
In the storyboard, drag a Round Rect Button to the view controller. Then, Control-drag it to View Controller and select sendMail: when prompted.
Step 5: Using MFMailComposeViewController
MFMailComposeViewController is a modal view controller, so you need to create it, set its attributes, and finally call presentModalViewController: animated:. Before you do this, however, it would be better to check whether the device is able to send mail.
- (IBAction)sendMail:(id)sender
{
if ([MFMailComposeViewController canSendMail]) {
MFMailComposeViewController *mail = [[MFMailComposeViewController alloc] init];
mail.mailComposeDelegate = self;
[mail setSubject:@"The Subject"];
NSArray *recipient = [NSArray arrayWithObjects:@"mail@example.com", nil];
[mail setToRecipients:recipient];
NSString *body = @"This is the body!";
[mail setMessageBody:body isHTML:NO];
[self presentModalViewController:mail animated:YES];
}
}
Step 6: Dismiss MFMailComposeViewController
To dismiss the modal view controller, simply add the following method:
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{
[self dismissModalViewControllerAnimated:YES];
}
Conclusion
Thank you for reading this tutorial! Please leave a comment if you have any doubts.