Question

I am relatively new to IoS and have a problem in using mail attachment. Below is my code.

    NSArray *paths = NSSearchPathForDirectoriesInDomains
    (NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

    //make a file name to write the data to using the documents directory:
    NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt",
                          documentsDirectory];
    //create content - four lines of text
    NSString *content = @"One\nTwo\nThree\nF\nFive";
    //save content to the documents directory
    [content writeToFile:fileName
              atomically:NO
                encoding:NSStringEncodingConversionAllowLossy
                   error:nil];
    mailComposer = [[MFMailComposeViewController alloc]init];
    mailComposer.mailComposeDelegate = self;
    [mailComposer setSubject:@"Test mail"];
    NSData *myData = [NSData dataWithContentsOfFile:fileName];
    [mailComposer addAttachmentData:myData mimeType:@"text/plain" fileName:fileName];
    [mailComposer setMessageBody:@"Testing message for the test mail" isHTML:NO];
    [self presentModalViewController:mailComposer animated:YES];

This works well and i get the mail attachment. But, if i change the filename to

NSString *fileName = [NSString stringWithFormat:@"%@",
                              @"Sample.txt"];

It shows the attachment in the compose mail, but when sent, there wont be any attachment. Can any one please suggest how to accomplish the same

Was it helpful?

Solution

Yes it wont work becuase you have to give the complete path to access that file , which you are trying to attach, like in your example:

NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt",
                          documentsDirectory];

this is the full path of the textfile.txt with document directory path as well. That is the reason you are not getting attachment correctly. YOu have to give full path to that file which you are trying to attach.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top