开发者

When attaching jpeg to SMTP mail message, why is the image "blank" when I receive it? What is wrong with this code?

开发者 https://www.devze.com 2023-02-16 08:02 出处:网络
开发者_JS百科I have the following code which attaches a jpeg to an email. System.Net.Mime.ContentType contentType = new System.Net.Mime.ContentType();

开发者_JS百科I have the following code which attaches a jpeg to an email.

System.Net.Mime.ContentType contentType = new System.Net.Mime.ContentType();
contentType.MediaType = System.Net.Mime.MediaTypeNames.Image.Jpeg;
contentType.Name = "screen";

Attachment screenCapture = new Attachment(imageStream, contentType);

//this next line works, I checked the image on the hard drive so I know the jpeg is ok
File.WriteAllBytes("c:\\somecoolimage.jpeg", imageStream.ToArray());

mail.Attachments.Add(screenCapture);

smtp.Send(mail);

However, when I get the email with the attachment in my email, it has 0 bytes. What am I doing wrong here?


Perhaps you've left imageStream positioned at the end of the data instead of at the start? (I'm assuming it's a MemoryStream.) Try this:

imageStream.Position = 0;
Attachment screenCapture = new Attachment(imageStream, contentType);

(MemoryStream.ToArray ignores the current position of the stream, but I suspect that Attachment doesn't.)

0

精彩评论

暂无评论...
验证码 换一张
取 消