How to send an email in iOS

This is tricky but doable. We’re using the MFMailComposeViewController protocol for this (don’t ask). This will open the mail app on your device. Older devices without mail sending capability will crash when you call this method so we’ll check before we do this.

    if ([MFMailComposeViewController canSendMail])
    {
        MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];
        
        mailer.mailComposeDelegate = self;
        
        [mailer setSubject:@"I've written a frigging Masterpiece!"];
        
        NSArray *toRecipients = [NSArray arrayWithObjects:@"email1@you.com", @"email2@you.com", nil];
        [mailer setToRecipients:toRecipients];
        
        UIImage *myImage = [UIImage imageNamed:@"yourimage.png"];
        NSData *imageData = UIImagePNGRepresentation(myImage);
        [mailer addAttachmentData:imageData mimeType:@"image/png" fileName:@"yourimage.png"];
        
        NSString *emailBody = self.emailField.text;
        [mailer setMessageBody:emailBody isHTML:NO];
        
        mailer.modalPresentationStyle = UIModalPresentationPageSheet;
        [self presentModalViewController:mailer animated:YES];
        
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Failure"
                                                        message:@"Your device doesn't support the composer sheet"
                                                       delegate:nil
                                              cancelButtonTitle:@"Darn!"
                                              otherButtonTitles:nil];
        [alert show];
    }

For this action to work the View Controller calling it needs to confirm to the MFMailComposeViewController protocol so we need to set this in our ViewController.h file. We also need to import the MessageUI Framework:

#import <MessageUI/MessageUI.h>
@interface ViewController : UIViewController <MFMailComposeViewControllerDelegate>

Don’t forget to add the framework itself via Build Phases (explained next).





Jay is the CEO and founder of WP Hosting, a boutique style managed WordPress hosting and support service. He has been working with Plesk since version 9 and is a qualified Parallels Automation Professional. In his spare time he likes to develop iOS apps and WordPress plugins, or draw on tablet devices. He blogs about his coding journey at http://wpguru.co.uk and http://pinkstone.co.uk.