一、使用iPhone系统自带邮件发送邮件
1. MFMailComposeViewController(原生)——使用模态跳转出邮件发送界面。具体实现如下:
1) 项目需要导入MessageUI.framework框架
2) 在对应类里导入头文件:#import <MessageUI/MessageUI.h>
3) 对应的类遵从代理:MFMailComposeViewControllerDelegate
2.代码
- (IBAction)sendMail:(UIButton *)sender {
//判断用户是否已设置邮件账户
if ([MFMailComposeViewController canSendMail]) {
[self sendEmailAction]; // 调用发送邮件的代码
}else{
//给出提示,设备未开启邮件服务
NSLog(@"");
}
}
-(void)sendEmailAction{
// 创建邮件发送界面
MFMailComposeViewController *mailCompose = [[MFMailComposeViewController alloc] init];
// 设置邮件代理
[mailCompose setMailComposeDelegate:self];
// 设置收件人
[mailCompose setToRecipients:@[@"abc123@163.com"]];
// // 设置抄送人
// [mailCompose setCcRecipients:@[@"123456@qq.com"]];
// // 设置密送人
// [mailCompose setBccRecipients:@[@"6789@163.com"]];
// 设置邮件主题
[mailCompose setSubject:@"设置邮件主题"];
//设置邮件的正文内容
NSString *emailContent = @"我是邮件内容";
// 是否为HTML格式
[mailCompose setMessageBody:emailContent isHTML:NO];
// 如使用HTML格式,则为以下代码
// [mailCompose setMessageBody:@"<html><body><p>Hello</p><p>World!</p></body></html>" isHTML:YES];
//添加附件
// UIImage *image = [UIImage imageNamed:@"qq"];
// NSData *imageData = UIImagePNGRepresentation(image);
// [mailCompose addAttachmentData:imageData mimeType:@"" fileName:@"qq.png"];
// NSString *file = [[NSBundle mainBundle] pathForResource:@"EmptyPDF" ofType:@"pdf"];
// NSData *pdf = [NSData dataWithContentsOfFile:file];
// [mailCompose addAttachmentData:pdf mimeType:@"" fileName:@"EmptyPDF.pdf"];
// 弹出邮件发送视图
[self presentViewController:mailCompose animated:YES completion:nil];
}
#pragma mark - MFMailComposeViewControllerDelegate的代理方法:
-(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;
}
// 关闭邮件发送视图
[self dismissViewControllerAnimated:YES completion:nil];
}
参考文章:
iOS 发送邮件(E-mail)
网友评论