使用mailto:URL发送电子邮件

时间:2012-01-26 01:36:14

标签: ios cocoa-touch cocoa mfmailcomposeviewcontroller

有人可以帮助我使用以下代码吗?对于在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]];

这是一个可靠的发送邮件的代码吗?

3 个答案:

答案 0 :(得分:6)

如果这是针对IOS 3.0+,那么MFMailCompseViewController

    #import <MessageUI/MFMailComposeViewController.h>
  //  ....

        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];
 }

答案 1 :(得分:2)

你真的应该使用MFMailComposeViewController。它让您熟悉应用程序并使您的代码更具可读性。

答案 2 :(得分:2)

为了扩展所提供的答案,我想补充一点,mailto方法有一个好处,那就是你不必检查用户是否能够发送电子邮件。如果用户无法做到,它将通过电子邮件向导提示用户,允许他/她使用默认的Apple邮件应用程序设置电子邮件帐户。

如果是MFMailComposeViewController,您应该始终检查用户是否可以使用canSendMail方法发送电子邮件,并采取相应的行动。

我还要注意,mailto方法不允许您直接设置委托,使错误处理更加棘手。

相关问题