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.
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]; <strong> picker.mailComposeDelegate = self;</strong> // <- 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…
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 :-(" 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
[self 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.
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,
Update: (28th August 2009)
Two commenters have asked me for sending email without showing the UI.
I think it’s not that easy. You have to use a SMTP client like http://code.google.com/p/skpsmtpmessage/
This blog explains how to send emails in the background without user intervention. But I’m not sure about Apple approving such apps however…
–
If you enjoyed this post, make sure you subscribe to my RSS feed!Related posts:
- iPhone Tutorial: How to send In-App SMS Officially, iPhone OS 4 is out of NDA and I...
- iPhone Tutorial: Elegant way to send formatted In-App email By now, most of you know how to send emails...
- iPhone Tutorial – Enabling reviewers to use your In-App purchases for free In-App purchases is a great way for developers to upsell...
- iPhone Tutorial – In-App Purchases Last week, Apple announced that in-app purchases will be available...
- iPhone Tutorial – UISearchDisplayController with NSPredicate Though UISearchDisplayController is seemingly easy (and yes it’s easy), apart...
30 Responses to “iPhone Tutorial – In-App Email”
Trackbacks/Pingbacks
- iPhoneOS iPad Development Resources | de - [...] http://blog.mugunthkumar.com/coding/iphone-tutorial-in-app-email/ [...]
- iPhone Tutorial: Elegant way to send formatted In-App email | blog.mugunthkumar.com - [...] you might want to subscribe to the RSS feed for updates on this topic.By now, most of you know ...
- iPhone Tutorial: How to send In-App SMS | MK Blog - [...] write a post on this. If you have been reading my blogs, you might already know how to send ...


I'm working with the MailComposer project and found your blog. I'm fairly new to iPhone development. In this project when the MFMailComposeViewController is presented I am trying to handle the send and cancel buttons. What IBAction or method do I have to handle to catch these two button events? My app sends the email, but I need a procedure to dismiss the MFMailComposeViewController.
Thank you!
If you set
picker.mailComposeDelegate = self; your controller will be notified of these events via, a delegate,
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
If you don't set your controller (the class that calls the mailcomposer dialog) as the delegate, you won't get those callbacks.
To dismiss the modal view, call
[self dismissModalViewControllerAnimated:YES];
inside the delegate method.
I've explained this in Step 4.
Hope my article is clear.
Thanks for visiting.
Hi,
Thank you very much for the post and the information provided. I tried this and it works fine.
But, I'm struck with some problem. I have 4 views. The email sending part is the 4th view. Once email is sent, I need to display an alert saying "email sent" ans then show the second view.
I have written code to show the alert in the case
case MFMailComposeResultSent:
[self dismissModalViewControllerAnimated:YES];
Takes me to the 3rd view after displaying the alert. But, how will I show the 2nd view instead of 3rd?
Waiting for your help.
Thanks,
ash.
Hey… I figured it out myself..
[self.navigateController popViewControllerAnimated:YES]
will do the trick !!!
-ash
oops, posted too soon, got it ….
Hello. Thank you for this great info! Keep up the good job!
Hi,
Is there a method to also send the email securely? Ie. encrypted?
Thanks,
Eric
It depends on your Email configuration settings. If your IMAP server supports (or requires) TLS, then every email u send is always sent over an encrypted channel. If it doesn't, even if you manually encrypt, it will not understand your data.
However, If you are looking for a solution to send some data from the user back to your server (like a highscore from your game), consider using RESTful services rather than encrypting data and sending it as an email.
My next blog post, which I currently writing is on consuming RESTful web services on iPhone.
Awesome post. You rock.
Hi,
Thanks for the great post!! I want to use MFMailComposeViewController in my app, like in Apple's MailComposer example application, but …
I don't want the user to be able to edit the "To:" field, in fact I don't want to display it at all. I don't want to display or have the user edit the CC or BCC fields, or even the Subject field. I want to be able to attach images, but I don't want them to be visible in the view. (In fact, I have another problem: I don't know how to dismiss the UI's keyboard other than clicking Send or Cancel).
What I *really* want is to be able to populate the picker properties (Subject, toRecipients, AttachmentData) programmatically, and programmatically call the "Send" button, so the email gets sent without even showing the UI.
Is there a way to do that? MFMailComposeViewController is the only way I know to send email with image attachments. If MFMailComposeViewController can't be used like that, can I get this functionality another way?
Thanks for any help.
/Steve
Post updated with your questions. Thanks for visiting my blog
and thanks for your interesting question…
Excellent site, keep up the good work
I’m so glad I found this site…Keep up the good work
Cool site, love the info.
did you ever figure this out:
I don't want the user to be able to edit the "To:" field, in fact I don't want to display it at all. I don't want to display or have the user edit the CC or BCC fields, or even the Subject field. I want to be able to attach images, but I don't want them to be visible in the view
also, to dismiss the MFMailComposeViewController, implement
(void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
To have utmost control on your email sending, use a custom SMTP mail sender like, http://code.google.com/p/skpsmtpmessage/
BTW, this post has implemented didFinishWithResult (sec 4)
Thanks much for this good piece of text.
Hi,
thankx for nice tutorial.
I have run the apples sample code,
but i want to attach files or images at run time, how i can do it?
thanks in advance
Use these two lines of code. You should know the filePath and it's mimeType
How to receive emails using pop service in iPhone programmetically?
Anyone knows?
Great post, have tried your way for the email body rather than from contents of html file but I still get the message being send encoded so the links as in your example (and mine) do not come out correct. Even though it is set to isHTML:YES I do not get visible text. The receeved email contains nothing to say it is HTML in fact the header says text/plain but the content is encoded?
Any ideas??
Thank you!!!
But how to send email without showing the UI?
The blog http://vafer.org/blog/20080604120118 shows it for cocoa, not for cocoa touch.
And using a SMTP client like http://code.google.com/p/skpsmtpmessage/ is too big.
Thanks for any help.
Just want to say a big Thank You for posting this. Definitely a big help and resource for me.
Thanks again!
Hi Im kinda New to iphone development and I want use MFMailComposeViewController to take the text/notes that are on the screen and have them automatically applied to the subject portion of the screen is this possible and if so how would I implement it. Thank for the great tutorial and any and all help you can provide.
Chris
Hi I believe the data written on your internet blog is fundamental, I have book marked you =D
Pretty nice post. I just stopped by by your site and wanted to say that I have really enjoyed checking your content. Any way, I’ll be subscribing to your RSS feed and I hope you write again shortly!
I am very new to iPhone app development.. This is my very first one. I am trying to implement your solution here and have a question. Inside the Frameworks tab, I don’t have the MessageUI Framework. I am using the most recent version of XCode. I know it is something simple, but.. Can someone give me a hand. Also my screen does not look like the one in this article, guessing newer version on my box.
Hi, I am trying to auto populate Recipient in mail composer once I select the person's email address from the address book.
I am not sure how I can do this? Is there a way I can do this?
Can anyone please help me with this.
Thanks,
How to receive emails using pop service in iPhone programmetically?
Anyone knows?
(…same question already posted by Sanniv 20 weeks ago, I can't find any answer too,
may be not possible …or just obvious !?)
Awesome tutorial. Saved me a lot of time integrating feedback email into my App. Thanks again.