jacko10101
jacko10101

Reputation: 21

C# Embed an image in an outlook email

I am trying to send emails with the same logo on it every time but I cannot seem to get any image to appear, the code I have done is as follows:

Outlook.Application oApp = new Outlook.Application();
            Outlook._MailItem oMailItem = (Outlook._MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);

            String attachmentDisplayName = "MyAttachment";
            string imageSrc = "C:\\Users\\Test\\Pictures\\image.jfif";
            Outlook.Attachment oAttach = oMailItem.Attachments.Add(imageSrc, Outlook.OlAttachmentType.olByValue, null, attachmentDisplayName);

            string imageContentid = "someimage.jpg";
            oAttach.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001E", imageContentid);
            oMailItem.HTMLBody = String.Format(
                "<body>Hello,<br><br>This is an example of an embedded image:<br><br><img src=\"cid:{0}\"><br><br>Regards,<br>Tarik</body>",
                imageContentid);

            oMailItem.To = textBox1.Text;
            oMailItem.Subject = textBox3.Text;

What am I doing wrong here?

Upvotes: 0

Views: 1579

Answers (1)

Eugene Astafiev
Eugene Astafiev

Reputation: 49397

Your code looks good. But I've noticed the following image format used in the code:

image.jfif

I'd recommend checking any other file format like PNG, JPEG.

You may find the PNG, GIF, or JPEG? Which is the Best Image Format for Email? article helpful.


The following code works like a charm on my side:

 Attachment attachment = newMail.Attachments.Add(
     @"E:\Pictures\image001.jpg"
    , OlAttachmentType.olEmbeddeditem
    , null
    , "Some image display name"
    );

   string imageCid = "image001.jpg@123";

   attachment.PropertyAccessor.SetProperty(
     "http://schemas.microsoft.com/mapi/proptag/0x3712001E"
    , imageCid
    );

   newMail.HTMLBody = String.Format(
     "<body><img src=\"cid:{0}\"></body>"
    , imageCid
    );

You may also try to change the second parameter passed to the Attachments.Add method in the following way:

Outlook.Attachment oAttach = oMailItem.Attachments.Add(imageSrc, Outlook.OlAttachmentType.olEmbeddeditem, null, attachmentDisplayName);

Pass the OlAttachmentType.olEmbeddeditem instead.

Upvotes: 1

Related Questions