Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Mobile / iPhone

iPhone Tutorial – In-App Email

4.22/5 (7 votes)
20 Jul 2009Ms-PL5 min read 57.1K  
Sending an email from your iPhone application is something which you normally want to do it asynchronously. But unfortunately, prior to iPhone 3.0, the only way to send email was using mailto:// url format. i.e, [[UIApplication sharedApplication] openURL: @mailto:john.appleseed@appl


Sending an email from your iPhone application is something which you normally want to do it asynchronously. But unfortunately, prior to iPhone 3.0, the only way to send email was using mailto:// url format. i.e,

[[UIApplication sharedApplication] openURL: @"mailto:john.appleseed@apple.com"];

The technique was clumsy for one reason.

It quits your app and launches mail. To our rescue, comes in-app email.

In-App email is not something new in iPhone 3.0 software. For the end users, it was available from day 1. Remember the Photos app? It sends your photos attached in the email message without quitting? But third party developers like us, were not given access to those private APIs.

In iPhone 3.0 Apple has exposed this private API with which you can send emails without quitting your application.

Sending an email with this technique might not be as easy as one single function call which we saw earlier, but at the same time it’s not complicated like “Push notification”. With less than say 10 lines of code, you can get the in-app email up and running in your own app. Now, let’s see how to do that.

I’m not going to attach any source code or like. The best source code that anyone can write is already available from Apple. Search for MailComposer or click the link below.

https://developer.apple.com/iphone/library/samplecode/MailComposer/index.html (link opens in new window)

There isn’t however a walkthrough though, which is why I thought I could bridge the gap ;-)

To summarize, there are 4 main steps (and 1 other not-so-important) in this.

1) Add the MessageUI Framework to your project

2) Add #import <MessageUI/MessageUI.h> line to the file where you want to use in-app email

3) The real code to show the UI as a modal dialog.

4) Implement a callback delegate so that you know when the user (and system) has finished sending the email.

Let’s get started.

Importing the MessageUI should be a cakewalk. On your XCode window,right click/cmd+click the “Frameworks” folder and click Add -> Existing Framworks. Choose the MessageUI from the path illustrated below.

Adding MessageUI Framework to XCode

Adding MessageUI Framework to XCode

Step 1 – Done

2) The second step needs no special explanation.

In your view controller, you will be using the classes in this framework. So #import the necessary header file, MessageUI/MessageUI.h

Do this #import on the h file rather than the m file as, you will be adding a delegate later (in step 4) to your ViewController.

Step 2 – Done

3)I’ve written a nifty little function that does the complete email sending logic.

The code is here. Feel free to use it in your apps, (attribution not necessary, though I would be happy if you do so)

-(void) showEmailModalView {

 MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
 picker.mailComposeDelegate = self; // <- very important step if you want feedbacks on what the user did with your email sheet

 [picker setSubject:titleText.text];

 // Fill out the email body text
 NSString *pageLink = @"http://mugunthkumar.com/mygreatapp"; // replace it with yours
 NSString *iTunesLink = @"http://link-to-mygreatapp"; // replate it with yours
 NSString *emailBody =
 [NSString stringWithFormat:@"%@\n\n<h3>Sent from <a href = '%@'>MyGreatApp</a> on iPhone. <a href = '%@'>Download</a> yours from AppStore now!</h3>", content, pageLink, iTunesLink];

 [picker setMessageBody:emailBody isHTML:YES]; // depends. Mostly YES, unless you want to send it as plain text (boring)

 picker.navigationBar.barStyle = UIBarStyleBlack; // choose your style, unfortunately, Translucent colors behave quirky.

 [self presentModalViewController:picker animated:YES];
 [picker release];

}

The first step is to create the view for the email class. For that we use the MFMailComposeViewController.

Subsequent steps are to fill in the subject, (ToAddress, CC etc also can be filled from [picker setBlahblahMethods]) and messagebody. Usually, you leave the addresses to be filled by the user. Until the user fills the “To” field, the “Send” button will not be enabled on the Email sheet.

You can choose a color for the in-app email sheet. Unfortunately translucent sheet behave a bit quirky. For me the To address field was getting hidden beneath the translucent toolbar. :( I may be wrong.

Finally call the presentModalViewController to display the email sheet.

Step 3 – Done!!!

4) Now, you need to implement a delegate that will be called when the user taps the “Send” button on the mail interface. Luckily, it’s again a simple thing… :D

For this delegate to be called, you have to set the picker.mailComposeDelegate to self before calling the presentModalViewController (this line is shown in bold in step 3)

If you compile the app, XCode will complain that your “MyGreatAppViewController doesn’t conform to  MFMailComposeViewControllerDelegate protocol. Though it’s a warning and can be ignored, for the sake of writing “quality” app, add the “MFMailComposeViewControllerDelegate” to your protocol handler list like this in the header file.

@interface MyGreatAppViewController : UIViewController <MFMailComposeViewControllerDelegate> { }

This is the reason why I advised you to add the MessageUI header imports in the .h file in Step 2. Now in your .m file, add the following block of code that handles the delegate.

// Dismisses the email composition interface when users tap Cancel or Send. Proceeds to update the message field with the result of the operation.
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{�
 // Notifies users about errors associated with the interface
 switch (result)
 {
 case MFMailComposeResultCancelled:
 break;
 case MFMailComposeResultSaved:
 break;
 case MFMailComposeResultSent:
 break;
 case MFMailComposeResultFailed:
 break;

 default:
 {
 UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Email" message:@"Sending Failed - Unknown Error <img class=""wp-smiley"" alt="":-("" src="%22http://blog.mugunthkumar.com/wp-includes/images/smilies/icon_sad.gif%22" /> "
 delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
 [alert show];
 [alert release];
 }

 break;
 }
 [self dismissModalViewControllerAnimated:YES];
}

Relax! Not the whole block is important. just write the last line,

[self dismissModalViewControllerAnimated:YES]

and that will do. The other lines are given here for the sake of completion. You can handle those situations if you want.

As of now, there is no delegate method that would report the percentage of the mail that has been transmitted (so that you can display a progress like the Mail app. But hopefully, with subsequent releases of the SDK, apple could open them up as well.

Step 4 – Done!!!

Now, just call

showEmailModalView

where you want the sheet to be shown. That’s it.

Now…. One more thing… ;-)

iPhone users have migrated to iPhone 3.0 (atleast over 75%). iPod touch users still haven’t (atleast at the time of writing this article). How will you handle a situation where in the user using your app is still running iPhone 2.x software?

Fortunately, Apple has provided a simple one-liner to tackle the situation. Just check it by calling canSendMail method

[MFMailComposeViewController canSendMail]

If canSendMail, then call my showEmailModalView function, otherwise, fall back to the tradional way. This handling is explained elegantly in Apple’s source code MailComposer.

<a href="%22https://developer.apple.com/iphone/library/samplecode/MailComposer/index.html%22" target=""_blank"">https://developer.apple.com/iphone/library/samplecode/MailComposer/index.html</a> (link opens in new window)

That’s it for this tutorial. Hope you enjoyed it and Thanks for visiting my blog,

Share and Enjoy: Print this article! Digg del.icio.us Facebook Google Bookmarks Netvibes

Related posts:

  1. Setting up XCode 3.0 with SVN codeproject Everyone knows SVN (Subversions) is the best version...

Related posts brought to you by Yet Another Related Posts Plugin.

License

This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)