iPhone提供了内嵌的Mail应用以支持电子邮件相关操作,此外还提供了MFMailComposeViewController以实现了在当前应用内编辑和发送邮件。使用内嵌的Mail应用还是MFMailComposeViewController就取决于实际的需求了,实现方法分别是:
- 调用内嵌Mail应用
- (void) sendEmailTo:(NSString *)to withSubject:(NSString *)subject withBody:(NSString *)body {
NSString *mailString = [NSString stringWithFormat:@"mailto:?to=%@&subject=%@&body=%@",
[to stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding],
[subject stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding],
[body stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:mailString]];
}
需要注意的是这里使用了NSString的stringByAddingPercentEscapesUsingEncoding接口,其作用就是在URL字符串中进行特殊字符的替换,比如将空格替换成%20之类的。
- 使用MFMailComposeViewController支持应用内邮件发送
- (IBAction)sendMail{
MFMailComposeViewController *controller = [[MFMailComposeViewController alloc] init];
controller.mailComposeDelegate = self;
[controller setSubject:@"In app email..."];
[controller setMessageBody:@"...a tutorial from mobileorchard.com" isHTML:NO];
[self presentModalViewController:controller animated:YES];
[controller release];
}
此外还需要实现mailComposeController:didFinishWithResult:error:的协议以进行发送成功或者失败后的处理:
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
...
[self dismissModalViewControllerAnimated:YES];
}
转载于:https://blog.51cto.com/bj007/541675