iOS开发-调用系统邮箱 MFMailComposeViewController

在APP中发送邮件是一个很普遍的应用场景,譬如将用户反馈的邮件发送到指定邮箱,就可以通过在APP中直接编辑邮件或者打开iOS自带的Mail来实现。

一般使用 MFMailComposeViewController 在我们自己的APP中展现一个邮件编辑页面,这样发送邮件就不需要离开当前的APP。

前提是系统中的Mail要设置了账户,或者iCloud设置了邮件账户才能使用。

首先要导入系统库:

#import <MessageUI/MessageUI.h>
- (void)sendMail {
    //先验证邮箱能否发邮件,不然会崩溃
    if (![MFMailComposeViewController canSendMail]) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"您还未配置邮箱账户,是否现在跳转邮箱配置?" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSURL *url = [NSURL URLWithString:@"mailto://"];
            if ([[UIApplication sharedApplication] canOpenURL:url]) {
                [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
            }
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }
    
    MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
    picker.mailComposeDelegate = self;
    //收件人邮箱,使用NSArray指定多个收件人
    NSArray *toRecipients = [NSArray arrayWithObject:@"[email protected]"];
    [picker setToRecipients:toRecipients];
    //抄送人邮箱,使用NSArray指定多个抄送人
    NSArray *ccRecipients = [NSArray arrayWithObject:@"[email protected]"];
    [picker setToRecipients:ccRecipients];
    //密送人邮箱,使用NSArray指定多个密送人
    NSArray *bccRecipients = [NSArray arrayWithObject:@"[email protected]"];
    [picker setToRecipients:bccRecipients];
    //邮件主题
    [picker setSubject:@"邮件主题"];
    //邮件正文,如果正文是html格式则isHTML为yes,否则为no
    [picker setMessageBody:@"邮件正文" isHTML:NO];
    //添加附件,附件将附加到邮件的结尾
    NSData *data = UIImageJPEGRepresentation([UIImage imageNamed:@"icon.jpg"], 1.0);
    [picker addAttachmentData:data mimeType:@"image/jpeg" fileName:@"new.png"];
    [self presentViewController:picker animated:YES completion:nil];
}

//代理
- (void)mailComposeController:(MFMailComposeViewController *)controller
          didFinishWithResult:(MFMailComposeResult)result
                        error:(NSError *)error {
    NSLog(@"send mail error:%@", error);
    switch (result) {
        case MFMailComposeResultCancelled:
            NSLog(@"邮件发送取消");
            break;
        case MFMailComposeResultSaved:
            NSLog(@"邮件保存成功");
            break;
        case MFMailComposeResultSent:
            NSLog(@"邮件发送成功");
            break;
        case MFMailComposeResultFailed:
            NSLog(@"邮件发送失败");
            break;
        default:
            NSLog(@"邮件未发送");
            break;
    }
    [controller dismissViewControllerAnimated:YES completion:nil];
}

猜你喜欢

转载自blog.csdn.net/qq_36557133/article/details/103564496