How to add a image in email body using MFMailComposeViewController

Ranjit picture Ranjit · Aug 31, 2012 · Viewed 21.5k times · Source

I am trying to find out the best way to add an image inside the body of the email and not as attachment in ios.

1) Apple has provided a function "addAttachment" and the doc says, to add any image in the content, we should use this function, but I tried that function, and sent an mail, I checked on my browser, it is recieved as an attachment.

2) Secondly, many blogs say to use base64 encoding, but that also wont work, image is sent as a broken one.

So friends, please help me out to find the best available solution to do this.

Regards Ranjit

Answer

msk picture msk · Aug 31, 2012

Set email format as HTML. This code is woking fine in my app.

MFMailComposeViewController *emailDialog = [[MFMailComposeViewController alloc] init];

NSString *htmlMsg = @"<html><body><p>This is your message</p></body></html>";

NSData *jpegData = UIImageJPEGRepresentation(emailImage, 1.0);

NSString *fileName = @"test";
fileName = [fileName stringByAppendingPathExtension:@"jpeg"];
[emailDialog addAttachmentData:jpegData mimeType:@"image/jpeg" fileName:fileName];

emailDialog setSubject:@"email subject"];
[emailDialog setMessageBody:htmlMsg isHTML:YES];


[self presentModalViewController:emailDialog animated:YES];
[emailDialog release];

Swift 5

import MessageUI

    func composeMail() {

        let mailComposeVC = MFMailComposeViewController()

        mailComposeVC.addAttachmentData(UIImage(named: "emailImage")!.jpegData(compressionQuality: CGFloat(1.0))!, mimeType: "image/jpeg", fileName:  "test.jpeg")

        mailComposeVC.setSubject("Email Subject")

        mailComposeVC.setMessageBody("<html><body><p>This is your message</p></body></html>", isHTML: true)

        self.present(mailComposeVC, animated: true, completion: nil)
    }