This is part of an ELC Tech Network

iPhone Programming Tutorial – Using openURL To Send Email From Your App

Have you been curious about how to open Mail.app from your applications to send contact email? Today, I will be teaching you how to do just that.  We will even be pre-filling the subject, to line, and body of the email.

This is a great way to to put a contact or bug report button on your app.  I’m going to start with a simple UI that I created.  I’m not going to discuss how it was created (I’ll leave that part up to you) as I have gone over Interface Builder quite a few times before.  

The UI simply consists of 2 UITextFields, a UITextArea, and a UIButton.  They are all connected to some code inside of the Applications Delegate.  This is not important, as the focus of this tutorial is to create a reusable function to send mail from your iPhone app. Here is a quick screenshot of the application…

screenshot_03

You can download my source code below, or simply start with a basic view-based application and make your own UI.  So, here is a function that I wrote to send email.  You can use this function in any application you wish.

screenshot_04

Ok, so let me explain what is going on… First, the function takes 3 arguments.  These are pretty obvious based on their name.  Next, we are building a string.  This string will have the format of a URL.  It’s pretty much the same thing as doing a “mailto” link on a webpage. One thing I want to point out is the fact that I had to use stringByAddingPercentEscapesUsingEncoding .  Wow, that’s a mouthful.  You would think Apple could come up with a shorter name.  Maybe SanitizeURLString or something… Either way, this does all of the special character replacements in the URL.  So spaces get replaced with %20, etc…

Advertisement

The next thing we do is simply open a URL using the built in openURL method in UIApplication.  This will cause the iPhone to open up Mail.app and magically, our to, subject, and body are already filled out.  Here is how I called the function in my app.

screenshot_05

I just connected this IBAction to the Mail UIButton in my app.  So when this method fires, it gets the value of to, subject, and body and passes it to our sendEmailTo method.  Pretty sweet ehh?  

That concludes this tutorial.  If you have any questions or comments feel free to leave them in the comments section or ask me on Twitter.  You can also download the source here.

Happy iCoding!

This entry was posted in iPhone Programming Tutorials and tagged , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

