如何使用MFMailComposerViewController从自定义UITableViewCell发送邮件

时间:2019-05-27 06:50:52

标签: ios objective-c mfmailcomposeviewcontroller

我想在使用UITableViewCell单击自定义MFMailComposeViewController中的按钮时发送邮件。

了解答案是否在Objective-C中。

2 个答案:

答案 0 :(得分:0)

.h文件中的以下代码

#import <MessageUI/MFMailComposeViewController.h>

给予委托<MFMailComposeViewControllerDelegate>

.m文件中的以下代码

//Where you want to open dialog write below code

if([MFMailComposeViewController canSendMail]) {
        MFMailComposeViewController *mailCont = [[MFMailComposeViewController alloc] init];
        mailCont.mailComposeDelegate = self; // Required to invoke mailComposeController when send

        [mailCont setSubject:@"Your Subject!"];
        [mailCont setToRecipients:[NSArray arrayWithObject:@"hello@test.com"]];
        [mailCont setMessageBody:@"Your Body" isHTML:NO];

        [self presentViewController:mailCont animated:YES completion:nil];
    }

//Delegate Method

- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    switch (result)
    {
        case MFMailComposeResultCancelled:
            //YOUR ACTION
            break;
        case MFMailComposeResultSent:
            //YOUR ACTION
            break;
        case MFMailComposeResultSaved:
            //YOUR ACTION
            break;
        case MFMailComposeResultFailed:
            //YOUR ACTION
            break;
        default:
            break;
    }
}

您可以通过以下代码关闭视图-[self dismissViewControllerAnimated:YES completion:nil];

答案 1 :(得分:0)

确保在Real设备中而不是在模拟器中进行测试,并且在设备中配置了邮件ID

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

@interface ViewController ()<MFMailComposeViewControllerDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (IBAction)sendmail:(id)sender {

    if ([MFMailComposeViewController canSendMail])
    {
            MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];
            mailer.mailComposeDelegate = self;
            [mailer setSubject:@"Subject"];
            NSArray *toRecipients = [NSArray arrayWithObjects:@"Recipients", nil];
            [mailer setToRecipients:toRecipients];
            NSString *emailBody = @"Body";
            [mailer setMessageBody:emailBody isHTML:NO];
            [self presentViewController:mailer animated:YES completion:nil];
    }
}

- (void) mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{

    // Close the Mail Interface
    [self dismissViewControllerAnimated:NO completion:NULL];
}