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:@"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).

Add your voice!

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