views:

525

answers:

2

I successfully created a txt file (i.e. the file exists and opens), I would like to attach it to an email that I am successfully generating (i.e. the email opens and I can put text into the email etc. and send it). Here is the code I have now for performing the attachment:

// Attach a file to the email
NSString *path = [self dataFilePath:(@"myFile.txt")];
NSData *myData = [NSData dataWithContentsOfFile:path];
[picker addAttachmentData:myData mimeType:@"text/plain" fileName:@"myFile"];

The dataFilePath is a method I use to get the path for a file, it works fine as I use it often. The above code puts a < br/ > < br/ >, then has the text from the text file with a few more < br/ > < br/ > ..breaks in there... so this doesn't actually attach the file it pastes it in the email text... I would like to attach the file.

I copied/modified this code from other posts on stackoverflow and I'm having a hard time finding info on apple's site. Note: I'm not sure what the mimeType is for a txt file, as their website (www.iana.org) doesn't denote a txt...???

Update: Changed to updated code, and Thanks for confirming that "plain" was the correct choice for the mimeType.

A: 

This isn't a complete solution, but the MIME type for plain text is:

text/plain
Greg Hewgill
+1  A: 

This might be an issue with your email client, and not with your program. Does the text file show up as an attachment in the mail compose view, but then when you receive the email it's in the main body?

When you receive the email, try doing a view source on it (or view original, or whatever your email client calls it). You should see something like this in the email:

--Apple-Mail-1-494911569
Content-Disposition: attachment;
    filename=myFile
Content-Type: text/plain;
    name=myFile
Content-Transfer-Encoding: 7bit

Text of the file here.

--Apple-Mail-1-494911569

If you see that in the email, then the file is being attached properly. It's possible that your email client is ignoring the Content-Disposition MIME header. In GMail and Apple mail, email sections like the one above are definitely shown as attachments.

For what it's worth, here's some complete working code the creates an email, adds an HTML body, adds a text attachment, and sends shows the compose view:

NSData *textData = [[self getEmailAttachment] dataUsingEncoding:NSUTF8StringEncoding];
NSString *htmlData = [self getEmailBodyHTML];

/* Set up the mail compose view and put in the body/attachment */
MFMailComposeViewController *mailComposer = [[[MFMailComposeViewController alloc] init] autorelease];
[mailComposer setMessageBody:htmlData isHTML:NO];
[mailComposer addAttachmentData:textData mimeType:@"text/plain" fileName:@"tripometer_report.csv"];

/* Set default subject */
[mailComposer setSubject:@"Email subject"];

mailComposer.mailComposeDelegate = self; 
[self presentModalViewController:mailComposer animated:YES];
Jacques