RSS feed

Nutsmuggling

iPhone SDK: sending formatted email

As a part of an iPhone app I’m presently working on1 I was confronted with an apparently simple problem, which turned out to be more difficult than I thought.
Except it was simple, once you knew how to do it.

Question

How do I send a tabular report via e-mail in the iPhone SDK?

Short answer

Use a mailto url + stringByAddingPercentEscapesUsingEncoding + HTML.

Longer answer

So far (iPhone OS 2.2) the de facto way to send e-mail on your iPhone application is using a mailto url.2

NSURL *url = [[NSURL alloc] initWithString:
@"mailto:me@me.com?subject=subject&body=Hi"];
[[UIApplication sharedApplication] openURL:url];

Of course you can use a format to include your own dynamic text, but the url string must be url escaped. Cocoa(Touch) provides a nice way to escape URLs, stringByAddingPercentEscapesUsingEncoding:

NSString *encodedBody = [eMailBody stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

The only problem left was representing tabular data. At first I though I’d use \t to create tabs, but I found out they’re not properly supported in e-mail bodies. Then a discussion on the Google Groups gave me the hint, the body parameter of mailto is actually parsed as HTML.
So, amazing as it seems, this code works:

NSString *eMailBody = @"<table>
<tr><td style='text-align:right'><b>Name</b>:</td>
<td>John</td></tr><tr>
<td style='text-align:right'><b>Surname</b>:</td><td>Doe</td></tr>
<tr><td style='text-align:right'>
 <b>Occupation:<b/></td><td>Placeholder</td></tr></table>";
NSString *encodedBody = 
[eMailBody stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 
NSString *urlString = 
[NSString stringWithFormat:@"mailto:me@me.com?subject=HiPhone&body=%@", encodedBody];
NSURL *url = [[NSURL alloc] initWithString:urlString];
[[UIApplication sharedApplication] openURL:url];

And here’s the result:

IMG_0001.PNG

Bingo!

A weird downside of this method is that the user will be able to edit the email, but not is formatting: the bold characters will stay bold and so on; this seems to be a feature of the mail app itself.

Device vs Simulator

Since the iPhone simulator does not have a Mail.app, you can use e-mail URLs only in the actual device. As a matter of fact, it’s advisable to use compiler statements to create specific simulator/device code:

#if TARGETIPHONESIMULATOR
    //compiler specific code
#else
    // device specific code
#endif

In my app, I use a UIAlertView in the simulator code, so I can have the email text displayed onscreen. Currently I have a UITextView as its subview, but I plan to use a UIWebView, so I can preview the HTML in the simulator.

(Thanks to Slashzero for his comment)

Notes

  1. shush shush, too early to talk about it! []
  2. Please note that, although the mailto protocol might support attachments, you specify attachment with the sdk. I know, it’s a shame, but so far we’re not allowed to send attachments through mail. The alternative is writing your own smtp server, but refrain from doing it, unless the composed mail is sent without any user intervention, otherwise you’ll also have to write your own mail client. []
Share and Enjoy:
  • Digg
  • del.icio.us
  • Google
  • Technorati
  • StumbleUpon
  • Furl
  • Reddit

24 responses to “iPhone SDK: sending formatted email”

  1. Nicolas Zinovieff says:

    For attachments, how about mime-parts and base64 encoding? it shouldn’t be very hard to code. Then again the mailto: scheme might have a size limitation.

  2. Davide says:

    Hi Nicolas. I confess I haven’t tried to use mime-parts myself, but I am sure I read in some forum thread that the iPhone sdk mailto schemes actually do not support attachments. Again, I can’t say I have tried that myself, also because I haven’t implemented the pdf export of my app yet. By the way, I had a look at apps sending mail attachments. ComicTouch, for example, has its own mail client; the desktop version, ComicLife, sends e-mails through Apple’s Mail.app. I guess that if the ComicTouch developer had to implement their client and break with the practice of the desktop version there must be a reason; I guess that when I implement pdf export I’ll have to write my own SMTP client. Unless, hopefully, Apple adds some facility to send mails with attachments to the SDK…

  3. slashzero says:

    Hi,

    Using your code above, I get an error stating “Unsupported URL”

  4. slashzero says:

    Nevermind. The simulator does not have any mail apps, therefore doesn’t know how to handle the URL.

  5. Davide says:

    Correct, you can use e-mail URLs only in the actual device. As a matter of fact, it’s advisable to use compiler statements to create specific simulator device/simulator code:

    #if TARGETIPHONESIMULATOR
        //compiler specific code
    #else
        // device specific code
    #endif

    In my app, I use a UIAlertView in the simulator code, so I can have the email text displayed onscreen. Currently I have a textview inside it, but I plan to use a UIWebView, so I can preview the HTML in the simulator.

  6. Sam says:

    Hey there. I am new to iPhone development/objective-c/c/c++. Can you suggest me a book to read?

    This is a nice example. Thank you.

  7. Davide says:

    Hi Sam, I have only read the PragProg PDF book, it’s a good resource, and you can get it instantly by buying it online, here.
    Yet, the best resources are always Apple’s own docs and sample code.

  8. Dave says:

    Great solution! Thanks. Please also check out iPhoneToot.com for great getting started xcode iphone video tutorials.

    iPhoneToot.com

  9. Dreb says:

    Hi, great tutorial. Is there a way you could post the source code for this small app. Iv been trying for a while to get this working and still no luck. I guess I dont blame myself too bad since I am a newbie at working in xcode. The source code would help me reference my own mistakes better. Thanks again and keep up the good work.

  10. Davide says:

    Hi Dreb.
    This post has received a good deal of attention, I guess because, simple as this procedure is, the email sending process is quite undocumented.
    I guess I will follow your suggestion and write a short tutorial to illustrate this procedure better. Still, you’ll have to wait a bit, for I am in the middle of some Web development projects, I’ll put my hands back on iPhone development in a couple of weeks, hopefully.

    Davide

  11. Dreb says:

    Thanks, that would be great. You are right, I have founded nothing really on this topic. This is a bad thing when Im still really new to writing in xcode.

  12. Tharindu says:

    Hi, Thanks friend this helped me a lot, I wanted to send an html table, I initially thought I have to send it as an attachment, but this is what I really wanted. It works fine. Thanks again.

  13. Dreb says:

    Wow, I put this iphone proj I was workin on on hold for a bit. Its been almost a month…man time flies. Davide I was seeing if you might have anymore helpful info on this topic as my code still isnt working correctly (I think its still cause Im such a newbie at iphone development). Thanks again for a great tutorial and keep up the good work!

  14. Davide says:

    Hi Dreb. As a matter of fact, with the iPhone 3.0 OS this topic might be outdated; there are new improvements to the mail framework allowing (maybe) to attach files. At any rate, this project is indeed late, but presently iPhone development is what I do when I don’t have any job, so maybe it’s better :) But sooner or later I’ll be back on it, an I guess I’ll post something on 3.0, as soon ans the 3.0 NDA is lifted.

  15. codist says:

    I tried this but it stripped the entire html portion out when it was sent. However in the email I could see the image in the img tag, but when I got the email (on my mac) there was nothing.

  16. Davide says:

    I don’t think you can use this method to add images. Anyway, I can safely say that all of this is made obsolete by iPhone os 3.0. Davide

  17. Paul says:

    Great tutorial, thanks for this.

    Have you ever found an easy way to email something in the background without opening the Mail.app. Can this be done using an API call of some sort? I suspect 3.0 has something added.

  18. Jennifer R. says:

    You made some good points there. I did a search on the topic and found most people will agree with your blog.

  19. narendar says:

    Hello can we send the image in mail, the image will be in the local folder of the application.

    Please provide any sample code for this?

  20. acai says:

    Undeniably verifiable. Very promoting. Because I’m not a clear English author I really took the critiques seriously. I had a lot to progress. I found this article to be very helpful for my reading and batch information. Thank you for one of the most dynamic write ups I will plausibly ever find. I read a great deal in a short period of time. I savored the eye glaze phrases and mode and the power to tempo my reading.

  21. Racano says:

    barkod dedi?imizde bundan birka? y?l ?nce akl?m?za sadece ?izgiler ve bo?lukar gelirdi. Zaten t?rk?eye de ?izgi kod olarak uyarland?. Ama ?uanda teknolojinin geli?mesine paralel olarak, bir?ok barkod g?rseli varyasyonu ?retildi.

  22. Nelia Sloanes says:

    There’s obviously a great deal to know about this. I think you manufactured some beneficial factors in Characteristics also.

  23. Susann Holka says:

    lolol where’s a dark beer once you want one

  24. help stop drinking says:

    I’ve recently started a blog, the information you provide on this site has helped me

Leave a Reply