如何显示图像并将其添加为电子邮件的附件

时间:2012-10-08 19:04:09

标签: c# email

我正在使用html正文创建一个System.Net.Mail消息。我将客户签名的jpeg图像(来自字节aray)附加到电子邮件中并发送到服务中心。服务中心希望看到签名而无需打开附件,因此我更改了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);

2 个答案:

答案 0 :(得分:5)

我不喜欢回答我自己的问题,但如果其他人犯了同样的错误,这就是解决方案。我用图像数据创建了一个新的MemoryStream,并尝试在附件和LinkedResource之间共享流。一旦我创建了2个MemoryStream就可以了。

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);

答案 1 :(得分:0)

使用image / jpeg作为图像的内容类型不起作用。它尝试将图像嵌入到电子邮件中并将其转换为base64。然后发件人,收件人和主题被清空。发送电子邮件但所有信息都已损坏。