I want to send an email from my iPhone application. I have heard that the iOS SDK doesn't have an email API. I don't want to use the following code because it will exit my application:
NSString *url = [NSString stringWithString: @"mailto:[email protected][email protected]&subject=Greetings%20from%20Cupertino!&body=Wish%20you%20were%20here!"]; [[UIApplication sharedApplication] openURL: [NSURL URLWithString: url]];
So how can I send an email from my app?
The first time you open the Mail app, you'll need to connect it with an existing email address. Select your email provider, then follow the instructions to connect your account with the Mail app. When you're done, you'll be able to send and receive emails from that account on your iPhone.
On iOS 3.0 and later you should use the MFMailComposeViewController
class, and the MFMailComposeViewControllerDelegate
protocol, that is tucked away in the MessageUI framework.
First add the framework and import:
#import <MessageUI/MFMailComposeViewController.h>
Then, to send a message:
MFMailComposeViewController* controller = [[MFMailComposeViewController alloc] init]; controller.mailComposeDelegate = self; [controller setSubject:@"My Subject"]; [controller setMessageBody:@"Hello there." isHTML:NO]; if (controller) [self presentModalViewController:controller animated:YES]; [controller release];
Then the user does the work and you get the delegate callback in time:
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error; { if (result == MFMailComposeResultSent) { NSLog(@"It's away!"); } [self dismissModalViewControllerAnimated:YES]; }
Remember to check if the device is configured for sending email:
if ([MFMailComposeViewController canSendMail]) { // Show the composer } else { // Handle the error }
MFMailComposeViewController is the way to go after the release of iPhone OS 3.0 software. You can look at the sample code or the tutorial I wrote.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With