C # Attaching System.Drawing.Image to Email

Is there a way to connect System.Drawing.Image to an email without saving, then grab it from a saved path.

Now I create an image and save it. Then I send an email:

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 { } 

Is it possible to transfer the System.Drawing.Image file directly to mail.Attachments.Add ()?

+6
source share
2 answers

You cannot pass Image directly to the attachment, but you can skip the file system by simply saving the image to a MemoryStream and then providing a MemoryStream the attachment constructor:

 var stream = new MemoryStream(); image.Save(stream, ImageFormat.Jpeg); stream.Position = 0; mail.Attachments.Add(new Attachment(stream, "image/jpg")); 
+12
source

In theory, you can convert the image to a MemoryStream, and then add the stream as an attachment. It will look like this:

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

Then you can use the following

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

Now that you have the stream, you can add it as an attachment:

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

Literature:

System.Drawing.Image for C # thread

C # email object for streaming to application

+5
source

All Articles