如何将资源文件夹中的图像作为附件添加并嵌入到C#中的Outlook邮件正文中

时间:2015-06-18 03:35:43

标签: c# vsto outlook-addin outlook-2013

我有几个图像存储在visual studio项目资源文件夹中,我必须加载它们并在Outlook邮件正文中显示。这是代码:

Bitmap b = new Bitmap(Properties.Resources.MyImage);
ImageConverter ic = new ImageConverter();
Byte[] ba = (Byte[])ic.ConvertTo(b, typeof(Byte[]));
MemoryStream logo = new MemoryStream(ba);

LinkedResource companyImage = new LinkedResource(logo);
companyImage.ContentId = "companyLogo";
mailitem.HTMLBody += "<img src=\"cid:companyLogo\">";

但是,它无法在邮件正文中显示,而是“带红色x的空框”。你能给我一些想法吗?

2 个答案:

答案 0 :(得分:0)

使用Attachment.PropertyAccessor创建附件并设置PR_ATTACH_CONTENT_ID属性(DASL名称&#34; http://schemas.microsoft.com/mapi/proptag/0x3712001F&#34;)。

您的HTML正文(MailItem.HTMLBody属性)需要通过cid引用该图像附件:

img src =&#34; cid:xyz&#34;

其中xyz是PR_ATTACH_CONTENT_ID属性的值。

查看包含OutlookSpy的现有邮件(单击IMessage按钮)。

attachment = mailitem.Attachments.Add("c:\temp\MyPicture.jpg")
attachment.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001F", "MyId1")
mailitem.HTMLBody = "<html><body>Test image <img src=""cid:MyId1""></body></html>"

答案 1 :(得分:-1)

也许你可以试试这个。

string htmlBody = "<html><body><h1>Picture</h1><br><img src=\"cid:filename\"></body></html>";
 AlternateView avHtml = AlternateView.CreateAlternateViewFromString
    (htmlBody, null, MediaTypeNames.Text.Html);

var fileName = Guid.NewGuid.ToString();
var path = Path.Combine(
    Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)),
    fileName);
File.WriteAllBytes(path, Properties.Resources.Pic);

 LinkedResource inline = new LinkedResource(path, MediaTypeNames.Image.Jpeg); //Jpeg or something
 inline.ContentId = Guid.NewGuid().ToString();
 avHtml.LinkedResources.Add(inline);

 MailMessage mail = new MailMessage();
 mail.AlternateViews.Add(avHtml);

 Attachment att = new Attachment(filePath);
 att.ContentDisposition.Inline = true;

 mail.From = from_email;
 mail.To.Add(data.email);
 mail.Subject = "Here is your subject;
 mail.Body = String.Format(
            "Here is the previous HTML Body" +
            @"<img src=""cid:{0}"" />", inline.ContentId);

 mail.IsBodyHtml = true;
 mail.Attachments.Add(att);
  1. 无需将图片更改为内存流
  2. 为方便使用,请将您的电子邮件内容作为HTML
  3. 您可以在上面的代码中找到
  4. 您也可以参考this link