郵件發送功能是由MessageUI Framework提供的,這個架構是iPhone sdk中最簡單的框。由一個類、一個視圖控制器,一個protocol組成。
一、建立視圖控制器:
MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init]; mc.mailComposeDelegate = self;
二、設定郵件主題:
[mc setSubject:@"Hello, World!"];
三、設定收件者,收件者有三種:
1、設定主收件者
[mc setToRecipients:[NSArray arrayWithObjects:@"zhuqi0@126.com", "@dave@iphonedevbook.com", nil];
2、設定cc
[mc setCcRecipients:[NSArray arrayWithObject:@"zhuqil@163.com"]];
3、設定bcc
[mc setBccRecipients:[NSArray arrayWithObject:@"secret@gmail.com"]];
四、設定郵件主體,有兩種格式。
一種是純文字
[mc setMessageBody:@"Watson!!!\n\nCome here, I need you!" isHTML:NO];
一個是html格式
[mc setMessageBody:@"<HTML><B>Hello, Joe!</B><BR/>What do you know?</HTML>" isHTML:YES];
五、添加附件
添加附件需要三個參數,一個是NSData類型的附件,一個是mime type,一個附件的名稱。
NSString *path = [[NSBundle mainBundle] pathForResource:@"blood_orange"
ofType:@"png"];
NSData *data = [NSData dataWithContentsOfFile:path];
[mc addAttachmentData:data mimeType:@"image/png" fileName:@"blood_orange"];
六、視圖呈現
[self presentModalViewController:mc animated:YES];
[mc release];
七、視圖控制器的委託方法
郵件視圖控制器的委託方法包含在MFMailComposeViewControllerDelegate中,無論使用者是否發送或取消發送,不論系統是否能夠發送郵件,
方法 mailComposeController:didFinishWithResult:error: gets called都會被調用。
- (void)mailComposeController:(MFMailComposeViewController*)controller
didFinishWithResult:(MFMailComposeResult)result
error:(NSError*)error {
switch (result)
{
case MFMailComposeResultCancelled:
NSLog(@"Mail send canceled...");
break;
case MFMailComposeResultSaved:
NSLog(@"Mail saved...");
break;
case MFMailComposeResultSent:
NSLog(@"Mail sent...");
break;
case MFMailComposeResultFailed:
NSLog(@"Mail send errored: %@...", [error localizedDescription]);
break;
default:
break;
}
[self dismissModalViewControllerAnimated:YES];
}