Send emails using MFMailComposer

Send emails with MFMailComposer

In this tutorial, I will show you how to send emails correctly in both Objective – C, and Swift using the native library MFMailComposerController.

Include the protocol MFMailComposeViewControllerDelegate.

Objective – C: 

-(void)sendEmail{
    MFMailComposeViewController* controller = [MFMailComposeViewController new];
    if ([MFMailComposeViewController canSendMail]){
        [controller setSubject:@"Set the subject here"];
        [controller setMessageBody:@"Set the message you want to send" isHTML:NO];
        [controller setToRecipients:@[@"support@theappspace.com"]];
        controller.mailComposeDelegate = self;
        [self presentViewController:controller animated:YES completion:nil];
    } else {
        // Doesn't supports email
    }
}

 

Callback for handling the state of the email:

#pragma mark - Mail delegate methods
- (void)mailComposeController:(MFMailComposeViewController*)controller
          didFinishWithResult:(MFMailComposeResult)result
                        error:(NSError*)error
{
    if (result == MFMailComposeResultSent) {
    // email sent
    }
    else if (result == MFMailComposeResultFailed) {
    //email not sent
    }
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

 

Swift:

func sendEmail(){
    let mailComposerVC = MFMailComposeViewController()
    mailComposerVC.mailComposeDelegate = self
    mailComposerVC.setToRecipients([""])
    mailComposerVC.setSubject("")
    mailComposerVC.setMessageBody(sign, isHTML: false)
    self.presentViewController(mailComposerVC, animated: true, completion: nil)
}

 

Callback for handling the state of the email:

// MARK: MFMailComposeViewControllerDelegate Method
func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
    controller.dismissViewControllerAnimated(true, completion: nil)
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *