How to Send Email with Attachments – Example Using iPhone Camera to Email a Photo

In this post: Camera Application to Take Pictures and Save Images to Photo Album, I demonstrated how you can take photos with the iPhone camera and save the captured images to the Photo Album. A reader asked if it would be possible to email the camera image in place of writing to the Photo Album, which is the focus of this tip.

Building on the previous post, the example created here starts the camera on the iPhone, and once a photo is snapped, launches the email application, attaching the resulting image to the email.

Start the iPhone Camera

The user interface of this application is quite simple, there is one button on the UI that will start the camera. Once the button is tapped, the method shown below will be called. Here we create an image picker controller, set the source type to the camera, point the delegate to self and specify not to allow image editing. From there, simply show a modal view controller to enable the camera.

- (void)buttonPressed:(UIButton *)button
{
  // Create image picker controller
  UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
 
  // Set source to the camera
  imagePicker.sourceType =  UIImagePickerControllerSourceTypeCamera;
 
  // Delegate is self
  imagePicker.delegate = self;
 
  // Allow editing of image ?
  imagePicker.allowsImageEditing = NO;
 
  // Show image picker
  [self presentModalViewController:imagePicker animated:YES];	
}
Convert Camera Image to NSData Object

Once the camera has taken a photo, the method below will be called, passing in a dictionary of related information, such as the original image, edited image (if any), URL to a movie (when applicable), etc. We grab the image from the dictionary and create a UIImage object. From there, dismiss the camera, then pass the camera image to the method emailImage where we will construct an email and append the image.

-- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
  // Access the uncropped image from info dictionary
  UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
 
  // Dismiss the camera
  [self dismissModalViewControllerAnimated:YES];
 
  // Pass the image from camera to method that will email the same
  // A delay is needed so camera view can be dismissed
  [self performSelector:@selector(emailImage:) withObject:image afterDelay:1.0];
 
  // Release picker
  [picker release];
}
Email Camera Image

The last step is to compose an email and attach the image from the camera. We begin be creating a MFMailComposeViewController object, setting the delegate to self. We then step through the configuration preferences for the email, setting the subject, the list of recipients (to, carbon copy, and blind carbon copy) and creating the body of the message.

Our next step is to convert theUIImage from the camera into an NSData object, which we can attach to our email. As you’ll notice in the code below, I’ve created the NSData as a PNG representation, you could also use JPG format if you prefer (which allows you to specify a value for image compression).

Once the image is attached to the email, we show a modal view controller which will launch the email application – one note, I am making the assumption that iPhone OS 3.x is the active platform.

- (void)emailImage:(UIImage *)image
{
  MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
  picker.mailComposeDelegate = self;
 
  // Set the subject of email
  [picker setSubject:@"Picture from my iPhone!"];
 
  // Add email addresses
  // Notice three sections: "to" "cc" and "bcc"	
  [picker setToRecipients:[NSArray arrayWithObjects:@"emailaddress1@domainName.com", @"emailaddress2@domainName.com", nil]];
  [picker setCcRecipients:[NSArray arrayWithObject:@"emailaddress3@domainName.com"]];	
  [picker setBccRecipients:[NSArray arrayWithObject:@"emailaddress4@domainName.com"]];
 
  // Fill out the email body text
  NSString *emailBody = @"I just took this picture, check it out.";
 
  // This is not an HTML formatted email
  [picker setMessageBody:emailBody isHTML:NO];
 
  // Create NSData object as PNG image data from camera image
  NSData *data = UIImagePNGRepresentation(image);
 
  // Attach image data to the email
  // 'CameraImage.png' is the file name that will be attached to the email
  [picker addAttachmentData:data mimeType:@"image/png" fileName:@"CameraImage"];
 
  // Show email view	
  [self presentModalViewController:picker animated:YES];
 
  // Release picker
  [picker release];
}
 
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error 
{
  // Called once the email is sent
  // Remove the email view controller	
  [self dismissModalViewControllerAnimated:YES];
}
Caveat

To keep things simple, this application runs on a single thread. It works fine, however, there is a few second delay when moving from the camera application to the email application. Ideally you would add a little logic to better manage the user interface.

Source Code

Here is the link to the source code: Email Camera Image Application.

