fbpx

Using standard MessageUI to send an email

This little code snipped is by far the quickest way to send an email using standard iOS7 SDK. It has surely helped me out in saving me a lot of time when I was in need of responding to an “hey we could make this email link clickable”. GRRR!

1.First of all import MessageUI as follows

#import <MessageUI/MessageUI.h>

2.Have your class implement the

MFMailComposeViewControllerDelegate

3.create a class property like this (name whatever you like, we do prefer to have explicitly talking variable names)

@property (strong, nonatomic) 
             MFMailComposeViewController *mailer;

4.finally implement a method, in which you instantiate the

MFMailComposeViewController

and compose your mail

 
-(void) sendMailTo: (NSString *) recipient {
    self.mailer = [[MFMailComposeViewController alloc] init];
    self.mailer.mailComposeDelegate = self;

    [self.mailer setSubject:@"My Fabolous Subject"];

    NSArray *toRecipients = [NSArray arrayWithObjects:recipient, nil];
    [self.mailer setToRecipients:toRecipients];

    /* You might want to uncomment the following, if you
    * have images to attach */
    // UIImage *myImage = [UIImage imageNamed:@"myfabolousimage.png"];
    // NSData *imageData = UIImagePNGRepresentation(myImage);
    // [self.mailer addAttachmentData:imageData
    //              mimeType:@"image/png" fileName:@"myfabolousimage.png"];

    NSString *emailBody = @"";
    [self.mailer setMessageBody:emailBody isHTML:NO];

    [self presentViewController:self.mailer animated:YES completion:nil];

}

5.of course we can’t let the

MFMailComposeViewControllerDelegate

behind, so you should implement the following, in order to have the full control of the exiting values of the mail controller, after he finishes his job. Implement the following in your class:

-(void)mailComposeController:
                (MFMailComposeViewController *)controller
		didFinishWithResult:(MFMailComposeResult)result
		error:(NSError *)error {
    if (error) {

    } else {
        [self.mailer dismissViewControllerAnimated:YES completion:nil];
    }
}
  1. Enjoy the results ! 🙂
Related Posts
Comment

Leave Your Comment

*

*