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…
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.
Advertisement
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.
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!
- Posted by brandontreb on 20 Feb 2009 in iPhone Programming Tutorials
- Digg |
- Del.icio.us |
- Stumble |
- 55 Comments »
55 Responses
Todd Says:
February 20th, 2009 at 4:22 pm
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?
Mark H. Delfs Says:
February 20th, 2009 at 8:34 pm
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.
Code for Sending email from your iPhone App | iphonedevelopmentbits Says:
February 21st, 2009 at 8:19 am
[...] 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. [...]
Hardy Macia Says:
February 21st, 2009 at 9:43 am
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
MyPicture and friend Says:
February 23rd, 2009 at 1:34 am
nice post, friend.please come to my blog to see MY picture and friend
Félix Simões Says:
February 23rd, 2009 at 6:06 pm
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 Says:
February 25th, 2009 at 5:02 am
It dosn’t work
Unsuported URL
“This URL wasn’t loaded: mailto:?to=******@yahoo.fr&subject=test&body=Check%20ou%20iCodeBlog.com!”
Why ?
Brandon Says:
February 25th, 2009 at 5:48 pm
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 Says:
February 27th, 2009 at 3:51 am
stringWithFormat:@”mailto:%@?cc=%@&subject=%@&body=%@
This is what works for me. I believe mailto: has to be followed by addresses and not a ?
JoshuaCaputo Says:
February 28th, 2009 at 11:18 am
this is pretty basic, but I guess it helps. I love your tuts
JoshuaCaputo Says:
February 28th, 2009 at 11:20 am
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,.
Christo Says:
March 1st, 2009 at 4:59 pm
Can the owner or webmaster of this site email me in regards to posting some of your tutorials on my site
Stuart Says:
March 8th, 2009 at 12:29 am
As another user asked, can it load attachments like the photo library does?
moss Says:
March 11th, 2009 at 7:19 am
Hi!
What is the easiest way to install a program to my iphone, what i made in xcode?
Thanks
Milan Says:
March 14th, 2009 at 12:21 am
Hi,
Email not sending from simulator.You have any idea.whats problem occur.
bess Says:
March 24th, 2009 at 5:44 pm
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];
iPhone development Tutorials « The Brook Song - ঝর্ণার গান Says:
March 24th, 2009 at 11:52 pm
[...] 38. Send email [...]
Tung Do Says:
April 7th, 2009 at 8:36 pm
The tag in mail’s body is disappeared in Mail app. How do it happen ?
John Says:
April 10th, 2009 at 10:46 am
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 Says:
April 10th, 2009 at 4:40 pm
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…
100 Free Courses & Tutorials for Aspiring iPhone App Developers | Best Universities Says:
April 21st, 2009 at 3:04 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] [...]
100% Free Iphone Says:
April 23rd, 2009 at 3:24 am
I just love your weblog! Very nice post! Still you can do many things to improve it.
MattjDrake Says:
April 24th, 2009 at 2:10 pm
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.
Scott Says:
May 5th, 2009 at 5:28 pm
It doesn’t work in iPhone simulator since there is no Mail.app
It will work on the iPhone.
Peter Says:
May 9th, 2009 at 9:38 pm
How do you email multiple addresses without having to have multiple text areas like if I typed “peter” it would email to
Rupnarayan Says:
May 20th, 2009 at 6:23 am
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.
Poppy Keant Says:
June 4th, 2009 at 7:10 pm
I’m definitely bookmarking this site. Really great articles. Do you recommend any other readings?
Lakshmikanth Says:
June 8th, 2009 at 6:14 am
after using the “openURL” method and sent message using mailto, how to come back to the application.
Christian Fries Says:
June 11th, 2009 at 1:11 pm
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).
Watch Year One Online Free Says:
June 20th, 2009 at 1:47 pm
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.
mweeza Says:
June 26th, 2009 at 9:22 am
I got an iPod touch a couple of days ago but I think I had better bought an iPhone
200ml » 100 Free courses for iPhone Dev Says:
June 28th, 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] [...]
Rafael Says:
July 2nd, 2009 at 6:46 pm
I was wondering if there is a way to send a photo attached to the mail.
Thanks!
100 ресурсов для iPhone-разработчиков - Краковецкий Александр: заметки программиста - iPhone Community в Украине Says:
July 5th, 2009 at 6:23 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] [...]
cheebs Says:
July 14th, 2009 at 10:00 am
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 Says:
July 16th, 2009 at 5:57 pm
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 Says:
July 17th, 2009 at 12:51 pm
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 Says:
July 26th, 2009 at 5:13 pm
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
Extenze Says:
August 3rd, 2009 at 12:06 pm
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’.
Some Great Resources! | My First iPhone Application Says:
October 20th, 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] [...]
Online Business Management Software and Services » Blog Archive » The Ultimate Toolbox for iPhone Development Says:
November 20th, 2009 at 4:54 pm
[...] 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. [...]
The Ultimate Toolbox for iPhone Development - Creative Solutions Says:
November 24th, 2009 at 1:58 am
[...] 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. [...]
Enlaces para desarrollar en el iPhone | El mundo de IMD Says:
November 30th, 2009 at 1:51 am
[...] 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 Says:
December 16th, 2009 at 10:44 pm
Hi,
How can I add attachment if I use openurl mailto?
-Nat
100 Free Courses & Tutorials for Aspiring iPhone App Developers | c'est la vie Says:
December 31st, 2009 at 7:43 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] [...]
Yasmine Dennis Says:
January 13th, 2010 at 4:47 am
The iphone is still on my shopping list. I wish the price would go down a bit so I could afford one.
The Ultimate Toolbox for iPhone Development | c'est la vie Says:
February 1st, 2010 at 7:57 pm
[...] 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. [...]





