发送邮件使用MFMailComposeViewController来显示界面
1、添加框架、导入头文件,及设置代理
1-1、MessageUi.framework
1-2、#import <MessageUI/MessageUI.h>
1-3、MFMailComposeViewControllerDelegate
2、发送邮件调用方法
- (void)sendEMail
{
Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
if (mailClass)
{
if ([mailClass canSendMail])
{
[self displayComposerSheet];
}
else
{
[self launchMailAppOnDevice];
}
}
else
{
[self launchMailAppOnDevice];
}
}
// 可以发送邮件的话
- (void)displayComposerSheet
{
MFMailComposeViewController *mailPicker = [[MFMailComposeViewController alloc] init];
mailPicker.mailComposeDelegate = self;
// 设置主题
[mailPicker setSubject:@"eMail主题"];
// 添加发送者
NSArray *toRecipients = [NSArray arrayWithObject:@"[email protected]"];
// NSArray *ccRecipients = [NSArray arrayWithObjects:@"[email protected]", @"[email protected]", nil];
// NSArray *bccRecipients = [NSArray arrayWithObject:@"[email protected]", nil];
[mailPicker setToRecipients: toRecipients];
// [picker setCcRecipients:ccRecipients];
// [picker setBccRecipients:bccRecipients];
// 添加图片
UIImage *addPic = [UIImage imageNamed:@"123.jpg"];
NSData *imageData = UIImagePNGRepresentation(addPic); // png
// NSData *imageData = UIImageJPEGRepresentation(addPic, 1); // jpeg
[mailPicker addAttachmentData: imageData mimeType:@"" fileName:@"123.jpg"];
NSString *emailBody = @"eMail 正文";
[mailPicker setMessageBody:emailBody isHTML:YES];
[self presentModalViewController:mailPicker animated:YES];
}
- (void)launchMailAppOnDevice
{
NSString *recipients = @"mailto:[email protected]&subject=my email!";
//@"mailto:[email protected][email protected],[email protected]&subject=my email!";
NSString *body = @"&body=email body!";
NSString *email = [NSString stringWithFormat:@"%@%@", recipients, body];
email = [email stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
[[UIApplication sharedApplication] openURL: [NSURL URLWithString:email]];
}
3、代理回调方法
- (void)mailComposeController:(MFMailComposeViewController *)controller
didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
switch (result)
{
case MFMailComposeResultCancelled:NSLog(@"邮件发送取消");break;
case MFMailComposeResultSaved:NSLog(@"邮件保存成功");break;
case MFMailComposeResultSent:NSLog(@"邮件发送成功");break;
case MFMailComposeResultFailed:NSLog(@"邮件发送失败");break;
default:break;
}
[self dismissModalViewControllerAnimated:YES];
}