iOS 调用系统发送邮件

第一步

导入messageUI.framework框架

第二步

导入头文件

#import

第三步

@property (nonatomic,strong)  MFMailComposeViewController *mailComposer;

准守协议

第四步

在点击事件里

-(void)gotoEmail:(UITapGestureRecognizer *)tap{
    NSString *email = objc_getAssociatedObject(tap, "firstObject");
    if ([MFMailComposeViewController canSendMail]) { // 用户已设置邮件账户
    
    }else{
        [SVProgressHUD showInfoWithStatus:@"无邮件帐户,请设置邮件帐户来发送电子邮件"];
        return;
    }
     if ([MFMessageComposeViewController canSendText] == YES) {
         _mailComposer = [[MFMailComposeViewController alloc]init];
         _mailComposer.mailComposeDelegate = self;
         [_mailComposer setSubject:@""];
         NSArray *arr = @[email];
         //收件人
         [_mailComposer setToRecipients:arr];
         // 设置邮件主题
         //[_mailComposer setSubject:@"我是邮件主题"];
         // 设置密抄送
         //[_mailComposer setBccRecipients:@[@"[email protected]"]];
         // 设置抄送人
         //[_mailComposer setCcRecipients:@[@"[email protected]"]];
         // 如使用HTML格式,则为以下代码
         //    [_mailComposer setMessageBody:@"

Hello

World!

" isHTML:YES];
         /*
          //添加附件
         UIImage *image = [UIImage imageNamed:@"image"];
         NSData *imageData = UIImagePNGRepresentation(image);
         [_mailComposer addAttachmentData:imageData mimeType:@"" fileName:@"custom.png"];
         NSString *file = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"pdf"];
         NSData *pdf = [NSData dataWithContentsOfFile:file];
         [_mailComposer addAttachmentData:pdf mimeType:@"" fileName:@"7天精通IOS"];
         */
         
         [_mailComposer setMessageBody:@"你好,很高兴认识你" isHTML:NO];
         [self presentViewController:_mailComposer animated:YES completion:nil];
     }else{
         [SVProgressHUD showInfoWithStatus:@"设备不支持"];
     }
}

第五步

代理方法

-(void)mailComposeController:(MFMailComposeViewController *)controller
         didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error{
    if (result) {
        YYLog(@"Result : %ld",(long)result);
    }
    if (error) {
        YYLog(@"Error : %@",error);
    }
    switch (result)
    {
        case MFMailComposeResultCancelled: // 用户取消编辑
            YYLog(@"Mail send canceled...");
            break;
        case MFMailComposeResultSaved: // 用户保存邮件
            YYLog(@"Mail saved...");
            break;
        case MFMailComposeResultSent: // 用户点击发送
            YYLog(@"Mail sent...");
            break;
        case MFMailComposeResultFailed: // 用户尝试保存或发送邮件失败
            YYLog(@"Mail send errored: %@...", [error localizedDescription]);
            break;
    }
    [self dismissViewControllerAnimated:YES completion:nil];
    
}



你可能感兴趣的:(Objective-C,iOS,邮件)