您的位置:首页 > 移动开发

iPhone How-to:如何发送邮件

2011-04-11 18:02 555 查看
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];

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息