jstedfast / MailKit

A cross-platform .NET library for IMAP, POP3, and SMTP.

Home Page:http://www.mimekit.net

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to transfer an "inline" image via SmtpClient.Send

AdvancedNotifier opened this issue · comments

I'm trying to send a message with an inline image. To do this, I'm using the BodyBuilder with the following code:

var stream = new FileStream(linkedResource.LocalFilename, FileMode.Open);
var mimePart = new MimePart()
{
    Content = new MimeContent(stream),
    ContentId = linkedResource.ContentId,
    ContentTransferEncoding = ContentEncoding.Base64,
    FileName = linkedResource.Filename,
};
mimePart.ContentDisposition.IsAttachment = false;
mimePart.ContentType.MediaType = HtmlParserHelper.GetImageContentTypeByFile(linkedResource.LocalFilename);
builder.LinkedResources.Add(mimePart;

Unfortunately, the image will be transffered as an attachment. The received mail shows the following headers for this image:

Content-Type: image/png/octet-stream;
	name=449a0b24-fabc-4cab-8c48-a0995b6c5de1.png
Content-Id: <d5316e0e5fc04362a7086deae753804f@xyz>
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
	filename=449a0b24-fabc-4cab-8c48-a0995b6c5de1.png

The Content-Disposition is still an attachment, even I set IsAttachment to false.

What is the correct way to tell the MimePart to be sent as inline?

Thanks a lot for your answer.

If you are going to use a BodyBuilder, just do this:

var mimePart = builder.LinkedResources.Add(linkedResource.LocalFilename);
mimePart.ContentDisposition.Disposition = ContentDisposition.Inline;

Also, the following line of code is creating an invalid Content-Type header:

mimePart.ContentType.MediaType = HtmlParserHelper.GetImageContentTypeByFile(linkedResource.LocalFilename);

... so don't do that. Pay special attention to the ContentType class. It has a Media Type and a MediaSubtype. The string returned by your HtmlParserHelper contains both values separated by a / which means you end up with an invalid mime-type like image/png/octet-stream.

Ok, your solution is very easy, thanks a lot for it.

But I still get these headers:

Content-Type: image/png/octet-stream;
	name=449a0b24-fabc-4cab-8c48-a0995b6c5de1.png
Content-Id: <d5316e0e5fc04362a7086deae753804f@xyz>
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
	filename=449a0b24-fabc-4cab-8c48-a0995b6c5de1.png

... so it's still an attachment and not inline.

Those headers are definitely NOT from the code snippet that I pasted, they are produced by your old code.

Yes, my mistake. Sorry.