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

时间:2014-02-10 21:27:46

标签: c# image email email-attachments memorystream

有没有办法将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
                {

                }

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

2 个答案:

答案 0 :(得分:15)

您无法将Image直接传递给附件,但只需将图片保存到MemoryStream,然后将MemoryStream提供给var stream = new MemoryStream(); image.Save(stream, ImageFormat.Jpeg); stream.Position = 0; mail.Attachments.Add(new Attachment(stream, "image/jpg")); 即可跳过文件系统。附件构造函数:

{{1}}

答案 1 :(得分: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;
}

然后您可以使用以下

var stream = myImage.ToStream(ImageFormat.Gif);

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

mail.Attachments.Add(new Attachment(stream, "myImage.gif", "image/gif" ));

参考文献:

System.Drawing.Image to stream C#

c# email object to stream to attachment