Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/image/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#将System.Drawing.Image附加到电子邮件_C#_Image_Email_Email Attachments_Memorystream - Fatal编程技术网

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

C#将System.Drawing.Image附加到电子邮件,c#,image,email,email-attachments,memorystream,C#,Image,Email,Email Attachments,Memorystream,是否有任何方法可以在不保存System.Drawing.Image的情况下将其附加到电子邮件,然后从保存的路径中获取它 现在我正在创建图像并保存它。然后,我发送电子邮件,其中包含: MailMessage mail = new MailMessage(); string _body = "body" mail.Body = _body; string _attacmentPath;

是否有任何方法可以在不保存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()?

理论上,您可以将映像转换为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" ));
参考资料:


您不能将
映像直接传递给附件,但您可以跳过文件系统,只需将映像保存到
内存流
,然后将
内存流
提供给附件构造函数:

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

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

+1-您的代码比我使用的代码更紧凑、更干净。=)谢谢,这很有效,我试了几次才意识到我必须在name参数的末尾添加“.jpg”!