C#将System.Drawing.Image附加到电子邮件

Jus*_*inV 8 c# email memorystream image email-attachments

有没有办法将System.Drawing.Image附加到电子邮件而不保存它,然后从保存的路径中抓取它.

现在我正在创建图像并保存它.然后我发送电子邮件:

MailMessage mail = new MailMessage();
                string _body = "body"

                mail.Body = _body;
                string _attacmentPath;
                if (iP.Contains(":"))
                    _attacmentPath = (@"path1");//, System.Net.Mime.MediaTypeNames.Application.Octet));
                else
                    _attacmentPath = @"path2");
                mail.Attachments.Add(new Attachment(_attacmentPath, System.Net.Mime.MediaTypeNames.Application.Octet));
                mail.To.Add(_imageInfo.VendorEmail);
                mail.Subject = "Rouses' PO # " + _imageInfo.PONumber.Trim();
                mail.From = _imageInfo.VendorNum == 691 ? new MailAddress("email", "") : new MailAddress("email", "");
                SmtpClient server = null;
                mail.IsBodyHtml = true;
                mail.Priority = MailPriority.Normal; 
                server = new SmtpClient("server");
                try
                {

                    server.Send(mail);
                }
                catch
                {

                }
Run Code Online (Sandbox Code Playgroud)

无论如何直接将System.Drawing.Image传递给mail.Attachments.Add()?

Dan*_*Dan 16

您无法Image直接传递给附件,但只需将图像保存到a MemoryStream,然后将其提供MemoryStream给附件构造函数即可跳过文件系统:

var stream = new MemoryStream();
image.Save(stream, ImageFormat.Jpeg);
stream.Position = 0;

mail.Attachments.Add(new Attachment(stream, "image/jpg"));
Run Code Online (Sandbox Code Playgroud)


Ono*_*dai 5

理论上,您可以将Image转换为MemoryStream,然后将该流添加为附件.它会是这样的:

public static Stream ToStream(this Image image, ImageFormat formaw) {
  var stream = new System.IO.MemoryStream();
  image.Save(stream, formaw);
  stream.Position = 0;
  return stream;
}
Run Code Online (Sandbox Code Playgroud)

然后您可以使用以下内容

var stream = myImage.ToStream(ImageFormat.Gif);
Run Code Online (Sandbox Code Playgroud)

现在您已拥有该流,您可以将其添加为附件:

mail.Attachments.Add(new Attachment(stream, "myImage.gif", "image/gif" ));
Run Code Online (Sandbox Code Playgroud)

参考文献:

System.Drawing.Image流C#

c#将对象流式传输到附件