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

非 Y 不嫁゛ 提交于 2020-01-06 21:10:30

问题


I have a couple of images stored in visual studio project Resources folder, and I have to load them and display on the outlook mail body. Here it is the code:

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\">";

However, it cannot display on the mail body but a ‘empty box with red x’. Can you give me some ideas?


回答1:


Create an attachment and set the PR_ATTACH_CONTENT_ID property (DASL name "http://schemas.microsoft.com/mapi/proptag/0x3712001F") using Attachment.PropertyAccessor.

Your HTML body (MailItem.HTMLBody property) would then need to reference that image attachment through the cid:

img src="cid:xyz"

where xyz is the value of the PR_ATTACH_CONTENT_ID property.

Look at an existing message with OutlookSpy (click IMessage button).

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>"



回答2:


Maybe you can try this.

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. No need to change your picture to memory stream
  2. For easy use, please do your content of e-mail to be HTML
  3. You can find in the code above

You can refer to this link too



来源:https://stackoverflow.com/questions/30906039/how-to-add-images-from-resources-folder-as-attachment-and-embed-into-outlook-mai

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!