发送邮件--MFMailComposeViewController
只能在真机使用.
模拟器没有E-mail发送功能.无法调用
#import "EmailViewController.h"
#import <UIKit/UIKit.h>
#import <MessageUI/MFMailComposeViewController.h>
@interface EmailViewController ()<MFMailComposeViewControllerDelegate>
@end
@implementation EmailViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
btn.frame=CGRectMake(20, 100, 200, 100);
[btn addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
}
-(void)click
{
Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
if (!mailClass) {
[self alertWithMessage:@"当前系统版本不支持应用内发送邮件功能,您可以使用mailto方法代替"];
return;
}
if (![mailClass canSendMail]) {
[self alertWithMessage:@"用户没有设置邮件账户"];
return;
}
[self displayMailPicker];
}
- (void)displayMailPicker
{
MFMailComposeViewController *mailPicker = [[MFMailComposeViewController alloc] init];
mailPicker.mailComposeDelegate = self;
//设置主题
[mailPicker setSubject: @"主题"];
//添加收件人
NSArray *toRecipients = [NSArray arrayWithObject: @"liuliuliu@hotmail.com"];
[mailPicker setToRecipients: toRecipients];
//添加抄送
//NSArray *ccRecipients = [NSArray arrayWithObjects:@"second@example.com", @"third@example.com", nil];
//[mailPicker setCcRecipients:ccRecipients];
//添加密送
//NSArray *bccRecipients = [NSArray arrayWithObjects:@"fourth@example.com", nil];
//[mailPicker setBccRecipients:bccRecipients];
// 添加一张图片
UIImage *addPic = [UIImage imageNamed: @"Icon@2x.png"];
NSData *imageData = UIImagePNGRepresentation(addPic); // png
//关于mimeType:http://www.iana.org/assignments/media-types/index.html
[mailPicker addAttachmentData: imageData mimeType: @"" fileName: @"Icon.png"];
NSString *emailBody = @"<font color='red'>eMail</font> 正文";
[mailPicker setMessageBody:emailBody isHTML:YES];
//[self presentModalViewController: mailPicker animated:YES];
[self presentViewController:mailPicker animated:YES completion:nil];
}
#pragma mark - 实现 MFMailComposeViewControllerDelegate
- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
//关闭邮件发送窗口
//[self dismissModalViewControllerAnimated:YES];
[self dismissViewControllerAnimated:YES completion:nil];
NSString *msg;
switch (result) {
case MFMailComposeResultCancelled:
msg = @"用户取消编辑邮件";
break;
case MFMailComposeResultSaved:
msg = @"用户成功保存邮件";
break;
case MFMailComposeResultSent:
msg = @"用户点击发送,将邮件放到队列中,还没发送";
break;
case MFMailComposeResultFailed:
msg = @"用户试图保存或者发送邮件失败";
break;
default:
msg = @"";
break;
}
[self alertWithMessage:msg];
}
- (void)alertWithMessage:(NSString*)message
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil
message:message
delegate:nil
cancelButtonTitle:@"确定"
otherButtonTitles:nil, nil];
[alert show];
}
posted on 2014-06-14 16:17 Sinner_Yun 阅读(215) 评论(0) 编辑 收藏 举报