Monday, 3 November 2008

iPhone development - Creating an Email with valid text!

When writing your iPhone application you may wish to send an email using the iPhone's built in mail client. This simple piece of code will do this:

NSURL* mailURL = [NSURL URLWithString: @"mailto:foo@example.com?cc=bar@example.com&subject=My%20Subject&body=bodyStuff"];
[[UIApplication sharedApplication] openURL: mailURL];

However, remember that the string must be correctly URL encoded. This is simple with a small string such as that in the example, but when creating a fairly long email, or constructing one from data in a loop for example.. this isn't so easy! If you replace mailURL in the final line with:

[mailURL stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]

then you can leave all the original space characters and slash n characters in with no problems!

1 comments:

Jürgen said...

This code doesn't work:

[mailURL stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]

mailURL must be a NSString - not NSURL

After changing that it works fine :)