Search code examples
iphoneobjective-ciosxcodemfmessagecomposeviewcontroller

How to attach screenshot to mailcomposer in iOS


Hi i'm using the below code to attach screenshot to mailcomposer, i'm not having a device to check so will this work on actual device?

-(void)launchMailAppOnDevice
{
    /*Take a SnapShot of current screen*/
    UIGraphicsBeginImageContext(self.view.frame.size);
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    NSData * imageData = UIImageJPEGRepresentation(image, 1.0);

    NSString *recipients = @"mailto:[email protected]?cc=@\"\"&subject=blah!!blah!!";

    NSString *body = @"&body=blah!!blah!!";

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

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

Solution

  • The last 5 lines are wrong. You most likely want to use the MFMailComposeViewController class:

    MFMailComposeViewController *mcv = [[MFMailComposeViewController alloc] init];
    
    [mcv setSubject:@"blah!!blah!!"];
    [mcv setToRecipients:[NSArray arrayWithObject:@"[email protected]"]];
    [mcv setMessageBody:@"Blah!! 'tis the body!" isHTML:NO];
    [mcv addAttachmentData:imageData mimeType:@"image/jpeg" fileName:@"Screenshot.jpg"];
    
    [someViewController presentModalViewController:mcv animated:YES];
    [mcv release];
    

    P. s.: don't forget to add the MessageUI framework to your project and also #import <MessageUI/MessageUI.h>.

    P. p. s.: while it's important to test on an actual device, it's even more important to read some guides and documentation before writing the actual code.