Click here to Skip to main content
6,822,123 members and growing! (16,014 online)
Email Password   helpLost your password?
    Beginner License: The Microsoft Public License (Ms-PL)

iPhone Tutorial – In-App Email

By Mugunth Kumar, Singapore

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
C (Objective-C), Mobile (iPhone), All-Topics, Dev
Revision:2 (See All)
Posted:20 Jul 2009
Views:8,012
Bookmarked:10 times
Technical Blog
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
4 votes for this technical blog.
Popularity: 2.77 Rating: 4.60 out of 5

1

2
1 vote, 25.0%
3

4
3 votes, 75.0%
5
A Technical Blog article. View entire blog here.


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 wp-smiley" alt=":-(" src="http://blog.mugunthkumar.com/wp-includes/images/smilies/icon_sad.gif" /> "
 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.

"_blank" href="https://developer.apple.com/iphone/library/samplecode/MailComposer/index.html">https://developer.apple.com/iphone/library/samplecode/MailComposer/index.html (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)

About the Author

Mugunth Kumar, Singapore


Member
Working as a Software Engineer @ Honeywell Singapore
I also develop iPhone Apps, Windows Apps, Web Apps in my free time.
Visit, http://mugunthkumar.com
for more information.

I blog @
http://blog.mugunthkumar.com/
Occupation: Software Developer
Company: Honeywell
Location: Singapore Singapore

Other popular Mobile Development articles:

  • Writing Your Own GPS Applications: Part 2
    In part two of the series, the author of "GPS.NET" teaches developers how to write GPS applications suitable for the real world by mastering GPS precision concepts. Source code includes a working NMEA interpreter and sample high-precision application in C# and VB.NET.
  • Writing Your Own GPS Applications: Part I
    What is it that GPS applications need to be good enough to use for in-car navigation? Also, how does the process of interpreting GPS data actually work? In this three-part series, I will cover both topics and give you the skills you need to write a commercial-grade GPS application.
  • Learn How to Find GPS Location on Any SmartPhone, and Then Make it Relevant
    A step by step tutorial for getting GPS from any SmartPhone, even without GPS built in, and then making location useful.
  • Windows Mobile, iPhone, Android - Marketplace Comparison
    Detailed comparison between Windows Mobile Marketplace, Apple's iPhone AppStore and Android Market from developer point of view.
  • iPhone UI in Windows Mobile
    It's an interface that works with transparency effects. As a sample I used an interface just like the iPhone one. In this tutorial I am explaining how simple is working with transparency on Windows Mobile.
Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 3 of 3 (Total in Forum: 3) (Refresh)FirstPrevNext
QuestionSend Mail on SDK Simulator Pinmembernaraku_8310:32 21 Nov '09  
GeneralAny way to send mail without the MailComposerViewController? Pinmembermobopro10:41 6 Aug '09  
GeneralGlad to see some objective-c samples/code Pinmemberronnyek12:18 21 Jul '09  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads.

PermaLink | Privacy | Terms of Use
Last Updated: 20 Jul 2009
Editor:
Copyright 2009 by Mugunth Kumar, Singapore
Everything else Copyright © CodeProject, 1999-2010
Web20 | Advertise on the Code Project