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

How to add images from resources folder as attachment and embed into outlook mail body in C#

我有几个图像存储在 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的空框’。你能给我一些想法吗?

也许你可以试试这个。

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. 你可以在上面的代码中找到

你也可以参考this link

创建附件并使用 Attachment.PropertyAccessor.SetProperty.

设置 PR_ATTACH_CONTENT_ID 属性(DASL 名称 "http://schemas.microsoft.com/mapi/proptag/0x3712001F"

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

<img src="cid:xyz">

其中 xyzPR_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>";