Ali Imran Ali Imran - 1 year ago 63
Objective-C Question

how to attach any document in email in iphone app

I am sending email from iphone app it is working fine but i want that with email i should attached a pdf file which is documents folder of the app.for testing first i attached a png from resources folder of app but it does not get attached and not sent in email i am using following code.

- (IBAction)onEmailResult

if ([[MFMailComposeViewController class] canSendMail]) {
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;

[picker setSubject:@"Pig Game"];

[picker setToRecipients:toRecipients];

int a=10;
int b=100;
NSString *path = [[NSBundle mainBundle] pathForResource:@"project existing photo" ofType:@"png"];
NSData *myData = [NSData dataWithContentsOfFile:path];
[picker addAttachmentData:myData mimeType:@"png" fileName:@"icon.png"];

NSString * emailBody = [NSString stringWithFormat:@"My Score %d",a];
[picker setMessageBody:emailBody isHTML:NO];
[self presentModalViewController:picker animated:YES];
[picker release];

else {

int a=10;
int b=20;
NSString *recipients = @" Game";
NSString *body = [NSString stringWithFormat:@"&body=My Score: %d/%d, My Time: %@", a,b, time];

NSString *email = [NSString stringWithFormat:@"%@%@", recipients, body];
email = [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:email]];

Answer Source

Try following code snippet.

- (NSString *)pathForFile : (NSString *) fileName{
    return [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent: fileName];

- (void) sendMailWithAttachedFile : (NSString *) fileName :(NSString *) extension{
    MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
    picker.mailComposeDelegate = self;
//    NSURL* outputURL = [[NSURL alloc] initFileURLWithPath:[self pathForResourse:fileName ofType:extension]];
    NSURL* outputURL = [[NSURL alloc] initFileURLWithPath:[self pathForFile:[NSString stringWithFormat:@"%@.%@", fileName, extension]]];
    NSData *data=[[NSData alloc]initWithContentsOfURL:outputURL];
    [picker addAttachmentData:data mimeType:@"application/pdf" fileName:@"TestOne.pdf"];
    [self presentModalViewController:picker animated:YES];

Now Call Send Mail method As:

[self sendMailWithAttachedFile:@"TestOne" :@"pdf"];