Thursday, May 13, 2010

iPhone: How to Open the Mail App With a Pre-Composed HTML Email

Have you ever wanted to open the Mail app with a pre-composed email? Then today’s iPhone development tip is the one for you! This has many uses, but a common one is a tell-a-friend feature in apps. If you attach the code from this tip to a button, you can give your users a way to promote your app to their friends via the iPhone’s built in Mail app.

A Handy Function
The sendEmailTo function, seen below, can be included in any view controller of your app. This function gives you a simple interface to send emails. It allows you to define “to” addresses, “cc” addresses, “bcc” addresses, a subject and a body. The body supports HTML tags.

- (void)sendEmailTo:(NSString*)to withCC:(NSString*)cc withBCC:(NSString*)bcc withSubject:(NSString*)subject withBody:(NSString*)body {
NSString * url = [NSString stringWithFormat:@"mailto:?to=%@&cc=%@&bcc=%@&subject=%@&body=%@",
[to stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding],
[cc stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding],
[bcc stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding],
[subject stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding],
[body stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
}


PS: Running this function in the iPhone Simulator will have no effect because the simulator does not include the iPhone’s Mail app. To see the effects of this function, it must be run on a device.

Example
The following example opens the Mail app and pre-populates the to, cc, bcc and other fields in it.
[self sendEmailTo:@"friend@example.com"
withCC:@"relative@example.com"
withBCC:@"secret-friend@example.com"
withSubject:@"Blog"
withBody:@"Check out my new blog, here."];


You could also leave some of these fields blank if you want user to specify and fill those.
[self sendEmailTo:@""
withCC:@""
withBCC:@""
withSubject:@"Blog"
withBody:@"Check out my new blog, here"];