我想用我的iPhone应用程序发送一封电子邮件。我听说iOS SDK没有电子邮件API。我不想使用下面的代码,因为它将退出我的应用程序:
NSString *url = [NSString stringWithString: @"mailto:foo@example.com?cc=bar@example.com&subject=Greetings%20from%20Cupertino!&body=Wish%20you%20were%20here!"];
[[UIApplication sharedApplication] openURL: [NSURL URLWithString: url]];
那么我如何从我的应用程序发送电子邮件呢?
下面的代码在我的应用程序中用于发送带有附件的电子邮件这里的附件是一张图片,你可以发送任何类型的文件唯一需要记住的是你必须指定正确的mimeType
将此添加到.h文件中
#import <MessageUI/MFMailComposeViewController.h>
将MessageUI.framework添加到项目文件中
NSArray *paths = SSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:@"myGreenCard.png"];
MFMailComposeViewController* controller = [[MFMailComposeViewController alloc] init];
controller.mailComposeDelegate = self;
[controller setSubject:@"Green card application"];
[controller setMessageBody:@"Hi , <br/> This is my new latest designed green card." isHTML:YES];
[controller addAttachmentData:[NSData dataWithContentsOfFile:getImagePath] mimeType:@"png" fileName:@"My Green Card"];
if (controller)
[self presentModalViewController:controller animated:YES];
[controller release];
委托方法如下所示
-(void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error;
{
if (result == MFMailComposeResultSent) {
NSLog(@"It's away!");
}
[self dismissModalViewControllerAnimated:YES];
}