iOS - 原生发送邮件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/iotjin/article/details/84643136

MFMailComposeViewController(原生)——使用模态跳转出邮件发送界面。具体实现如下:
1) 项目需要导入MessageUI.framework框架
2) 在对应类里导入头文件:#import <MessageUI/MessageUI.h>
3) 对应的类遵从代理:MFMailComposeViewControllerDelegate

-(void)SendMail{
  
    //判断用户是否已设置邮件账户
    if (![MFMailComposeViewController canSendMail]) {
         //给出提示,设备未开启邮件服务
        
    }else{
        // 调用发送邮件的代码
        
        // 创建邮件发送界面
        MFMailComposeViewController *mailCompose = [[MFMailComposeViewController alloc] init];
        // 设置邮件代理
        [mailCompose setMailComposeDelegate:self];
        
        [mailCompose setToRecipients:@[@"[email protected]"]];
        
//        // 设置收件人
//        [mailCompose setToRecipients:@[@"[email protected]"]];
//        // 设置抄送人
//        [mailCompose setCcRecipients:@[@"[email protected]"]];
//        // 设置密送人
//        [mailCompose setBccRecipients:@[@"[email protected]"]];
        
        // 设置邮件主题
        [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];
}

猜你喜欢

转载自blog.csdn.net/iotjin/article/details/84643136