Search code examples
iosobjective-cxcodeemail-attachmentsmfmailcomposeviewcontroller

Attaching .txt to MFMailComposeViewController


I have a .txt file stored in Documents Folder and I want to send it by MFMailComposeViewController with next code in the body of -sendEmail method:

NSData *txtData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"dataBase" ofType:@"txt"]];
        [mail addAttachmentData:txtData mimeType:@"text/plain" fileName:[NSString stringWithFormat:@"dataBase.txt"]];

When Mail composer appears I can see attachment in the mail body but I receive this mail without attachment. Maybe it is wrong MIME-type for .txt attachment or something wrong with this code?

Thanks


Solution

  • NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];        
            NSString *txtFilePath = [documentsDirectory stringByAppendingPathComponent:@"abc.txt"];
    NSData *noteData = [NSData dataWithContentsOfFile:txtFilePath];
            MFMailComposeViewController *_mailController = [[MFMailComposeViewController alloc] init];
            [_mailController setSubject:[NSString stringWithFormat:@"ABC"]];
            [_mailController setMessageBody:_messageBody
                                     isHTML:NO];
            [_mailController setMailComposeDelegate:self];
            [_mailController addAttachmentData:noteData mimeType:@"text/plain" fileName:@"abc.txt"];
    

    Hope it helps.