View
logo
logo

Contatti

Labs Software Development 21 August 2014

Using Standard MessageUI to send an email

Writen by odc-admin

comments 0

This little code snippet is by far the fastest, and my preferred, way to send an email via the standard API provided by the iOS SDK (7+). It certainly helped me by saving me a lot of time when getting requests like “Hey can we make this email link clickable?”. GRRR!

1.First we import the MessagUI as follows

[objc]
#import <MessageUI/MessageUI.h>
[/objc]

2.We add the code to our class, so it can implement the following delegate

[objc]MFMailComposeViewControllerDelegate[/objc]

  1. Let’s create a class property like this one (give it whatever name you want, we prefer very “telling” and explicit names)

[objc]@property (strong, nonatomic)
MFMailComposeViewController *mailer;[/objc]

  1. Finally we implement the method in which to instantiate the

[objc]MFMailComposeViewController[/objc]

and compose the email

[objc]
-(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 can uncomment the following code if you have
* images to be inserted as attachments*/
// 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];

}
[/objc]

  1. And we certainly can’t leave the delegate

[objc]MFMailComposeViewControllerDelegate[/objc]

behind, so we’re going to implement the delegate method as follows, in order to have full control over the mail controller’s return values, after it has finished its work. Add this method to the class:

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

} else {
[self .mailer dismissViewControllerAnimated:YES completion:nil];
}
}
[/objc]

  1. Enjoy the results! 🙂

Tags :