51 Comments

  1. Posted February 20, 2009 at 1:39 pm | Permalink

    Oh I didn’t know this functionality. Great ^^

  2. Todd
    Posted February 20, 2009 at 4:22 pm | Permalink

    I was implementing something similar this week and was having issues with European characters (umlats and such) getting encoded for the URL string. Unforunatley, I was unable to figure out why encoded euro chars were breaking the string. The nslog showed the string encoded them properly, but they would chop the string when passed to the mail client. Any thoughts?

  3. Posted February 20, 2009 at 8:34 pm | Permalink

    I tried to run the code, but, it gave a good 400+ errors–something about frameworks not being there–I tried to drag the 3 frameworks from the finder, but, that seems to have not done anything.

  4. Posted February 21, 2009 at 9:43 am | Permalink

    I had some issue with just using stringByReplacingPercentEscapesUsingEncoding. After some help from Apple I ended up with the following work around. You should run this preprocessor on the body of the email to get a good encoded string for the body. Also using the UTF8 encoding will help with the above commenter’s accented character issue.

    CFStringRef nonAlphaNumValidChars = CFSTR(“!$&’()*+,-./:;=?@_~”);
    CFStringRef preprocessedString = CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault, (CFStringRef)body, CFSTR(“”), kCFStringEncodingUTF8);
    CFStringRef bodyCFS = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,preprocessedString,NULL,nonAlphaNumValidChars,kCFStringEncodingUTF8);

    Hardy

  5. Posted February 23, 2009 at 1:34 am | Permalink

    nice post, friend.please come to my blog to see MY picture and friend

  6. Todd
    Posted February 23, 2009 at 1:45 pm | Permalink

    Hardy,

    Thank you. Works like a charm!

  7. Posted February 23, 2009 at 6:06 pm | Permalink

    I have a working code very similar to that one. But I have a problem… Since I am trying to export data from my application, it can be quite an amount of data. And it seems that this method truncates the body… Do you know anything related to this issue?

  8. RoMa
    Posted February 25, 2009 at 5:02 am | Permalink

    It dosn’t work :(

    Unsuported URL
    “This URL wasn’t loaded: mailto:?to=******@yahoo.fr&subject=test&body=Check%20ou%20iCodeBlog.com!”

    Why ?

  9. Posted February 25, 2009 at 5:48 pm | Permalink

    hrmm.. for those of you who are getting errors. What are they? Do they happen with the sample code? Are you running 2.2.1?

  10. mahboud
    Posted February 27, 2009 at 3:51 am | Permalink

    stringWithFormat:@”mailto:%@?cc=%@&subject=%@&body=%@

    This is what works for me. I believe mailto: has to be followed by addresses and not a ?

  11. Mat
    Posted February 27, 2009 at 10:12 am | Permalink

    Can it do attachments?

  12. Posted February 28, 2009 at 11:18 am | Permalink

    this is pretty basic, but I guess it helps. I love your tuts

  13. Posted February 28, 2009 at 11:20 am | Permalink

    err, normally in html its, mailto:email@emailprov.com?subject=…..

    just another piece of advice, I have never used & in my experience with web or iPhone,.

  14. Posted March 1, 2009 at 4:59 pm | Permalink

    Can the owner or webmaster of this site email me in regards to posting some of your tutorials on my site

  15. Stuart
    Posted March 8, 2009 at 12:29 am | Permalink

    As another user asked, can it load attachments like the photo library does?

  16. Posted March 11, 2009 at 7:19 am | Permalink

    Hi!
    What is the easiest way to install a program to my iphone, what i made in xcode?
    Thanks

  17. Milan
    Posted March 14, 2009 at 12:21 am | Permalink

    Hi,

    Email not sending from simulator.You have any idea.whats problem occur.

  18. bess
    Posted March 24, 2009 at 5:44 pm | Permalink

    It doesn’t seem to work this way

    NSString *toText = @”enter your email”;
    NSString *to = [toText stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *subjectText = @”enter subject”;
    NSString *subject = [subjectText stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *bodyText = @”enter body”;
    NSString *body = [bodyText stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    NSString *urlString =
    [NSString stringWithFormat:@"mailto:%@?subject=%@&body=%@", to, subject, body];
    NSURL *url = [[NSURL alloc] initWithString:urlString];
    [[UIApplication sharedApplication] openURL:url];

  19. Tung Do
    Posted April 7, 2009 at 8:36 pm | Permalink
  20. Tung Do
    Posted April 7, 2009 at 8:39 pm | Permalink

    I mean a href = “” tag

  21. John
    Posted April 10, 2009 at 10:46 am | Permalink

    Hello,

    Thanks For This – newbie here….

    I’m trying to incorporate this code into Tab Controller based app I have.

    What I have done:

    Copied your delegate OpenMailDelegates to my program. Should I have just added the code to my current delegates?

    Duplicated your main nib as SendEmail.xib and hooked everything up.

    Added an Item to my Tab Bar Controller and set it to: Nib – SendEmail.xib

    When I launch the program, all of my previous tabs work, the new tab however terminates due to uncaught exception.

    Any suggestions on where to start will be much appreciated!

    Thanks

  22. john
    Posted April 10, 2009 at 4:40 pm | Permalink

    Well -nothing like a little trial and error – got it working.

    I wish there was a way to return to the app once the email has been sent…

  23. Posted April 23, 2009 at 3:24 am | Permalink

    I just love your weblog! Very nice post! Still you can do many things to improve it.

  24. Posted April 23, 2009 at 3:45 am | Permalink

    really nice post.

  25. Posted April 24, 2009 at 2:10 pm | Permalink

    Great post – creating the strings that will work like this seems tricky sometimes, but it is generally reasonable to use email from the iPhone. Wish it was possible to send file attachments (which coding our own email server). Most of my customers want detail CSV files exported somehow from my apps which are all information driven.

    • Posted May 23, 2010 at 6:25 am | Permalink

      I’ve been using box.net to upload text files from my app – My Bird Observations. It’s a file-sharing site. 2G space for free. Easy to use.

  26. Posted May 5, 2009 at 5:28 pm | Permalink

    It doesn’t work in iPhone simulator since there is no Mail.app
    It will work on the iPhone.

  27. Jay
    Posted May 6, 2009 at 1:32 am | Permalink

    Can I send Attachment with E-mail?

  28. Peter
    Posted May 9, 2009 at 9:38 pm | Permalink

    How do you email multiple addresses without having to have multiple text areas like if I typed “peter” it would email to

    peter@gmail.com
    peter@yahoo.com
    peter@aol.com

  29. Posted May 20, 2009 at 6:23 am | Permalink

    Hello everyone,
    I am using this application(openmail) but i have some problem.when i run the app then fill up text field and press button then it gives me problem:

    Unsupported URL

    This URL wasn’t loaded:
    mailto:?
    to=rt@gmail.com&subject=sending email&body=Check%20out%20.
    in alert.So,plz give me any suggestion when i am wrong.

  30. Posted June 4, 2009 at 7:10 pm | Permalink

    I’m definitely bookmarking this site. Really great articles. Do you recommend any other readings?

  31. Lakshmikanth
    Posted June 8, 2009 at 6:14 am | Permalink

    after using the “openURL” method and sent message using mailto, how to come back to the application.

  32. Posted June 11, 2009 at 1:11 pm | Permalink

    Just a small note: The code of bess works, but has a memory leak: the NSURL will not be released. Use URLWithString (as in the blog post) instead of alloc] initWithString. Or add an autorelease after initWithString. Then use an autoreleasepool (if there is none).

  33. Posted June 20, 2009 at 1:47 pm | Permalink

    If you ever want to hear a reader’s feedback :) , I rate this article for four from five. Decent info, but I just have to go to that damn google to find the missed bits. Thank you, anyway!
    p.s. Year One is already on the Internet and you can watch it for free.

  34. Posted June 26, 2009 at 9:22 am | Permalink

    I got an iPod touch a couple of days ago but I think I had better bought an iPhone :(

  35. Posted July 2, 2009 at 6:46 pm | Permalink

    I was wondering if there is a way to send a photo attached to the mail.

    Thanks!

  36. cheebs
    Posted July 14, 2009 at 10:00 am | Permalink

    Great tutorial. However, it’s worth mentioning that this only works on-device and not within the simulator (which is weird as openUrl with a http url works fine (i.e. launches safari) within the simulator)

  37. Sachin
    Posted July 16, 2009 at 5:57 pm | Permalink

    hello there,

    Having one ?…

    can i attach file to this mail which i am sending.

    i am trying to develop the same mail app.but in my app, i also need to attach file,so is there any way that if i provide the file then it will be automatically get attached to mail app.
    like mail id and subject.

  38. jfm
    Posted July 17, 2009 at 12:51 pm | Permalink

    thanks for this! worked for us. big help. didn’t know you could encode different parts of a string differently. this shows how we used this but used an HTML string only for the body.

    NSString *mailString = [NSString stringWithFormat:@"mailto:?to=%@&subject=%@&body=%@",
    [to stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding],
    [subject stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding],
    [finalEmailBody stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

    jfm

  39. Ethan
    Posted July 26, 2009 at 5:13 pm | Permalink

    I’m having the same issue as John -

    I’m using a Tab Bar based application. In one of my tabs, which loads a separate nib, I want to use this mail function, so I copied the OpenMailAppDelegate files over to my nib. The issue I’m having is that I can’t (or, rather, don’t know how to) connect the delegate to the UIApplication, since it is contained in a different nib. Or, if I wanted to write the mail code in my application delegate, contained in a nib named MainWindow.xib, how to I connect its outlets to a view contained in another nib (QuizView.xib)?

    Thanks for the help,

    Ethan

  40. Posted August 3, 2009 at 12:06 pm | Permalink

    my God, i thought you were going to chip in with some decisive insght at the end there, not leave it with ‘we leave it to you to decide’.

  41. Posted August 22, 2009 at 5:31 am | Permalink

    Ta for the information, very usefull

  42. Posted September 13, 2009 at 4:33 pm | Permalink

    Good post, adding it to my blog now, thanks

  43. Nat
    Posted December 16, 2009 at 10:44 pm | Permalink

    Hi,

    How can I add attachment if I use openurl mailto?

    -Nat

  44. Posted January 13, 2010 at 4:47 am | Permalink

    The iphone is still on my shopping list. I wish the price would go down a bit so I could afford one.

  45. Posted March 25, 2010 at 3:39 pm | Permalink

    Very helpful, Thanks a lot. I have one question thought. If I’ll have two text fields and two labels as a body how do I manage to send that? I tried, didn’t give me any error but e-mail is not sending. Any ideas?

    fieldArray = [[NSArray arrayWithObjects:

    [NSString stringWithFormat:@"%@",txtBody.text],
    [NSString stringWithFormat:@"%@",txtBody2.text], nil] retain];

    - (void) sendEmailTo:(NSString *)to withSubject:(NSString *) subject withBody:(NSString *)body {
    NSString *mailString = [NSString stringWithFormat:@"mailto:?to=%@&subject=%@&body=%@",
    [to stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding],
    [subject stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding],
    [body stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];

    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:mailString]];
    }

    [self sendEmailTo:[txtTo text] withSubject:[txtSubject text] withBody:fieldArray];

    [fieldArray release];
    }

  46. Posted April 6, 2010 at 11:26 pm | Permalink

    This was a Fantastic write up, I will save this in my Diigo account. Have a awesome day.

  47. jeff
    Posted May 14, 2010 at 6:22 am | Permalink

    Next time idiot make the source code TEXT and not a JPEG so we can copy and paste that shit! :)

  48. Posted June 13, 2010 at 9:08 pm | Permalink

    A Excellent blog post, I will be sure to save this in my StumbleUpon account. Have a awesome evening.

  49. Posted June 27, 2010 at 8:17 pm | Permalink

    Thanks for posting the info on this app!

  50. Posted July 12, 2010 at 3:46 am | Permalink

    Haloadministrator I love with your news . May i use this information for my school test ? thank you adminstrator

15 Trackbacks

  1. [...] A quick and short tutorial plus code for calling mail app in iphone from your application and automatically filling in the address, subject and content. Read it here. [...]

  2. [...] 38. Send email [...]

  3. [...] iPhone Programming Tutorial-Using openURL to Send Email from Your App: This tutorial explains how you can send email through applications, and even pre-fill fields. [iCode] [...]

  4. By 200ml » 100 Free courses for iPhone Dev on June 28, 2009 at 10:58 am

    [...] iPhone Programming Tutorial-Using openURL to Send Email from Your App: This tutorial explains how you can send email through applications, and even pre-fill fields. [iCode] [...]

  5. [...] iPhone Programming Tutorial-Using openURL to Send Email from Your App: This tutorial explains how you can send email through applications, and even pre-fill fields. [iCode] [...]

  6. By Some Great Resources! | My First iPhone Application on October 20, 2009 at 9:24 pm

    [...] iPhone Programming Tutorial-Using openURL to Send Email from Your App: This tutorial explains how you can send email through applications, and even pre-fill fields. [iCode] [...]

  7. [...] iPhone Programming Tutorial – Using openURL to Send Email from Your App This tutorial shows you how to use openURL to allow your apps to send email. [...]

  8. [...] iPhone Programming Tutorial – Using openURL to Send Email from Your App This tutorial shows you how to use openURL to allow your apps to send email. [...]

  9. [...] iPhone Programming Tutorial – Using openURL to Send Email from Your App This tutorial shows you how to use openURL to allow your apps to send email. [...]

  10. [...] iPhone Programming Tutorial-Using openURL to Send Email from Your App: This tutorial explains how you can send email through applications, and even pre-fill fields. [iCode] [...]

  11. [...] iPhone Programming Tutorial – Using openURL to Send Email from Your App This tutorial shows you how to use openURL to allow your apps to send email. [...]

  12. [...] iPhone Programming Tutorial-Using openURL to Send Email from Your App: This tutorial explains how you can send email through applications, and even pre-fill fields. [iCode] [...]

  13. [...] Using openURL to send Email – If you have ever needed to send email from within your app this short tutorial explains how. [...]

  14. [...] A quick and short tutorial plus code for calling mail app in iphone from your application and automatically filling in the address, subject and content. Read it here. [...]

  15. [...] Using openURL to send mail from your app. Ottimo tutorial su come implementare nelle applicazioni un modulo per invio diretto di email. Assolutamente da non perdere. [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">