How to send an email in iOS

- by

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:@"", @"", 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];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Failure"
                                                        message:@"Your device doesn't support the composer sheet"
        [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).

If you enjoy my content, please consider supporting me on Ko-fi. In return you can browse this whole site without any pesky ads! More details here.

Leave a Comment!

This site uses Akismet to reduce spam. Learn how your comment data is processed.