33 Comments

  1. First let me offer my thanks for posting this for me, I mean us.. I can not even tell you how much this has helped me.. People like you are just… Thank you so much.. I want to send you a check for the work that you did on this and to express my gratitude.. I am not rich, so it will not buy you a car or a house, but I want you to have something.. How can this be done (paypal perhaps?).. You should have something for your efforts.. and generosity of time and effort… I am totally serious.. you an simply respond to my email and I will get it out to you..THANKS MAN..

  2. Thank a lot. You saved my day. I don’t usually leave messages, but for this one I just had to. Thanks a lot!

  3. Great work John. Excellent.

    Just wondering if it’s possible to save the image to a FTP location instead of sending it as email attachement?

    • Atif, you could save the file to a remote (ftp) location, however that is not a supported capability in the existing API. You would need to write the code to upload and save the file to a server.

    • Hello Atif,

      just came across this post. Did you ever figure out how to upload the photo to ftp folder?

  4. Thanks John for your prompt reply.

    I have been thinking about this for couple of hours. I’m thinking to pass NSData (Containing Image) to a .NET webservice and use C# code to save the image to disk?

    My question would be can I receive NSData into a Stream object in C#?

  5. Is it possible to have the e-mail address you send to hardcoded into the app, so that upon hitting send it simply sends the photo with some pre-written subject lines etc?

  6. Dude, thank you very much for all your efforts. I’ve been looking for this for hours and finally got it. I’m building a photo app that load pics from camera roll and other and this is one of the features i’m trying to add. Again thanks for your wonderful code.

    • Hi Dinusha ,

      This is Abhishek… I am also building an app tht takes pic from camera so tht they can be sent via email at a time.So if u hav any help how to send multiple images in attachment at a time.It will b appreciable.
      I have also left comment below how i tried..
      Abhishek says:
      December 4, 2011 at 1:04 am

      Thanks.

  7. Hi John, seriously, thanks!
    Great tutorial. I have an app I’m playing with which puts user location and image into a uitable, and this code helped me send the data. You’re a legend. Cheers!

    • Hi Ryan,

      Trying to do the same as you, by the sounds of it, how are you pinning the users location to the image?

      Cheers

  8. Have you ever tried to take a picture and upload it to Facebook?
    I’m having difficulty and I think this post will help (thank you).

    -Jon

  9. hi john,
    many thanks for this very nice sample.

    a little question to the size of the image: everytimes when i try to send the email the mailclient asks for reducing the file size of the attachment! could thsi be done in the MailComposer part? and how?

    • I have not found any API references that allow for customization of the attachment size, this seems to be controlled by the OS only.

      • ok thx,

        the only solution in that will be to store the picture in local gallery, resize it and send in from app!

  10. HI,

    Thank you tremendously for your tutorial!

    One question though, how can this be adapted for video? I have the camera set up to take video, but I run into issues when trying to email it..Could someone please point me in the right direction??

    Thanks!

  11. Hi,

    Your post immensely helped me implement a couple of things in my app.
    But I am trying to select more than just one photo out of the camera roll, could you/ anyone please lead me on this issue? Many thanks!!

  12. Thank you for the great tutorial!

    But is it possible to take the current view in the attachement
    instead of a certain photo from a library?

  13. What if i want to send multiple image attachment with different image(file) name.
    Actually i made a for loop for multiple attachement but i hav got images in email body not as attachment with no file name(image name)…..if you have any suggestion it will be appreciable..

    i uses in the following way….

    for(int i =0;i<appDel.arrPics.count;i++)
    {

    if (![[(NSDictionary*)[appDel.arrPics objectAtIndex:i] objectForKey:@"item"] isEqualToString:@"Select Item"])

    {
    UIImage *itemsimage = (UIImage*)[(NSDictionary*)[appDel.arrPics objectAtIndex:i] objectForKey:@"pic"];

    NSData *itemsImageData = [NSData dataWithData:UIImagePNGRepresentation(itemsimage)];

    NSString *itemsPrices = [NSString stringWithFormat:@"%@ £ %@",[(NSDictionary*)[appDel.arrPics objectAtIndex:i] objectForKey:@"item"],[(NSDictionary*)[appDel.arrPics objectAtIndex:i] objectForKey:@"price"]];

    NSLog(@"Item Prices%@",itemsPrices);

    [picker addAttachmentData:itemsImageData mimeType:@"image/png" fileName:itemsPrices];

    }
    }

  14. Is it possible to take a picture and email it WITHOUT the user’s knowledge?

  15. I am trying to send image in attachment by the given below code. it works fine but when i open the mail in out look or google crome it does not show attachment image name. so please reply me to solve this problem……

    for(int i =0;i<appDel.arrPics.count;i++)
    {

    if (![[(NSDictionary*)[appDel.arrPics objectAtIndex:i] objectForKey:@"item"] isEqualToString:@"Select Item"])

    {
    UIImage *itemsimage = (UIImage*)[(NSDictionary*)[appDel.arrPics objectAtIndex:i] objectForKey:@"pic"];

    NSData *itemsImageData = [NSData dataWithData:UIImagePNGRepresentation(itemsimage)];

    NSString *itemsPrices = [NSString stringWithFormat:@"%@ £ %@",[(NSDictionary*)[appDel.arrPics objectAtIndex:i] objectForKey:@"item"],[(NSDictionary*)[appDel.arrPics objectAtIndex:i] objectForKey:@"price"]];

    NSLog(@"Item Prices%@",itemsPrices);

    [picker addAttachmentData:itemsImageData mimeType:@"image/png" fileName:itemsPrices];

    }
    }

  16. thank you, thank you!! I’ve been looking for this (with a twist) for almost 2 months. I had to combine what you had and another post so I could use video instead of png/jpeg… thanks again :-)

  17. Great Post John Muchow!

    I have an important question: Is it possible to have a pre-determined email message ‘to/from/subject/body text/ and have it send right away without popping up the mail application and the send button? I am trying to bypass that screen all together. I look forward to a response and thank you for the amazing article!

    -David

  18. hi john
    I need to adjust the orientation of the attaching image inside the mail. can you help me.. thanks in advance.

    • This is something that you will need to do before you attach the image, rotate the image and then attach.

Comments are closed.