How can I send mail from an iPhone application

前端 未结 11 1864
甜味超标
甜味超标 2020-11-22 11:47

I want to send an email from my iPhone application. I have heard that the iOS SDK doesn\'t have an email API. I don\'t want to use the following code because it will exit my

11条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 12:14

    On iOS 3.0 and later you should use the MFMailComposeViewController class, and the MFMailComposeViewControllerDelegate protocol, that is tucked away in the MessageUI framework.

    First add the framework and import:

    #import 
    

    Then, to send a message:

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

    Then the user does the work and you get the delegate callback in time:

    - (void)mailComposeController:(MFMailComposeViewController*)controller  
              didFinishWithResult:(MFMailComposeResult)result 
                            error:(NSError*)error;
    {
      if (result == MFMailComposeResultSent) {
        NSLog(@"It's away!");
      }
      [self dismissModalViewControllerAnimated:YES];
    }
    

    Remember to check if the device is configured for sending email:

    if ([MFMailComposeViewController canSendMail]) {
      // Show the composer
    } else {
      // Handle the error
    }
    

提交回复
热议问题