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

  • Twitter
  • Facebook
  • Digg
  • Reddit
  • StumbleUpon
  • del.icio.us
  • Google Bookmarks
February 20th, 2009 Posted by: (ELC) - posted under:Snippets

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…

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!

  • http://www.pierreabiaad.com Pierre

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

  • Todd

    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?

  • http://www.webappgalaxy.com Mark H. Delfs

    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.

  • http://iphonedevelopmentbits.com/code-for-sending-email-from-your-iphone-app/ Code for Sending email from your iPhone App | iphonedevelopmentbits

    [...] 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. [...]

  • http://www.catamount.com Hardy Macia

    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

  • http://girly-photo.blogspot.com/ MyPicture and friend

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

  • Todd

    Hardy,

    Thank you. Works like a charm!

  • http://fass-software.com Félix Simões

    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?

  • RoMa

    It dosn’t work :(

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

    Why ?

  • http://brandontreb.com Brandon

    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?

  • mahboud

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

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

  • Mat

    Can it do attachments?

  • http://JoshuaCaputo.com JoshuaCaputo

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

  • http://JoshuaCaputo.com JoshuaCaputo

    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,.

  • http://iphone.christosblog.com Christo

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

  • Stuart

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

  • http://mossreg.webp.com moss

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

  • Milan

    Hi,

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

  • bess

    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];

  • http://afruj.wordpress.com/2009/03/24/iphone-tutorials/ iPhone development Tutorials « The Brook Song – ঝর্ণার গান

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

  • Tung Do
  • Tung Do

    I mean a href = “” tag

  • John

    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

  • john

    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…

  • http://www.bestuniversities.com/blog/2009/100-free-courses-tutorials-for-aspiring-iphone-app-developers/ 100 Free Courses & Tutorials for Aspiring iPhone App Developers | Best Universities

    [...] 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] [...]

  • http://cloakedlink.com/wurdokwohh 100% Free Iphone

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

  • http://cloakedlink.com/wurdokwohh GetAFreeIphone

    really nice post.

  • http://howtomakeiphoneapps.com MattjDrake

    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.

  • http://www.farfromperfection.com/ Scott

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

  • Jay

    Can I send Attachment with E-mail?

  • Peter

    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

  • http://www.fortuneinfotech.com Rupnarayan

    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.

  • http://bricetsjkxgray.blogsome.com Poppy Keant

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

  • Lakshmikanth

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

  • http://www.christian-fries.de/iphone/presentationassistant/ Christian Fries

    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).

  • http://www.watchyearoneonline.com/ Watch Year One Online Free

    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.

  • http://www.ipwngames.com mweeza

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

  • http://200ml.info/wordpress/?p=12 200ml » 100 Free courses for iPhone Dev

    [...] 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] [...]

  • http://qwonder.com Rafael

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

    Thanks!

  • http://iphoner.org.ua/blogs/akrakovetsky/archive/2009/07/05/100-iphone.aspx 100 ресурсов для iPhone-разработчиков – Краковецкий Александр: заметки прогÑ

    [...] 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] [...]

  • cheebs

    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)

  • Sachin

    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.

  • jfm

    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

  • Ethan

    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

  • http://www.extenzedeal.com Extenze

    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’.

  • http://www.yourfreegadget.co.uk Free Gadget

    Ta for the information, very usefull

  • http://www.free-mobilephone.co.uk Free Mobile Phone

    Good post, adding it to my blog now, thanks

  • http://www.myfirstiphoneapplication.com/2009/10/some-great-resources/ Some Great Resources! | My First iPhone Application

    [...] 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] [...]

  • http://www.onlinemagazabayiservisyazilim.com/the-ultimate-toolbox-for-iphone-development.html Online Business Management Software and Services » Blog Archive » The Ultimate Toolbox for iPhone Development

    [...] 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. [...]

  • http://cs-me.com/2009/11/21/the-ultimate-toolbox-for-iphone-development/ The Ultimate Toolbox for iPhone Development – Creative Solutions

    [...] 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. [...]

  • http://mundoimd.com/2009/11/30/enlaces-para-desarrollar-en-el-iphone/ Enlaces para desarrollar en el iPhone | El mundo de IMD

    [...] 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. [...]

  • Nat

    Hi,

    How can I add attachment if I use openurl mailto?

    -Nat

  • http://fansibo.com/?p=238 100 Free Courses & Tutorials for Aspiring iPhone App Developers | c'est la vie

    [...] 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] [...]

  • http://fansibo.com/?p=238 100 Free Courses & Tutorials for Aspiring iPhone App Developers | c'est la vie

    [...] 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] [...]

  • http://www.chlymidia.org Yasmine Dennis

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

  • http://fansibo.com/?p=240 The Ultimate Toolbox for iPhone Development | c'est la vie

    [...] 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. [...]

  • http://fansibo.com/?p=240 The Ultimate Toolbox for iPhone Development | c'est la vie

    [...] 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. [...]

  • http://kerempalabiyik.com/2010/02/27/iphone-uygulamalari-gelistirmek-isteyenler-icin-ucretsiz-100-kurs-ve-rehber/ iPhone uygulamaları geliÅŸtirmek isteyenler için ücretsiz 100 kurs ve rehber « Kerem PALABIYIK

    [...] 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] [...]

  • http://iphoneapp.us/the-complete-iphone-development-toolbox/ The Complete iPhone Development Toolbox | iPhoneApp Dev Blog

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

  • http://iphone.maxi-pulsa.com/?p=327 Code for Sending email from your iPhone App | iphone place

    [...] 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. [...]

  • http://www.olasz-ales.com alessign

    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];
    }

  • http://6050403020.com/ Alfonzo Brancati

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

  • jeff

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

  • http://mybirdlists.ginasfamilystore.com gina

    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.

  • http://watchmacgruberonlinefree.wetpaint.com Larry Callis

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

  • http://www.codeobsessed.com Coder

    Thanks for posting the info on this app!

  • http://gadgetax.com Krystina Settlemires

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

  • http://www.theapplelounge.com/tutorial/app-development-per-ios-i-tutorial/ App development per iOS, i tutorial – TheAppleLounge

    [...] 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. [...]

  • Carol

    Why force the user to constantly leave your app????
    (I thought you wanted people do *USE* your app, instead.)

    Email can be sent directly from inside your app, instead.

  • Carol

    Feed that code the EURO character… and it still returns nothing/error.

  • siva

    Hi

    Have any one tested this sample code.if it works please let me know.for me its not working.
    i have added the following code

    NSString *url = [NSString stringWithFormat:@"mailto:foo@example.com"];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString: url]];
    NSLog(@”Notes Closed%@”,url);

    even i tried with the following :
    —————————————–
    NSString *url = [NSString stringWithFormat:@"mailto:?=foo@example.com"];

    Thanks & Regards

  • Danielle

    Carol – do you have resources or sample code to e-mail inside the app?

  • http://www.uwsp.edu/athletics/mbb/schedule.htm Schedule

    Best you should edit the post subject title iPhone Programming Tutorial – Using openURL To Send Email From Your App | iCodeBlog to something more suited for your webpage you create. I enjoyed the the writing however.

  • samar gupta

    hii,,

    thanks for doing best.
    this is good for sending mail but if I want retrive mail list or mail gata then what should I do for this…..

  • polo

    What the point to put some code into images!!! fucking dumbass

  • http://seo1sem2services3.blogspot.com/ atif yousuf

    Great Information and post! It is very informative and suggestible for the user of solar energy, May I think it can be beneficial in coming days…

  • http://www.rapidwriters.net/ Writing Custom Essay

    Hello !
    iPhone Programming Tutorial – Using openURL To Send Email From Your App Article is very Interesting Article
    i like it !!!

  • http://vendomiapple.com/2011/01/29/100-cursos-gratuitos-y-tutoriales-para-aspirantes-a-desarrolladores-de-app-para-iphone/ 100 cursos gratuitos y tutoriales para aspirantes a desarrolladores de App para iphone « Programacion « VENDO MI APPLE

    [...] 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] [...]

  • Nehal11

    I have downloaded project and tried to send mail but i am not receiving any email.I have tested through simulator.
    Is it like that i have to use device only and what i have to do if i want to do it using iphone simulator?

  • Ventura_332

    You have to use a device real!!

  • Jpatel

    hello it not worked on my mac i can not get mail….. if i change my id in to…

  • Minthos

    Hey, thanks for this and not to sound unappreciative but did you really have to make the code snippets images instead of text? Sure it looks nice but it’s highly resistant to copy+paste.

  • Rlsommer

    Please indicate which part goes into to .h and which into the .m
    I receive the message that SendEmailTo undeclared. Where and how is it to be declared?

  • Ajith

    @bbff8f65565fdf7298dd66e3ef5aff77:disqus @nehal :do you have your account configured on the device you are tryin to send the mail from ?

  • Ajith_ajith3

    and also it doesnt work on simulator, only on real devices as pointed out by @7c285ce480c502bdd4dfcd2c8b8d8968:disqus

  • chris

    4.3.3 iPad 1, nothing happens… a real device

    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:mailString]];NSLog(@”Supposing to be opening email [%@]“,mailString);2011-05-11 23:37:20.659 Toolbox[3276:707] Supposing to be opening email [mailto:?to=monemail@domaine:disqus .com&subject=iOS Device Infos&body=Model:%20iPad%0AVersion:%20Version%204.3.3%20(Build%208J3)%0AMemory:%20246%20MB%0AUptime:%203d%209h%2046min%0toolbox:%20%5B0.2%5D%202011.05.11%0AUnique%20ID:%0A5cbdxxxxxxx7e6d0c19d7f]

  • chris

    my problem was that I had “spaces in the Subject”.
    Thanks a lot for this, works fine on iPad1 and iPhone4, iOS 4.3.3 (but not in the simulator)

  • chris

    my problem was that I had “spaces in the Subject”.
    Thanks a lot for this, works fine on iPad1 and iPhone4, iOS 4.3.3 (but not in the simulator)

  • chris

    my problem was that I had “spaces in the Subject”.
    Thanks a lot for this, works fine on iPad1 and iPhone4, iOS 4.3.3 (but not in the simulator)

  • Janhavin

    I want to test the above functionality from iphone simulator,
    How can I test it?

  • Ajith-ajith3

    You cant test it on a Simulator as there is no account set up on the simulator and even if there is i dont think you can test it.. But give it a try
    Somethings dont work on simulator ..you need a real device to test it.
    And please do let us know it it worked out.

  • Ganesh

    can we send email from a third party server. They provided some url with .php extension. Please help me in this regard

  • Vaddi Subbu2011

    How to send to email from this. I could’t get the result.

  • http://www.mantrais.com/iphone-application-development.php iPhone App Development

    is this coding work work me if i want to send bulk mail from my apps??

blog comments powered by Disqus