小编典典

如何在 MFMailComposeViewController 的 MailComposer 表中添加 UIImage

javascript

我想UIImage在 的撰写表中插入一个 s MFMailComposerViewController

请注意,我不想附加它们,但我想使用 HTML 代码将它们放在一个表格中,该代码将成为电子邮件正文的一部分。


阅读 226

收藏
2022-05-24

共1个答案

小编典典

带着新的答案再次回来。不过,我仍然保留我以前的代码,因为我仍然不相信没有办法利用它。我自己会坚持的。以下代码确实有效。Mustafa 建议对图像进行 base64 编码,并表示它们只适用于 Apple 到 Apple,但实际上并非如此。Base64 编码现在可以与大多数邮件客户端一起使用(IE 以前不支持它,但现在支持到一定大小的图像,尽管我不确定大小到底是多少)。问题是像 Gmail 这样的邮件客户端会删除你的图像数据,但是有一个简单的解决方法......只需<b> and </b>在你的周围放置标签<img ...>标签是您需要做的一切,以防止它被剥离。为了将图像添加到您的电子邮件中,您需要将 base64 编码器添加到您的项目中。那里有几个(虽然主要是 C),但我发现的最简单的 ObjC 是由 Matt Gallagher 称为 NSData+Base64 的(我在复制它后把“+”从名称中去掉,因为它给我带来了问题)。将 .h 和 .m 文件复制到您的项目中,并确保在您计划使用它的地方 #import .h 文件。然后像这样的代码会将图像放入您的电子邮件正文中......

- (void)createEmail {
//Create a string with HTML formatting for the email body
    NSMutableString *emailBody = [[[NSMutableString alloc] initWithString:@"<html><body>"] retain];
 //Add some text to it however you want
    [emailBody appendString:@"<p>Some email body text can go here</p>"];
 //Pick an image to insert
 //This example would come from the main bundle, but your source can be elsewhere
    UIImage *emailImage = [UIImage imageNamed:@"myImageName.png"];
 //Convert the image into data
    NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(emailImage)];
 //Create a base64 string representation of the data using NSData+Base64
    NSString *base64String = [imageData base64EncodedString];
 //Add the encoded string to the emailBody string
 //Don't forget the "<b>" tags are required, the "<p>" tags are optional
    [emailBody appendString:[NSString stringWithFormat:@"<p><b><img src='data:image/png;base64,%@'></b></p>",base64String]];
 //You could repeat here with more text or images, otherwise
 //close the HTML formatting
    [emailBody appendString:@"</body></html>"];
    NSLog(@"%@",emailBody);

 //Create the mail composer window
    MFMailComposeViewController *emailDialog = [[MFMailComposeViewController alloc] init];
    emailDialog.mailComposeDelegate = self;
    [emailDialog setSubject:@"My Inline Image Document"];
    [emailDialog setMessageBody:emailBody isHTML:YES];

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

我已经在 iPhone 上对此进行了测试,并在雅虎、我的个人网站和我的 MobileMe 上向自己发送了可爱的图片嵌入电子邮件。我没有Gmail 帐户,但Yahoo 运行良好,而且我发现的每个来源都说粗体标签是让它运行所需的一切。希望这对大家有帮助!

2022-05-24