Search code examples
iosobjective-cmfmailcomposeviewcontroller

How to send mail from a custom UITableViewCell using MFMailComposerViewController


I want to send mail while clicking a button in a custom UITableViewCell using MFMailComposeViewController.

Appreciate if answer is in Objective-C.


Solution

  • Following code in your .h file

    #import <MessageUI/MFMailComposeViewController.h>

    Give Delegate <MFMailComposeViewControllerDelegate>

    Following code in your .m file

    //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:@"[email protected]"]];
            [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;
        }
    }
    

    You can dismiss view by this code - [self dismissViewControllerAnimated:YES completion:nil];