iOS
Email

Modified

Overview

Email client is must implement:

MFMailComposeViewControllerDelegate

and define method:

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

Must import add MessageUI.framework framework.

Works only on real devices, not emulator.

Need an email account setup on the device.

Can add attachments with application results rather than storing on a server, alleviates the need to maintain external infrastructure.

 

Example

Download

First test that MFMailComposeViewController can send mail, displaying an alert if not configured.

Create an instance:

MFMailComposeViewController *mailController.

Set delegate:

mailController.mailComposeDelegate=self;

MFMailComposeViewController handles user interaction to compose and send mail.

[mailController autorelease] for delayed rather than release immediately.

emailViewController
#import <UIKit/UIKit.h>
#import <MessageUI/MessageUI.h>

@interface emailViewController : UIViewController <MFMailComposeViewControllerDelegate>
-(IBAction) sendButton: (id) sender;
@end

#import "emailViewController.h"

@implementation emailViewController

-(IBAction) sendButton: (id) sender {
	if(![MFMailComposeViewController canSendMail]) {
		UIAlertView *cantMailAlert=[[UIAlertView alloc] 
                                    initWithTitle:@"Can't mail" 
                                    message:@"This device not configured for email."
                                    delegate: NULL
                                    cancelButtonTitle:@"Dismiss"
                                    otherButtonTitles:NULL];
		[cantMailAlert show];
		[cantMailAlert release];
		return;
	}

	NSArray *toRecipients = [[NSArray alloc] initWithObjects: @"user1@fakehost.com", @"user2@fakehost.com", nil];
	NSArray *ccRecipients = [[NSArray alloc] initWithObjects: @"user3@fakehost.com", @"user4@fakehost.com", nil];
	
	MFMailComposeViewController *mailController = [[[MFMailComposeViewController alloc] init] autorelease];

	[mailController setSubject:@"My subject"];
	[mailController setToRecipients:toRecipients];
	[mailController setCcRecipients:ccRecipients];
	[mailController setBccRecipients:nil];
	[mailController setMessageBody: @"My message" isHTML:NO];

	mailController.mailComposeDelegate=self;

	[self presentModalViewController:mailController animated:YES];

	[toRecipients release];
	[ccRecipients release];
}
											// Send or Cancel clicked
- (void)mailComposeController:(MFMailComposeViewController*)controller 
		  didFinishWithResult:(MFMailComposeResult)result  error:(NSError*)error {

	[controller dismissModalViewControllerAnimated:YES];
}

@end