邮件 发送
在头文件中引入framework
- 加入#import <MessageUI/MessageUI.h> 到InAppEmailViewController.h
显示 MFMailComposeViewController UI
MFMailComposeViewController与其他view controller一样; 我们可以在InAppEmailViewController 使用presentModalViewController使其滑入屏幕。
替换InAppEmailController.m中的buttonPressed方法:
1
2 3 4 5 6 7 |
- (IBAction)buttonPressed {
MFMailComposeViewController *controller = [[MFMailComposeViewController alloc] init]; [controller setSubject:@"In app email..."]; [controller setMessageBody:@"...a tutorial from mobileorchard.com" isHTML:NO]; [self presentModalViewController:controller animated:YES]; [controller release]; } |
如果你此时运行程序,你一定会失望。“Send Email” 按钮被禁止了。启用它是十分容易,但我们一定要在iPhone或iPod Touch程序已经运行并设置好发送邮件后,才能这样做。在InAppEmailViewController.m的viewDidLoad方法下加入代 码:
1
2 3 4 |
- (void)viewDidLoad {
if ([MFMailComposeViewController canSendMail]) button.enabled = YES; } |
关闭MFMailComposeViewController UI
我们的任务差不多完成了。运行程序:按下按钮打开预填了示例信息的compose UI。在“To"处添上电邮地址然后运行。
我们还缺少一个部分:我们需要在什么时候关闭composer UI。 MFMailComposeViewControllerDelegate协议提供了一个回调机制帮助我们完成此任务。
要接收回调,我们需要:
- InAppEmailViewController遵循协议
- 将自身设定为接收回调的代理
- 实现回调方法
更新InAppEmailViewController.h以采用协议。修改如下:
1
2 3 4 5 6 7 8 9 |
#import <UIKit/UIKit.h>
@interface InAppEmailViewController : UIViewController <MFMailComposeViewControllerDelegate> { IBOutlet UIButton *button; } - (IBAction)buttonPressed; @end |
为设定自身为接收回调的代理,更新InAppEmailViewController.m中buttonPressed方法。修改如下:
1
2 3 4 5 6 7 8 9 |
- (IBAction)buttonPressed
{ MFMailComposeViewController *controller = [[MFMailComposeViewController alloc] init]; controller.mailComposeDelegate = self; [controller setSubject:@"In app email..."]; [controller setMessageBody:@"...a tutorial from mobileorchard.com" isHTML:NO]; 加入HTML NSString *body = @”<h1>Check this out</h1><p>I selected this image from the <code><b>UIImagePickerController</b></code>.</p>”; [self presentModalViewController:controller animated:YES]; [controller release]; } |
最后,实现回调方法。将mailComposeController:didFinishWithResult:error:方法加入InAppEmailViewController.m:
1
2 3 4 5 6 |
- (void)mailComposeController:(MFMailComposeViewController*)controller
didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error { [self becomeFirstResponder]; [self dismissModalViewControllerAnimated:YES]; } |
MFMailComposeViewController发送邮件的实例
http://blog.csdn.net/bl1988530/article/details/6597230