如何使用MFMailComposeViewController在电子邮件正文中添加图像

Ran*_*jit 23 ios ios5 mfmailcomposeviewcontroller

我试图找出在电子邮件正文中添加图像的最佳方式,而不是在ios中作为附件.

1)Apple提供了一个功能" addAttachment ",并且doc说,要在内容中添加任何图像,我们应该使用这个功能,但我尝试了这个功能,并发了一封邮件,我在浏览器上查了一下,就收到了一个附件.

2)其次,许多博客都说要使用base64编码,但这也不会起作用,图像会以破坏的形式发送.

所以朋友们,请帮助我找到最好的解决方案来做到这一点.

问候Ranjit

msk*_*msk 61

将电子邮件格式设置为HTML.这段代码在我的应用程序中很好.

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];
Run Code Online (Sandbox Code Playgroud)

迅速

import MessageUI

    func composeMail() {

        let mailComposeVC = MFMailComposeViewController()

        mailComposeVC.addAttachmentData(UIImageJPEGRepresentation(UIImage(named: "emailImage")!, 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.presentViewController(mailComposeVC, animated: true, completion: nil)

    }
Run Code Online (Sandbox Code Playgroud)

  • 嗨@MSK,我有一个疑问,这里只有你使用 HTML 创建了字符串而不是图像,那么它是如何进入正文的,假设如果我不使用 HTML 创建字符串,那么图像将作为附件,不是很我很清楚,你能解释一下吗 (2认同)

Ric*_*ard 10

我最近刚刚为Swift做了这个.

在Swift中将照片添加到电子邮件的功能:

func postEmail() {
    var mail:MFMailComposeViewController = MFMailComposeViewController()
    mail.mailComposeDelegate = self
    mail.setSubject("your subject here")

    var image = // your image here
    var imageString = returnEmailStringBase64EncodedImage(image)
    var emailBody = "<img src='data:image/png;base64,\(imageString)' width='\(image.size.width)' height='\(image.size.height)'>"

    mail.setMessageBody(emailBody, isHTML:true)

    self.presentViewController(mail, animated: true, completion:nil)
}
Run Code Online (Sandbox Code Playgroud)

返回格式化图像的功能:

func returnEmailStringBase64EncodedImage(image:UIImage) -> String {
    let imgData:NSData = UIImagePNGRepresentation(image)!;
    let dataString = imgData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
    return dataString
}
Run Code Online (Sandbox Code Playgroud)

  • 这些图片是否在Gmail,Hotmail等中正确显示?他们不适合我.. (4认同)
  • 这适用于iOS,但要小心 - 仍然无法在hotmail,gmail或大多数其他客户端工作,例如egfconnor. (4认同)