Search code examples
iphoneemailxcode4ios4

How do i send a saved text file as an email attachment


I have an app which is sending data collected via an email as an attachment. I use the following code to create and save the data to a file called 'leads.xml' in my docs folder.

NSArray *sysPath = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES );
NSString *sysFilePath = [sysPath objectAtIndex:0];
[picker addAttachmentData:sysFilePath mimeType:@"text/xml" fileName:@"leads.xml"];

.
.
.

[emailBody writeToFile:filePath atomically:YES];

I then try to send the saved file as an attachment using this code -

NSArray *sysPaths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES );
NSString *docDirectory = [sysPaths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:@"%@/leads.xml", docDirectory];

When it runs I get an error, what am I doing wrong?


Solution

  • The mail want a NSData object, contain the files content not a path. You will need to load the file into a NSData object like:

    NSArray *sysPaths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES );
    NSString *docDirectory = [sysPaths objectAtIndex:0];
    NSString *filePath = [docDirectory stringByAppendingPathComponent:@"leads.xml"];
    
    NSData *fileData = [NSData dataWithContentsOfFile:filePath];
    [picker addAttachmentData:fileData mimeType:@"text/xml" fileName:@"leads.xml"];