我正在创建带有html正文的System.Net.Mail消息。我将客户签名的jpeg图像(从一个字节开始)附加到电子邮件中,然后发送到服务中心。服务中心希望看到签名而不必打开附件,因此我更改了html并将图像再次添加为LinkedResource。问题是,现在附件比以前大,尝试查看附件会显示错误。如果我保存附件并在十六进制编辑器中打开文件,则整个文件为空。我可以注释添加链接的资源的代码,并且附件可以再次工作。如何包含内嵌图像和附件?
这是我嵌入图像的标签:<p><img src=cid:CustomerSignature /></p>
这是我的代码:
System.IO.MemoryStream ms = new System.IO.MemoryStream(insuranceClaim.Signature, 0, insuranceClaim.Signature.Length);
ms.Position = 0;
System.Net.Mime.ContentType contentType = new System.Net.Mime.ContentType();
contentType.MediaType = System.Net.Mime.MediaTypeNames.Image.Jpeg;
contentType.Name = "signature.jpg";
System.Net.Mail.Attachment imageAttachment = new System.Net.Mail.Attachment(ms, contentType);
System.Net.Mime.ContentDisposition disposition = imageAttachment.ContentDisposition;
mailMessage.Attachments.Add(imageAttachment);
System.Net.Mail.LinkedResource signature = new System.Net.Mail.LinkedResource(ms, new System.Net.Mime.ContentType("image/jpeg"));
signature.ContentId = "CustomerSignature";
System.Net.Mail.AlternateView aView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(mailMessage.Body, new System.Net.Mime.ContentType("text/html"));
aView.LinkedResources.Add(signature);
mailMessage.AlternateViews.Add(aView);
最佳答案
我不喜欢回答自己的问题,但是如果其他人犯了与我相同的错误,这就是解决方案。我使用图像数据创建了一个新的MemoryStream,并尝试在附件和LinkedResource之间共享流。一旦我创建了2个MemoryStreams,它就可以工作了。
System.IO.MemoryStream ms = new System.IO.MemoryStream(insuranceClaim.Signature, 0, insuranceClaim.Signature.Length);
System.Net.Mime.ContentType contentType = new System.Net.Mime.ContentType();
contentType.MediaType = System.Net.Mime.MediaTypeNames.Image.Jpeg;
contentType.Name = "signature.jpg";
System.Net.Mail.Attachment imageAttachment = new System.Net.Mail.Attachment(ms, contentType);
mailMessage.Attachments.Add(imageAttachment);
System.IO.MemoryStream embeddedMs = new System.IO.MemoryStream(insuranceClaim.Signature, 0, insuranceClaim.Signature.Length);
System.Net.Mail.LinkedResource signature = new System.Net.Mail.LinkedResource(embeddedMs, new System.Net.Mime.ContentType("image/jpeg"));
signature.ContentId = "CustomerSignature";
System.Net.Mail.AlternateView aView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(mailMessage.Body, new System.Net.Mime.ContentType("text/html"));
aView.LinkedResources.Add(signature);
mailMessage.AlternateViews.Add(aView);
关于c# - 如何显示图像并将其添加为电子邮件的附件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12787852/