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

    February 20th, 2009 Posted by: - 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…


    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.


    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 . You can also download the source here.

    Happy iCoding!