如何从iPhone应用程序发送邮件?

时间:2011-02-09 09:13:30

标签: iphone objective-c mfmailcomposeviewcontroller

我尝试从我的应用发送邮件。我想输入(动态)收件人ID,ccid,sub和消息。

谢谢

Senthilkumar

2 个答案:

答案 0 :(得分:3)

iOS 3+上的

在视图控制器标题中导入#import。

然后:

-(void)showMailPanel {
    MFMailComposeViewController *mailComposeViewController = [[MFMailComposeViewController alloc] init];

        // only on iOS < 3
    //if ([MFMailComposeViewController canSendMail] == NO)
    //  [self launchMailApp]; // you need to 

    mailComposeViewController.mailComposeDelegate = self;
    [mailComposeViewController setToRecipients:[NSArray arrayWithObjects:@"email address1",@"email address 2",nil]];
    [mailComposeViewController setSubject:@"your subject"];
    [mailComposeViewController setMessageBody:@"your body" isHTML:YES];
    mailComposeViewController.delegate = self;
    [self.navigationController presentModalViewController:mailComposeViewController animated:YES];

    [mailComposeViewController release];

}


- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error 
{   
    // Notifies users about errors associated with the interface
    switch (result)
    {
        case MFMailComposeResultCancelled:
            NSLog(@"Result: canceled");
            break;
        case MFMailComposeResultSaved:
            NSLog(@"Result: saved");
            break;
        case MFMailComposeResultSent:
            NSLog(@"Result: sent");
            break;
        case MFMailComposeResultFailed:
            NSLog(@"Result: failed");
            break;
        default:
            NSLog(@"Result: not sent");
            break;
    }
    [controller dismissModalViewControllerAnimated:YES];
}

-(void)launchMailApp {
{
    NSString *recipients = @"dest_email";
    NSString *email = [NSString stringWithFormat:@"%@%@", recipients, subject];
    email = [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:email]];
}

答案 1 :(得分:2)

你需要这样的事情:

//Import this in your .h file
#import <MessageUI/MessageUI.h>

...

    MFMailComposeViewController *mailController = [[[MFMailComposeViewController alloc] init] autorelease];
    mailController.mailComposeDelegate = self;
    [mailController setSubject:[NSString stringWithFormat:@"Report a problem - #%@", yourUserID]];
    [mailController setToRecipients:[NSArray arrayWithObject:@"support@yourWebsite.com"]];
    [self presentModalViewController:mailController animated:YES];

此外,父视图控制器(委托)需要符合 MFMailComposeViewControllerDelegate 协议:

    - (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
        //Extra implementation here...
        [self dismissModalViewControllerAnimated:YES];
    }