使用mailto:URL发送电子邮件
有人可以帮助我使用以下代码吗? 对于在iOS中发送电子邮件,下面的代码是好的还是我应该使用MFMailComposeViewController而不是这个?:
NSString *url = [NSString stringWithString: @"mailto:foo@example.com?cc=bar@example.com&subject=Greetings%20from%20Cupertino!&body=Wish%20you%20were%20here!"]; [[UIApplication sharedApplication] openURL: [NSURL URLWithString: url]];NSString *url = [NSString stringWithString: @"mailto:foo@example.com?cc=bar@example.com&subject=Greetings%20from%20Cupertino!&body=Wish%20you%20were%20here!"]; [[UIApplication sharedApplication] openURL: [NSURL URLWithString: url]];
它是一个可靠的发送邮件的代码吗?
如果这是针对IOS 3.0+然后MFMailCompseViewController
#import // .... MFMailComposeViewController* controller = [[MFMailComposeViewController alloc] init]; controller.mailComposeDelegate = self; [controller setSubject:@"My Subject"]; [controller setMessageBody:@"Hello there." isHTML:NO]; if (controller) [self presentModalViewController:controller animated:YES]; [controller release];
然后用户完成工作,并及时获得委托回调:
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error; { if (result == MFMailComposeResultSent) { NSLog(@"sent"); } [self dismissModalViewControllerAnimated:YES]; }
你真的应该使用MFMailComposeViewController。 它使您保持在应用程序中,使您的代码更具可读性。
为了扩展所提供的答案,我想补充说, mailto
方法有一个好处,那就是你不必检查用户是否能够发送电子邮件。 如果用户无法做到,它将通过电子邮件向导提示用户,允许他/她使用默认的Apple邮件应用程序设置电子邮件帐户。
对于MFMailComposeViewController
,您应始终检查用户是否可以使用canSendMail
方法发送电子邮件,并采取相应措施。
我还要注意, mailto
方法不允许您以直接的方式设置委托,使error handling更加棘手。