Archive for April 19th, 2009

Snippet: Building mailtos

Ever got some strange results trying to send emails on the iPhone? Yeah, us too. Here’s a workaround that may help — use the Core Foundation utilities instead of using NSString for everything:

This simple approach ensures that your full message will arrive properly at the iPhone mail program after you have your application open the merged URL. Escaping the html body text ensures that mailto: specific characters will not confuse the URL handler and that your e-mail will be built with the proper headers and body.

NSString *htmlBody = @"you probably want something HTML-y here";  
  
// First escape the body using a CF call  
NSString *escapedBody = [(NSString*)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)htmlBody, NULL,  CFSTR("?=&+"), kCFStringEncodingUTF8) autorelease];

// Then escape the prefix using the NSString method  
NSString *mailtoPrefix = [@"mailto:?subject=Some Subject&body=" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];  
  
// Finally, combine to create the fully escaped URL string  
NSString *mailtoStr = [mailtoPrefix stringByAppendingString:escapedBody];  

// And let the application open the merged URL  
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:mailtoStr]];

Now you know!

Continue Reading →
0