Exchange Web服务 - 内嵌图像到外部电子邮件客户端无法呈现

时间:2016-02-08 21:21:23

标签: c# exchangewebservices

我正在使用EWS接收/发送电子邮件。我在电子邮件中发送嵌入的图像,以将用户导航到另一个页面。但是,当发送到其他电子邮件客户端,如gmail和yahoo时,图像不会被设置为html,而是文本。我在下面创建了一个控制台应用程序来演示:

static void Main(string[] args)
    {
        var service = getExchangeService(NetworkCreds.Credentials);

        // Create the HTML body with the content identifier of the attachment.
        string html = @"<html>
                 <head>
                 </head>
                 <body>
                    <img width=100 height=100 id=""1"" src=""cid:Party.jpg"">
                 </body>
                 </html>";

        // Create the email message.
        EmailMessage email = new EmailMessage(service);
        email.Subject = "Test Email";
        email.Body = new MessageBody(BodyType.HTML, html);
        email.ToRecipients.Add("test@gmail.com");

        // Add the attachment to the local copy of the email message.
        string file = @"C:\projects\Party.jpg";
        email.Attachments.AddFileAttachment("Party.jpg", file);
        email.Attachments[0].IsInline = true;
        email.Attachments[0].ContentId = "Party.jpg";

        // Save a copy of the email, add the attachment, and then send the email. This method results in three calls to EWS.
        email.SendAndSaveCopy();
    }

当我在outlook中收到消息时它工作正常但在gmail中它只有正文中的以下文本:[cid:Party.jpg],下面是文件附件。我知道Gmail和其他客户对图像进行了大量处理,这可能就是为什么它无法正确显示的原因。 我的问题是内联图片是否可以从交换网络服务发送到其他客户端并正确处理?

2 个答案:

答案 0 :(得分:0)

我知道我有点迟了但也许其他人会遇到类似的问题,这可能有助于解决问题。

您可以将图像设置为base64编码图像。

在我的情况下,我想在浏览器控件中加载现有电子邮件的预览。 一切都有效,除了显示图像。但是将它们替换为base64编码的字符串非常有效。

在此示例中,以下代码应如所述:

EmailMessage email = new EmailMessage(service);
email.Subject = "Test Email";
email.Body = new MessageBody(BodyType.HTML, html);
email.ToRecipients.Add("test@gmail.com");
// Add the attachment to the local copy of the email message.
string file = @"C:\projects\Party.jpg";
MemoryStream stream = new MemoryStream();
email.Attachments.AddFileAttachment("Party.jpg", file).Load(stream);
byte[] imageBytes = stream.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
stream.close();
email.Attachments[0].IsInline = true;
email.Attachments[0].ContentId = "Party.jpg";

string html = @"<html>
                <head>
                </head>
                <body>
                <img width=100 height=100 id=""1"" src=""data: image/jpg;base64, " + base64String + """>
                </body>
                </html>";

答案 1 :(得分:0)

这就是你解决这类问题的方法

bodyText = bodyText.Replace("cid:" + fileAttachment.ContentId, fileAttachment.Name);

请务必将文件附加为&#34; Image 001.png&#34;或者不管它是什么,那么你可以用图像重新发送这封电子邮件:)