[iOS基础]关于Mail的一切

本文详细介绍了如何在iOS应用中使用MFMailComposeViewController进行邮件发送操作,包括初始化控制器、设置邮件详情及实现邮件发送结果的委托处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用

说道iOS Mail就应该提到MFMailComposeViewController以及MFMailComposeViewControllerDelegate
下面来看看如何使用该类:

//加入邮箱的框架
#import <MessageUI/MFMailComposeViewController.h>
#import <MessageUI/MessageUI.h> 

//添加委托
@interface ExportViewController ()<MFMailComposeViewControllerDelegate>

-(void)sendMail
{
    Class mailViewCon =  NSClassForString(MFMailComposeViewController);
    if(!mailViewCon){
        NSLog(@"当前系统版本不支持应用内发送邮件功能,您可以使用mailto方法代替");
        return;
    }
    if(![mailViewCon canSendMail]){
        NSLog(@"用户没有设置邮件账户");
        return;
    }
//初始化MailController
    MFMailComposeViewController *mailViewCon = [[MFMailComposeViewController alloc] init];
//依次设置收件人、抄送人、密送人、主题、内容、附件
    [mailViewCon setToRecipients:@[@"123@qq.com"]];
    [mailViewCon setCcRecipients:@[@"456@qq.com"]];
    [mailViewCon setBccRecipients:@[@"789@qq.com"]];
    [mailViewCon setSubject:@"hey body"];
//参数1:MessageBody内容 参数2:是否HTML内容
    [mailViewCon setMessageBody:@"110" isHTML:NO];
//参数1:附件NSData 参数2:附件拓展名 参数3:附件名称
    [mailViewCon addAttachmentData:[fileContent objectForKey:AttachFileData] mimeType:@"txt" fileName:[fileContent objectForKey:AttachFileNameStr]];
//设置弹出展示效果
    mailViewCon.modalPresentationStyle = UIModalPresentationPageSheet;
    mailViewCon.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
//设置mailcomposedelegate
    mailViewCon.mailComposeDelegate = self;
//弹出Controller
     [self presentViewController:mailViewCon animated:YES completion:nil];
}

//实现delegate的方法处理邮件发送结果
-(void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    switch (result) {
        case MFMailComposeResultSent:
            break;
        case MFMailComposeResultCancelled:
            break;
        case MFMailComposeResultFailed:
            break;
        case MFMailComposeResultSaved:
            break;
        default:
            logWithError(self, @"这出错了!!");
            break;
    }
    [controller dismissViewControllerAnimated:YES completion:nil];
}

下面来看看其类的其他内容:

//邮件发送结果
enum MFMailComposeResult {
    MFMailComposeResultCancelled,
    MFMailComposeResultSaved,
    MFMailComposeResultSent,
    MFMailComposeResultFailed
};
//邮件发送错误
enum MFMailComposeErrorCode {
    MFMailComposeErrorCodeSaveFailed,
    MFMailComposeErrorCodeSendFailed
};
//是否可以发送
+ (BOOL)canSendMail

获取系统邮件

待补充。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值